Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slider runs, Delete Cell, Origin Id in run code #15

Merged
merged 3 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions zt_backend/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .request import Request
from .request import Request, ComponentRequest, DeleteRequest
from .response import Response
from .notebook import Notebook
from .components.slider import Slider

__all__ = ['Request', 'Response', 'Slider', 'Notebook']
__all__ = ['Request', 'Response', 'Slider', 'Notebook', 'ComponentRequest', 'DeleteRequest']
2 changes: 1 addition & 1 deletion zt_backend/models/components/slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def validate_color(cls, color):

@field_validator('value')
def get_value_from_global_state(cls, value, values):
id = values.get('id') # Get the id if it exists in the field values
id = values.data['id'] # Get the id if it exists in the field values
try:
if id and id in component_values: # Check if id exists in global_state
return component_values[id] # Return the value associated with id in global_state
Expand Down
2 changes: 1 addition & 1 deletion zt_backend/models/components/zt_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class ZTComponent(BaseModel):
id: str = Field(description="Unique id for a component")
variable_name: str = Field('fake', description="Optional variable name associated with a component")

@field_validator('id',mode='before')
@field_validator('id', mode='before')
def validate_unique_component_id(cls, id):
if context_globals['exec_mode'] and id in created_components:
raise Exception("Component ID is not unique")
Expand Down
3 changes: 2 additions & 1 deletion zt_backend/models/generate_schema.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from zt_backend.models import *
from fastapi.encoders import jsonable_encoder
import json

def generate_json(model, name):
Expand All @@ -8,6 +7,8 @@ def generate_json(model, name):

def generate_schema():
generate_json(Request, 'request')
generate_json(ComponentRequest, 'component_request')
generate_json(DeleteRequest, 'delete_request')
generate_json(Response, 'response')
generate_json(Slider, 'slider')
generate_json(Notebook, 'notebook')
27 changes: 7 additions & 20 deletions zt_backend/models/request.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,15 @@
from pydantic import BaseModel
from pydantic import BaseModel, Field
from typing import List, Dict, Union
from zt_backend.models.components.slider import Slider
from zt_backend.models.components.zt_component import ZTComponent

# def deserialize_component(data: Dict[str, Any]) -> ZTComponent:
# component_map = {
# "v-slider": Slider,
# # add other component types here
# }
# component_class = data.get("component")
# if component_class not in component_map:
# raise ValueError(f"Invalid component class: {component_class}")
# return component_map[component_class].model_validate(data)

class CodeRequest(BaseModel):
id: str
code: str


class Request(BaseModel):
originId: str = Field('id')
cells: List[CodeRequest]
components: Dict[str, Union[str, bool, int]]


class Cell(BaseModel):
code: str
defined_names: List[str]
Expand All @@ -34,9 +21,9 @@ class Cell(BaseModel):
class CodeDict(BaseModel):
cells: Dict[str, Cell]

class ComponentRequest(BaseModel):
componentId: str
componentValue: Union[str, bool, int]

# @root_validator(pre=True)
# def deserialize_components(cls, values):
# components = values.get('components', [])
# values['components'] = [deserialize_component(comp) for comp in components]
# return values
class DeleteRequest(BaseModel):
cellId: str
12 changes: 11 additions & 1 deletion zt_backend/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ def runcode(request: request.Request):
globalStateUpdate(run_response=response)
return response

@router.post("/api/component_run")
def runcode(request: request.ComponentRequest):
print(request)

@router.post("/api/create_cell")
def create_cell():
createdCell = notebook.CodeCell(
Expand All @@ -41,6 +45,10 @@ def create_cell():
globalStateUpdate(newCell=createdCell)
return createdCell

@router.post("/api/delete_cell")
def delete_cell(deleteRequest: request.DeleteRequest):
globalStateUpdate(deletedCell=deleteRequest.cellId)

@router.get("/api/notebook")
def get_notebook():
return get_notebook()
Expand All @@ -50,10 +58,12 @@ def get_notebook():
notebook_data = toml.load(project_file)
return notebook.Notebook(**notebook_data)

def globalStateUpdate(newCell: notebook.CodeCell=None, run_request: request.Request=None, run_response: response.Response=None):
def globalStateUpdate(newCell: notebook.CodeCell=None, deletedCell: str=None, run_request: request.Request=None, run_response: response.Response=None):
zt_notebook = get_notebook()
if newCell is not None:
zt_notebook.cells[newCell.id] = newCell
if deletedCell is not None:
del zt_notebook.cells[deletedCell]
if run_request is not None:
for requestCell in run_request.cells:
zt_notebook.cells[requestCell.id].code = requestCell.code
Expand Down
24 changes: 19 additions & 5 deletions zt_frontend/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
<v-container v-for="codeCell in notebook.cells" >
<CodeComponent
:cellData = codeCell
@runCode="runCode"/>
@runCode="runCode"
@componentValueChange="componentValueChange"
@deleteCell="deleteCell"/>
</v-container>
<v-toolbar color="secondary">
<v-btn small color="primary" @click="createCodeCell">Add Code Cell</v-btn>
<v-spacer></v-spacer>
<v-spacer/>
<v-btn small color="primary">Add Markdown Cell</v-btn>
</v-toolbar>
</v-main>
Expand All @@ -25,6 +27,8 @@
<script lang="ts">
import axios from 'axios';
import { Request, CodeRequest } from './types/request';
import { ComponentRequest } from './types/component_request';
import { DeleteRequest } from './types/delete_request';
import { Response } from './types/response';
import { Notebook, CodeCell } from './types/notebook';
import CodeComponent from '@/components/CodeComponent.vue';
Expand All @@ -45,18 +49,17 @@ export default {
},

methods: {
async runCode() {
async runCode(originId: string) {
const cellRequests: CodeRequest[] = []
const requestComponents: { [key: string]: any } = {};
for (let key in this.notebook.cells){
const cellRequest: CodeRequest = {id: key, code: this.notebook.cells[key].code}
for (const c of this.notebook.cells[key].components){
requestComponents[c.id] = c.value
}
//requestComponents.push.apply(requestComponents, this.notebook.cells[key].components)
cellRequests.push(cellRequest)
}
const request: Request = { cells: cellRequests, components: requestComponents }
const request: Request = { originId: originId, cells: cellRequests, components: requestComponents }
const axiosResponse = await axios.post(import.meta.env.VITE_BACKEND_URL + 'api/runcode', request)
const response: Response = axiosResponse.data
for (const cellResponse of response.cells){
Expand All @@ -65,6 +68,11 @@ export default {
}
},

async componentValueChange(componentId: string, newValue: any){
const componentRequest: ComponentRequest = {componentId: componentId, componentValue: newValue}
const axiosResponse = await axios.post(import.meta.env.VITE_BACKEND_URL + 'api/component_run', componentRequest)
},

navigateToApp(){
console.log('navigate')
},
Expand All @@ -73,6 +81,12 @@ export default {
const response = await axios.post(import.meta.env.VITE_BACKEND_URL + 'api/create_cell');
const cell: CodeCell = response.data
this.notebook.cells[cell.id] = cell
},

async deleteCell(cellId: string){
const deleteRequest: DeleteRequest = {cellId: cellId}
await axios.post(import.meta.env.VITE_BACKEND_URL + 'api/delete_cell', deleteRequest);
delete this.notebook.cells[cellId]
}
}
}
Expand Down
23 changes: 14 additions & 9 deletions zt_frontend/src/components/CodeComponent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@
}"
>
</ace-editor>
<!-- Run Button -->
<v-btn color="primary" class="run-button" @click="runCode">Run</v-btn>
<v-toolbar>
<v-btn color="primary" @click="runCode">Run</v-btn>
<v-spacer/>
<v-btn small color="primary" @click="deleteCell">Delete Cell</v-btn>
</v-toolbar>
<!-- Render Components -->
<div v-for="component in cellData.components" :key="component.id">
<component :is="component.component" v-bind="component" v-model="component.value"></component>
<component :is="component.component" v-bind="component" v-model="component.value" @end="handleValueChange($event, component.id)"></component>
</div>
<div class="text-p">{{cellData.output}}</div>
</v-card>
Expand All @@ -33,7 +36,7 @@ import 'ace-builds/src-noconflict/snippets/python';
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/theme-dracula';
import { VSlider } from 'vuetify/lib/components/index.mjs';
import { CodeCell } from '@/types/notebook';
import { CodeCell, ZTComponent } from '@/types/notebook';


export default {
Expand All @@ -49,7 +52,13 @@ export default {
},
methods: {
runCode(){
this.$emit('runCode');
this.$emit('runCode', this.cellData.id);
},
handleValueChange(newValue:any, componentId: string){
this.$emit('componentValueChange', componentId, newValue );
},
deleteCell(){
this.$emit('deleteCell', this.cellData.id);
}
},
}
Expand All @@ -63,10 +72,6 @@ export default {
margin-bottom: 20px;
}

.run-button {
margin-bottom: 20px;
}

.formatted-code {
white-space: pre-wrap;
padding: 15px;
Expand Down
15 changes: 15 additions & 0 deletions zt_frontend/src/types/component_request.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/

export type Componentid = string;
export type Componentvalue = string | boolean | number;

export interface ComponentRequest {
componentId: Componentid;
componentValue: Componentvalue;
[k: string]: unknown;
}
13 changes: 13 additions & 0 deletions zt_frontend/src/types/delete_request.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/* eslint-disable */
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/

export type Cellid = string;

export interface DeleteRequest {
cellId: Cellid;
[k: string]: unknown;
}
2 changes: 2 additions & 0 deletions zt_frontend/src/types/request.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
* and run json-schema-to-typescript to regenerate this file.
*/

export type Originid = string;
export type Id = string;
export type Code = string;
export type Cells = CodeRequest[];

export interface Request {
originId: Originid;
cells: Cells;
components: Components;
[k: string]: unknown;
Expand Down
28 changes: 28 additions & 0 deletions zt_schema/component_request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"properties": {
"componentId": {
"title": "Componentid",
"type": "string"
},
"componentValue": {
"anyOf": [
{
"type": "string"
},
{
"type": "boolean"
},
{
"type": "integer"
}
],
"title": "Componentvalue"
}
},
"required": [
"componentId",
"componentValue"
],
"title": "ComponentRequest",
"type": "object"
}
13 changes: 13 additions & 0 deletions zt_schema/delete_request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"properties": {
"cellId": {
"title": "Cellid",
"type": "string"
}
},
"required": [
"cellId"
],
"title": "DeleteRequest",
"type": "object"
}
2 changes: 1 addition & 1 deletion zt_schema/notebook.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"type": "string"
},
"variable_name": {
"default": null,
"default": "fake",
"description": "Optional variable name associated with a component",
"title": "Variable Name",
"type": "string"
Expand Down
5 changes: 5 additions & 0 deletions zt_schema/request.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
}
},
"properties": {
"originId": {
"title": "Originid",
"type": "string"
},
"cells": {
"items": {
"$ref": "#/$defs/CodeRequest"
Expand All @@ -46,6 +50,7 @@
}
},
"required": [
"originId",
"cells",
"components"
],
Expand Down
2 changes: 1 addition & 1 deletion zt_schema/response.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"type": "string"
},
"variable_name": {
"default": null,
"default": "fake",
"description": "Optional variable name associated with a component",
"title": "Variable Name",
"type": "string"
Expand Down
2 changes: 1 addition & 1 deletion zt_schema/slider.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"type": "string"
},
"variable_name": {
"default": null,
"default": "fake",
"description": "Optional variable name associated with a component",
"title": "Variable Name",
"type": "string"
Expand Down