Skip to content

Commit

Permalink
chore(imporoved-valdiations-and-spacing-in-cells): Added Vlaidations …
Browse files Browse the repository at this point in the history
…in different components, improvded spacing in cell and added wide mode option in settings
  • Loading branch information
priyakanabar-crest committed Dec 27, 2024
1 parent fcb5071 commit 4782ecf
Show file tree
Hide file tree
Showing 15 changed files with 119 additions and 34 deletions.
5 changes: 4 additions & 1 deletion zt_backend/models/api/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,7 @@ class MoveItemRequest(BaseModel):
sourcePath: str
targetId: str
sourceId: str
targetPath: str
targetPath: str

class WideModelRequest(BaseModel):
wideMode: bool
8 changes: 7 additions & 1 deletion zt_backend/models/components/layout.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pydantic import BaseModel,Field
from pydantic import BaseModel,Field, validator
from typing import ForwardRef,Union
from typing import List
from zt_backend.models.state.user_state import UserContext
Expand All @@ -11,6 +11,12 @@ class Column(BaseModel):
components: List[Union[str,"Row"]] = Field([], description="List of component IDs and rows that belong to this column, rendered in order")
width: Union[int,bool] = Field(False, description="Width of the column. It can be a number 1-12 and by default is automatically calculated")

@validator('width')
def width_must_be_between_1_and_12(cls, v):
if isinstance(v, int) and not 1 <= v <= 12:
raise ValueError('Column width must be between 1 and 12 got {v}')
return v

def __init__(__pydantic_self__, *args, **data):
if args:
data['components'] = args[0]
Expand Down
11 changes: 7 additions & 4 deletions zt_backend/models/components/number_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ class NumberInput(ZTComponent):
hint: Optional[str] = Field(
"Press Enter to Submit", description="Hint text for the number input"
)
value: Union[int, float, None] = Field(0, description="The input number value")
label: Optional[str] = Field("", description="Label for the number input")
readonly: Optional[bool] = Field(
False, description="If true, the input is read-only"
Expand All @@ -26,6 +25,7 @@ class NumberInput(ZTComponent):
1, description="The number to increment or decrement by"
)
style: Optional[str] = Field("", description="CSS style to apply to the component")
value: Union[int, float, None] = Field(0, description="The input number value")
triggerEvent: str = Field(
None, description="Trigger event to send code to the backend"
)
Expand All @@ -40,9 +40,12 @@ def get_value_from_global_state(cls, value, values):
if (
execution_state and id and id in execution_state.component_values
): # Check if id exists in global_state
return execution_state.component_values[
id
] # Return the value associated with id in global_state
stored_value = execution_state.component_values[id]
if isinstance(stored_value, str):
if '.' in stored_value:
return float(stored_value)
else:
return int(stored_value)
except Exception as e:
e
return value # If id doesn't exist in global_state, return the original value
14 changes: 10 additions & 4 deletions zt_backend/models/components/range_slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@ class RangeSlider(ZTComponent):
"""A slider component that allows a user to select a range of values"""

component: str = Field("v-range-slider", description="Vue component name")
value: List[Union[int, float]] = Field(
[0, 100], description="Current value range of the slider"
)
min: Union[int, float] = Field(0, description="Minimum value of the slider")
max: Union[int, float] = Field(100, description="Maximum value of the slider")
step: Union[int, float] = Field(1, gt=0, description="Step increment of the slider")
Expand All @@ -30,14 +27,23 @@ class RangeSlider(ZTComponent):
True, description="Determines if the slider has rounded edges"
)
style: Optional[str] = Field("", description="CSS style to apply to the component")
value: List[Union[int, float]] = Field(
[0, 100], description="Current value range of the slider"
)
triggerEvent: str = Field(
"end", description="Trigger event for when to trigger a run"
)

def __init__(self, **data):
# Set initial value to [min, max]
data['value'] = [data.get('min', 0), data.get('max', 100)]
super().__init__(**data)


@field_validator("color")
def validate_color(cls, color):
return validate_color(color)

@validator("value", always=True) # TODO: debug and replace with field validator
def get_value_from_global_state(cls, value, values):
id = values["id"] # Get the id if it exists in the field values
Expand Down
1 change: 1 addition & 0 deletions zt_backend/models/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ class Notebook(BaseModel):
notebookId: str = Field(default=str(uuid4())) # Added notebook UUID
cells: OrderedDict[str, CodeCell]
userId: str
wideMode: bool = Field(False)


class Dependency(BaseModel):
Expand Down
8 changes: 7 additions & 1 deletion zt_backend/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
)
from zt_backend.models import notebook
from zt_backend.models.api import request
from zt_backend.models.state import notebook_state
from zt_backend.runner.execute_code import execute_request
from zt_backend.config import settings
from zt_backend.utils.completions import get_code_completions
Expand All @@ -26,6 +27,7 @@
from zt_backend.utils.notebook import (
get_notebook_request,
get_request_base,
save_notebook,
save_worker,
websocket_message_sender,
)
Expand Down Expand Up @@ -99,6 +101,11 @@ def env_data():
def base_path():
return settings.user_name + "/" + settings.project_name

@router.post("/api/wide_mode_update")
async def update_wide_mode(request: request.WideModelRequest):
notebook_state.zt_notebook.wideMode = request.wideMode
await save_notebook()
return {"status": "success"}

@router.websocket("/ws/run_code")
async def run_code(websocket: WebSocket):
Expand Down Expand Up @@ -261,7 +268,6 @@ def cell_reactivity(cellReactivityRequest: request.CellReactivityRequest):
app_state.save_queue.put_nowait({"cellReactivity": cellReactivityRequest})
logger.debug("Cell reactivity request completed")


@router.post("/api/expand_code")
def expand_code(expandCodeRequest: request.ExpandCodeRequest):
if app_state.run_mode == "dev":
Expand Down
2 changes: 1 addition & 1 deletion zt_backend/utils/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def write_notebook():
with tmp_uuid_file.open("w", encoding="utf-8") as project_file:
# Write notebookId
project_file.write(
f'notebookId = "{notebook_state.zt_notebook.notebookId}"\nnotebookName = "{notebook_state.zt_notebook.notebookName}"\n\n'
f'notebookId = "{notebook_state.zt_notebook.notebookId}"\nnotebookName = "{notebook_state.zt_notebook.notebookName}"\nwideMode = "{notebook_state.zt_notebook.wideMode}"\n\n'
)

for cell_id, cell in notebook_state.zt_notebook.cells.items():
Expand Down
2 changes: 0 additions & 2 deletions zt_dev_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ def app(
if os.name == "nt":
backend_cmd = ["start"] + backend_cmd

os.environ["LOCAL_URL"] = f"http://localhost:{port}"

backend_process = subprocess.Popen(backend_cmd, shell=(os.name == "nt"))
os.chdir("zt_frontend")
Expand Down Expand Up @@ -110,7 +109,6 @@ def notebook(
if os.name == "nt":
backend_cmd = ["start"] + backend_cmd

os.environ["LOCAL_URL"] = f"http://localhost:{port}"

backend_process = subprocess.Popen(backend_cmd, shell=(os.name == "nt"))
os.chdir("zt_frontend")
Expand Down
27 changes: 27 additions & 0 deletions zt_frontend/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,25 @@
</v-btn>
</template>
</v-tooltip>
<v-menu
v-if="$devMode && !isAppRoute"
:close-on-content-click="false"
>
<template v-slot:activator="{ props }">
<v-btn
:icon="`ztIcon:${ztAliases.settings}`"
v-bind="props"
></v-btn>
</template>
<v-list bg-color="bluegrey-darken-4">
<v-list-item>
<template v-slot:prepend>
<v-switch v-model="reactiveMode"></v-switch>
</template>
<v-list-item-title>Reactive Mode</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
<!-- <v-btn
v-if="$devMode && !isAppRoute"
:icon="`ztIcon:${ztAliases.message}`"
Expand Down Expand Up @@ -1084,6 +1103,14 @@ export default {
timer.start(startTimer);
}
},
async updateWideMode(value:boolean) {
// Send update to backend
await axios.post(import.meta.env.VITE_BACKEND_URL + "api/wide_mode_update", {
wideMode: value
});
this.notebook.wideMode = value;
}
},
};
</script>
Expand Down
8 changes: 6 additions & 2 deletions zt_frontend/src/components/Cell.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
:thickness="4"
></v-divider>
<div class="content">
<header class="header">
<header v-if="isFocused" class="header">
<div class="click-edit" v-if="isDevMode && keepCodeInAppModel">
<div class="click-edit__show-text" v-if="!editingCellName">
<div class="loading-wrapper">
Expand Down Expand Up @@ -336,7 +336,11 @@ const props = defineProps({
cellHasOutput:{
type: Boolean,
default:false
}
},
isFocused: {
type: Boolean,
default: false,
},
});
const emits = defineEmits<{
(e: "delete"): void;
Expand Down
10 changes: 7 additions & 3 deletions zt_frontend/src/components/CodeCellManager.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
@createCodeCell="e => createCodeCell('', e)"
/>
</v-container>
<v-container
<v-container
:class="[
'cell-container',
{ 'cell-container--app': !$devMode || isAppRoute }
{ 'cell-container--app': !$devMode || isAppRoute },
{ 'cell-container--wide': notebook.wideMode }
]"
v-for="codeCell in notebook.cells"
>
Expand Down Expand Up @@ -57,7 +58,6 @@ import PackageComponent from "@/components/PackageComponent.vue";
import AddCell from '@/components/AddCell.vue'
import { PropType } from "vue";
import { useRoute } from "vue-router";
import { callbackify } from "util";
export default {
Expand Down Expand Up @@ -262,6 +262,10 @@ export default {
&--app {
padding-bottom: 0;
}
&--wide {
max-width: 100% !important;
margin: 0% !important;
}
}
.cm-editor {
height: auto !important;
Expand Down
7 changes: 5 additions & 2 deletions zt_frontend/src/components/CodeComponent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
:cell-has-output="hasCellContent"
:currentlyExecutingCell="currentlyExecutingCell"
:isCodeRunning="isCodeRunning"
:is-focused="isFocused"
:is-dev-mode="$devMode && !isAppRoute && !isMobile"
@play="runCode(false, '', '')"
@delete="deleteCell"
Expand Down Expand Up @@ -538,8 +539,10 @@ export default {
handleFocus() {
this.isFocused = true;
this.runLint = true;
if (this.view) {
this.view.dispatch({});
if (this.getEditorView()) {
if (this.view) {
this.view.dispatch({});
}
}
},
handleBlur() {
Expand Down
21 changes: 18 additions & 3 deletions zt_frontend/src/components/EditorComponent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,18 @@
:hide-cell="(cellData.hideCell as boolean)"
:cell-name="(cellData.cellName as string)"
:cell-has-output="true"
:is-focused="isFocused"
@save="saveCell"
@delete="deleteCell"
@addCell="(e) => createCell(e)"
>
@addCell="(e) => createCell(e)" >
<template v-slot:code>
<tiny-editor
v-if="$devMode && !isAppRoute && !isMobile"
v-model="cellData.code"
:init="editorConfig"
@keyUp="saveCell"
@focus="onEditorFocus"
@blur="onEditorBlur"
/>
</template>
<template v-slot:outcome v-if="($devMode && isAppRoute) || !$devMode">
Expand Down Expand Up @@ -98,6 +100,7 @@ export default {
{ title: "Text" },
],
editor: null,
isFocused: false,
};
},
computed: {
Expand Down Expand Up @@ -264,6 +267,18 @@ isCursorAtEnd(editor: any): boolean {
}
});
},
handleFocus(focus: boolean) {
console.log('EditorComponent handleFocus:', focus);
this.isFocused = focus;
},
onEditorFocus() {
console.log('TinyMCE editor focused');
this.handleFocus(true);
},
onEditorBlur() {
console.log('TinyMCE editor blurred');
this.handleFocus(false);
}
},
};
</script>
Expand All @@ -277,4 +292,4 @@ isCursorAtEnd(editor: any): boolean {
.tox-tinymce {
border: none !important;
}
</style>
</style>
10 changes: 10 additions & 0 deletions zt_frontend/src/components/MarkdownComponent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
:hide-cell="(cellData.hideCell as boolean)"
:cell-name="(cellData.cellName as string)"
:cell-has-output=hasCellContent
:is-focused="isFocused"
@delete="deleteCell"
@save="saveCell"
@addCell="e => createCell(e)"
Expand All @@ -22,6 +23,8 @@
:extensions="extensions"
@keyup="saveCell"
@ready="handleReady"
@focus="onEditorFocus"
@blur="onEditorBlur"
/>
</template>
<template v-slot:outcome>
Expand Down Expand Up @@ -138,6 +141,13 @@ export default {
getEditorView() {
return this.view || null;
},
onEditorFocus() {
this.isFocused = true;
},
onEditorBlur() {
this.isFocused = false;
},
},
};
</script>
Expand Down
Loading

0 comments on commit 4782ecf

Please sign in to comment.