├── .gitignore ├── .prettierrc ├── src ├── css │ ├── draft-mode.css │ ├── cursor.css │ ├── hole.css │ ├── tooltip.css │ ├── notification.css │ ├── construct-doc.css │ ├── index.css │ ├── console.css │ ├── suggestion-menu.css │ ├── accordion.css │ ├── messages.css │ ├── editor.css │ ├── cascaded-menu.css │ ├── doc-box.css │ └── toolbox.css ├── docs │ ├── num.json │ ├── list-item.json │ ├── true.json │ ├── false.json │ ├── mult.json │ ├── div.json │ ├── sub.json │ ├── str.json │ ├── assign-add.json │ ├── find.json │ ├── range.json │ ├── assign-div.json │ ├── assign-mult.json │ ├── assign.json │ ├── join.json │ ├── split.json │ ├── input.json │ ├── replace.json │ ├── not.json │ ├── randint.json │ ├── f-str-item.json │ ├── assign-sub.json │ ├── floor-div.json │ ├── mod.json │ ├── f-str.json │ ├── to-int.json │ ├── add.json │ ├── choice.json │ ├── in.json │ ├── else.json │ ├── not-in.json │ ├── import.json │ ├── print.json │ ├── len.json │ ├── list-element-assign.json │ ├── comp-gt.json │ ├── comp-eq.json │ ├── comp-lt.json │ ├── list-index.json │ ├── comp-lte.json │ ├── list-append.json │ ├── comp-ne.json │ ├── comp-gte.json │ ├── list-literal.json │ ├── and.json │ ├── or.json │ ├── if.json │ ├── to-str.json │ ├── add-var.json │ ├── elif.json │ ├── while.json │ ├── break.json │ └── for.json ├── logger │ ├── requests.ts │ ├── user.ts │ └── analytics.ts ├── syntax-tree │ ├── callback.ts │ ├── tree-array.ts │ ├── body.ts │ ├── type-checker.ts │ └── scope.ts ├── editor │ ├── data-types.ts │ ├── draft.ts │ ├── cursor.ts │ ├── event-stack.ts │ ├── accordion.ts │ ├── hole.ts │ ├── doc-box.ts │ ├── editor.ts │ └── action-filter.ts ├── pyodide-ts │ └── pyodide-ui.ts ├── pyodide-js │ ├── load-pyodide.js │ └── pyodide-controller.js ├── index.ts ├── utilities │ ├── text-enhance.ts │ └── util.ts ├── index.html ├── messages │ ├── notifications.ts │ └── message-controller.ts └── suggestions │ └── construct-doc.ts ├── .vscode └── settings.json ├── readme.md ├── tsconfig.json ├── package.json └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | lib 4 | logs 5 | *.log 6 | npm-debug.log* 7 | .env 8 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "useTabs": false, 4 | "printWidth": 120 5 | } 6 | -------------------------------------------------------------------------------- /src/css/draft-mode.css: -------------------------------------------------------------------------------- 1 | .draftModeLine { 2 | background-color: rgba(255, 0, 0, 0.3); 3 | position: absolute; 4 | pointer-events: none; 5 | border-radius: 5px; 6 | } 7 | 8 | .draftModeLine.fixed { 9 | background-color: rgba(30, 255, 0, 0.3); 10 | } 11 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": ["elif", "randint", "consts", "pyodide", "builtins"], 3 | "editor.formatOnSave": true, 4 | "editor.codeActionsOnSave": { 5 | "source.organizeImports": true 6 | }, 7 | "editor.tabSize": 4 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/css/cursor.css: -------------------------------------------------------------------------------- 1 | .custom-selection-cursor { 2 | position: absolute; 3 | background: #a4e2ff94; 4 | mix-blend-mode: multiply; 5 | 6 | transition: 0.1s ease-in; 7 | pointer-events: none; 8 | z-index: 5; 9 | border-radius: 8.5px; 10 | 11 | /* this should match the border-width of hole in hole.css */ 12 | padding: 1px; 13 | } 14 | -------------------------------------------------------------------------------- /src/docs/num.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "123", 3 | "tooltip": { 4 | "title": "Insert a Number", 5 | "body": "Inserts a number and edit its value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-num", 11 | "example": "age = 21\nprint(age)\nprint(21)" 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /src/docs/list-item.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "List Item", 3 | "tooltip": { 4 | "title": "Insert List Element", 5 | "body": "Inserts a new empty element inside a list." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-list-item", 11 | "example": "a = []\nb = [1, 2]\nc = [1, 2, 3]" 12 | } 13 | ], 14 | "search-queries": ["comma", "list item"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/true.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "true", 3 | "tooltip": { 4 | "title": "Insert True", 5 | "body": "Inserts a True boolean value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-true", 11 | "example": "if True :\n\tprint(\"will print\")\n\nif False :\n\tprint(\"will not print\")" 12 | } 13 | ], 14 | "search-queries": ["true", "boolean"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/false.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "false", 3 | "tooltip": { 4 | "title": "Insert False", 5 | "body": "Inserts a False boolean value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-false", 11 | "example": "if False :\n\tprint(\"will not print\")\n\nif True :\n\tprint(\"will print\")" 12 | } 13 | ], 14 | "search-queries": ["false", "boolean"] 15 | } 16 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # CodeStruct 2 | A new text-based environment that helps beginners transition into conventional text-based programming environments. 3 | 4 | Features: 5 | - avoids syntax errors 6 | - enables structured text-based editing 7 | - provides learning moments on invalid attempts 8 | - provides hints and visual descriptions 9 | 10 | Authoring code with CodeStruct: 11 | - Cursor-aware Toolbox 12 | - Suggestion Menus and Autocomplete 13 | - Draft Mode Editing 14 | -------------------------------------------------------------------------------- /src/docs/mult.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "multiply", 3 | "tooltip": { 4 | "title": "Insert Multiplication", 5 | "body": "Multiplies the values to the left and right of the operator." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-mul-vars", 11 | "example": "a = 2\nb = 5\nprint((b * a))" 12 | } 13 | ], 14 | "search-queries": ["multiply numbers", "multiply"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/div.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "divide", 3 | "tooltip": { 4 | "title": "Insert Division", 5 | "body": "Divides the values to the left of the operator by the right value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-div-two-vars", 11 | "example": "a = 2\nb = 10\nprint((b / a))" 12 | } 13 | ], 14 | "search-queries": ["divide", "division", "divide numbers"] 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "experimentalDecorators": true, 4 | "sourceMap": true, 5 | "module": "commonjs", 6 | "moduleResolution": "node", 7 | "target": "ES6", 8 | "outDir": "./dist", 9 | "lib": ["dom", "ES6"], 10 | "types": [], 11 | "baseUrl": "./node_modules", 12 | "jsx": "preserve", 13 | "typeRoots": ["node_modules/@types"], 14 | "resolveJsonModule": true 15 | }, 16 | "include": ["./src/**/*"], 17 | "exclude": ["node_modules"] 18 | } 19 | -------------------------------------------------------------------------------- /src/docs/sub.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "subtract", 3 | "tooltip": { 4 | "title": "Insert Subtraction", 5 | "body": "Subtracts the value to the right of the operator from the value to the left." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-sub-vars", 11 | "example": "a = 20\nb = 10\nprint((a - b))" 12 | } 13 | ], 14 | "search-queries": ["subtract numbers", "subtraction", "deduct"] 15 | } 16 | -------------------------------------------------------------------------------- /src/logger/requests.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosPromise } from "axios"; 2 | import { LogEvent } from "./analytics"; 3 | 4 | const baseUrl = "https://nova.majeed.cc/api"; 5 | 6 | export function sendEventsBatch(events: Array, user: string, app: string): AxiosPromise { 7 | return axios({ 8 | method: "post", 9 | url: `${baseUrl}/events/batch`, 10 | data: { 11 | user, 12 | app, 13 | events, 14 | }, 15 | }); 16 | } 17 | -------------------------------------------------------------------------------- /src/docs/str.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "text", 3 | "tooltip": { 4 | "title": "Insert a Text", 5 | "body": "Inserts an editable text that is wrapped by double quotes." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-assign-str", 11 | "example": "fruit = \"apple\"\nprint(fruit)\nprint(\"apple\")" 12 | } 13 | ], 14 | "search-queries": ["create text", "create string", "empty string", "empty text"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/assign-add.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Add to Variable", 3 | "tooltip": { 4 | "title": "Add Value to Variable", 5 | "body": "Adds the value on the right-hand side of the += sign to the specified variable and stores the result in the variable." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-var-sum-by-val", 11 | "example": "a = 2\na += 2\nprint(a)" 12 | } 13 | ], 14 | "search-queries": ["add to variable"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/find.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "find(txt: text)", 3 | "tooltip": { 4 | "title": "Call Find Method", 5 | "body": "Finds the first occurrence of the input's textual value in the text." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-find-1", 11 | "example": "name = \"Zimmer\"\nindexOfE = name.find(\"e\")\nprint(indexOfE)" 12 | } 13 | ], 14 | "search-queries": ["search text", "find text", "find string"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/range.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "range(end: number)", 3 | "tooltip": { 4 | "title": "Create Iterable Sequence", 5 | "body": "Generates a sequence of numbers from 0 to the provided input. Usually used with a for loop." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-range", 11 | "example": "for i in range(10):\n\tprint(i)" 12 | } 13 | ], 14 | "search-queries": ["range", "sequence", "iterate", "for loop"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/assign-div.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Divide a Variable", 3 | "tooltip": { 4 | "title": "Divide Variable by Value", 5 | "body": "Divides the variable by the value given on the right-hand side of the /= sign and stores the result back in the variable." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-var-divide-by-value", 11 | "example": "a = 10\na /= 2\nprint(a)" 12 | } 13 | ], 14 | "search-queries": ["divide variable"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/assign-mult.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Multiply a Variable", 3 | "tooltip": { 4 | "title": "Multiply Variable by Value", 5 | "body": "Multiplies the variable by the value on the right-hand side of the *= sign and stores the result back in the variable." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-var-mul-by-val", 11 | "example": "a = 5\na *= 2\nprint(a)" 12 | } 13 | ], 14 | "search-queries": ["multiply variable"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/assign.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Assign to Variable", 3 | "tooltip": { 4 | "title": "Update Value of Variable", 5 | "body": "Allows assigning a new value to an existing variable." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-assign-val-var-twice", 11 | "example": "a = 123\nprint(a)\na=321\nprint(a)" 12 | } 13 | ], 14 | "search-queries": ["set", "assign", "assign variable", "set variable", "update value variable"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/join.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "join(elements: list[text])", 3 | "tooltip": { 4 | "title": "Call Join Method", 5 | "body": "Uses this text as a separator to join a list of values together into a new text." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-join-1", 11 | "example": "names = [\"Anna\", \"John\", \"Peter\"]\njoinedNames = \"-\".join(names)\nprint(joinedNames)" 12 | } 13 | ], 14 | "search-queries": ["join string", "join text"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/split.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "split(separator: text)", 3 | "tooltip": { 4 | "title": "Call Split Method", 5 | "body": "Splits the text into a list of components based on the input (as a separator)." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-split", 11 | "example": "name = \"Split-this-text-on-hyphen\"\nsplitName = name.split(\"-\")\nprint(splitName)" 12 | } 13 | ], 14 | "search-queries": ["split", "split text", "split string"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/input.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "input(prompt: text)", 3 | "tooltip": { 4 | "title": "Ask User for Textual Input", 5 | "body": "Displays a message that prompts the user to enter some text. The entered text will be returned." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-input-1", 11 | "example": "name = input(\"Hi! What’s your name?\")\nprint(name)" 12 | } 13 | ], 14 | "search-queries": ["input", "prompt", "text", "user", "ask input", "ask user"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/replace.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "replace(old: text, new: text)", 3 | "tooltip": { 4 | "title": "Call Replace Method", 5 | "body": "Replaces all occurrences of the first input with the value of the second input in the text." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-replace", 11 | "example": "name = \"John\"\nname = name.replace(\"oh\", \"a\")\nprint(name)" 12 | } 13 | ], 14 | "search-queries": ["replace", "replace text", "replace string"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/not.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "not", 3 | "tooltip": { 4 | "title": "Not Operator", 5 | "body": "Flips the truth value of an expression. True becomes False, and False becomes True." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-not", 11 | "example": "a = 2\nb = 2\nif not (a == b):\n\tprint(\"Will not print.\")\n\nif not (b != a):\n\tprint(\"b is equal to a\")" 12 | } 13 | ], 14 | "search-queries": ["negate", "not", "logical", "boolean", "opposite"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/randint.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "randint(min: number, max: number)", 3 | "tooltip": { 4 | "title": "Generate a Random Number", 5 | "body": "Returns a randomly generated number from the given range. Needs to be imported from the random module." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-randint", 11 | "example": "a = randint(0, 10)\nprint(a)" 12 | } 13 | ], 14 | "search-queries": ["random number", "random integer", "randint", "random between"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/f-str-item.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "formatted text item", 3 | "tooltip": { 4 | "title": "Formatted Text Item", 5 | "body": "Converts the item to its textual value. Can only be used inside a formatted text (f'')." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-f-str-item", 11 | "example": "age = 16\nname = \"Alex\"\nprint(f'My name is {name} and I am {age} years old')" 12 | } 13 | ], 14 | "search-queries": ["formatted string item", "formatted text item"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/assign-sub.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Subtract from Variable", 3 | "tooltip": { 4 | "title": "Subtract Value from Variable", 5 | "body": "Subtracts the value on the right-hand side of the -= sign from the specified variable and stores the result back in the variable." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-var-sub-by-val", 11 | "example": "a = 5\na -= 2\nprint(a)" 12 | } 13 | ], 14 | "search-queries": ["subtract from variable", "deduct from variable"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/floor-div.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "floor division", 3 | "tooltip": { 4 | "title": "Insert Floor Division", 5 | "body": "Performs integer division (remainder is discarded and always result is always rounded down) between the values to the left and right of the operator." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-floor-div", 11 | "example": "a = 2\nb = 7\nprint((b / a))" 12 | } 13 | ], 14 | "search-queries": ["divide numbers", "divide integer", "divide floor"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "modulo", 3 | "tooltip": { 4 | "title": "Insert Modulo", 5 | "body": "Calculates the remainder of the division between the values to the left and right of the operator." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-modulo", 11 | "example": "print((29 % 5)) # prints 4\nprint((28 % 5)) # prints 3\nprint((27 % 5)) # prints 2\nprint((26 % 5)) # prints 1\nprint((25 % 5)) # prints 0" 12 | } 13 | ], 14 | "search-queries": ["modulo", "remainder"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/f-str.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "formatted text", 3 | "tooltip": { 4 | "title": "Insert Formattable Text", 5 | "body": "Inserts an editable, formattable text; used along with the {} operator to include non-static values and variables inside the text." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-f-str-1", 11 | "example": "age = 16\nname = \"Alex\"\nprint(f'My name is {name} and I am {age} years old')" 12 | } 13 | ], 14 | "search-queries": ["formatted string", "formatted text"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/to-int.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "int(object: string)", 3 | "tooltip": { 4 | "title": "Converts Text to Number", 5 | "body": "Converts a number text to an actual number. Extremely useful when trying to input numbers from the user." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-int-cast", 11 | "example": "a = \"2\"\nb = \"5\"\ntext_add = a + b\nnumber_add = int(a) + int(b)" 12 | } 13 | ], 14 | "search-queries": ["integer cast", "number convert", "convert to number", "convert to integer"] 15 | } 16 | -------------------------------------------------------------------------------- /src/syntax-tree/callback.ts: -------------------------------------------------------------------------------- 1 | import { CodeConstruct } from "./ast"; 2 | 3 | export class Callback { 4 | static counter: number = 0; 5 | callback: (code: CodeConstruct) => void; 6 | callerId: string; 7 | 8 | constructor(callback: (code: CodeConstruct) => void) { 9 | this.callback = callback; 10 | this.callerId = "caller-id-" + Callback.counter; 11 | Callback.counter++; 12 | } 13 | } 14 | 15 | export enum CallbackType { 16 | change, 17 | replace, 18 | delete, 19 | fail, 20 | focusEditableHole, 21 | showAvailableVars, 22 | onFocusOff, 23 | } 24 | -------------------------------------------------------------------------------- /src/editor/data-types.ts: -------------------------------------------------------------------------------- 1 | import { EditActionType, InsertActionType } from "./consts"; 2 | 3 | export class EditAction { 4 | type: EditActionType; 5 | data: any; 6 | 7 | constructor(type: EditActionType, data?: any) { 8 | this.type = type; 9 | this.data = data; 10 | } 11 | } 12 | 13 | export class InsertActionData { 14 | cssId: string; 15 | action: InsertActionType; 16 | data: any; 17 | 18 | constructor(cssId: string, type: InsertActionType, data: any = {}) { 19 | this.cssId = cssId; 20 | this.action = type; 21 | this.data = data; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/docs/add.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "add", 3 | "tooltip": { 4 | "title": "Insert Addition", 5 | "body": "Adds the values to the left and right of the operator." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-sum-numbers", 11 | "example": "a = 2\nb = 5\nprint((a + b))" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-sum-strings", 16 | "example": "a = \"hello\"\nb = \"world\"\nprint((a + \" \" + b))" 17 | } 18 | ], 19 | "search-queries": ["add", "sum"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/choice.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "choice(choices: list[any])", 3 | "tooltip": { 4 | "title": "Insert Choice from List", 5 | "body": "Randomly selects and returns an item from the given list. Needs to be imported from the random module." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-choice", 11 | "example": "from random import choice\n\nif choice([1, 2, 3, 4, 5, 6]) == 6:\n\tprint(\"Rolled Six!\")" 12 | } 13 | ], 14 | "search-queries": ["choice", "random choice", "choose randomly from list", "select randomly from array"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/in.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Inside?", 3 | "tooltip": { 4 | "title": "Inside?", 5 | "body": "Returns True if the left item is inside the right item; returns False otherwise." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-in-list", 11 | "example": "from random import randint\na = randint(1, 10)\nb = [1, 2, 3, 4, 5]\nif a in b:\n\tprint(\"a is inside b\")\n\nif a not in b:\n\tprint(\"a is not inside b\")" 12 | } 13 | ], 14 | "search-queries": ["in list", "inside list", "is inside list", "check inside list", "check list includes"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/else.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "else statement", 3 | "tooltip": { 4 | "title": "Insert Else Statement", 5 | "body": "Can be used after an if or an elif statement. will execute its block of code when the if and the elif statements were not true" 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-else-1", 11 | "example": "a = 2\nif a > 3:\n\tprint(3)\nelif a > 4:\n\tprint(4)\nelif a == 5:\n\tprint(5)\nelif a > 6:\n\tprint(6)\nelse:\n\tprint(\"None of the above are true.\")" 12 | } 13 | ], 14 | "search-queries": ["else", "otherwise", "if"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/not-in.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Not Inside?", 3 | "tooltip": { 4 | "title": "Not Inside?", 5 | "body": "Returns True if the left item is not inside the right item; returns False otherwise." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-not-inside-rand-list", 11 | "example": "from random import randint\na = randint(1, 10)\nb = [1, 2, 3, 4, 5]\nif a in b:\n\tprint(\"a is inside b\")\n\nif a not in b:\n\tprint(\"a is not inside b\")" 12 | } 13 | ], 14 | "search-queries": ["not in", "not inside list", "not within list", "does not include"] 15 | } 16 | -------------------------------------------------------------------------------- /src/docs/import.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Import Module", 3 | "tooltip": { 4 | "title": "Imports A Function", 5 | "body": "Loads a particular function from a module." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-import-randint-and-choice", 11 | "example": "from random import randint\nfrom random import choice" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-import-randint-use", 16 | "example": "from random import randint\nprint(randint(1, 6))" 17 | } 18 | ], 19 | "search-queries": ["import module", "import random"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/print.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "print(message: any)", 3 | "tooltip": { 4 | "title": "Display Text in Console", 5 | "body": "Displays the textual value of its input in the console." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-print-num-str", 11 | "example": "print(123)\nprint(\"Hello World!\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-print-var", 16 | "example": "a = \"abc\"\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["output", "say", "print", "print output", "console", "write", "see output"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/len.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "len(iterable: list/text)", 3 | "tooltip": { 4 | "title": "Get Length of List or Text", 5 | "body": "Returns the number of items in an object, or the number of characters in a text." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-len-1", 11 | "example": "greeting = \"Hello World!\"\na = len(greeting)\nprint(a)" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-len-2", 16 | "example": "items = [1, 2, 3]\na = len(items)\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["length of list", "length of string", "length of text"] 20 | } 21 | -------------------------------------------------------------------------------- /src/pyodide-ts/pyodide-ui.ts: -------------------------------------------------------------------------------- 1 | export const CONSOLE_TXT_CLASS = "consoleTxt"; 2 | export const CONSOLE_ERR_TXT_CLASS = "consoleErrTxt"; 3 | export const CONSOLE_WARN_TXT_CLASS = "consoleWarnTxt"; 4 | 5 | export const addTextToConsole = (consoleId: string, text: string, styleClass: string = CONSOLE_TXT_CLASS) => { 6 | const outputArea = document.getElementById(consoleId); 7 | const textEm = document.createElement("div"); 8 | textEm.classList.add(CONSOLE_TXT_CLASS); 9 | textEm.classList.add(styleClass); 10 | textEm.textContent = text; 11 | outputArea.appendChild(textEm); 12 | }; 13 | 14 | export const clearConsole = (consoleId: string) => { 15 | document.getElementById(consoleId).innerHTML = ""; 16 | }; 17 | -------------------------------------------------------------------------------- /src/docs/list-element-assign.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "List Element Assignment", 3 | "tooltip": { 4 | "title": "", 5 | "body": "" 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-list-el-assign-1", 11 | "example": "a = [1, 2, 3]\na[2] = 4\nprint(a)" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-list-el-assign-2", 16 | "example": "a = [1, 2, 3]\na[1] = \"cat\"\nprint(a)" 17 | } 18 | ], 19 | "search-queries": [ 20 | "assign element at index", 21 | "change value list index", 22 | "update item at index", 23 | "set value list index" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /src/docs/comp-gt.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Is Greater Than?", 3 | "tooltip": { 4 | "title": "Is Greater Than?", 5 | "body": "Compares two values. Returns True if the left value is greater than the right value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-gt-1", 11 | "example": "a = 2\nb = 3\nif b > a:\n\tprint(\"b is greater than a\")\n\nif a > b:\n\tprint(\"a is greater to b\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-gt-2", 16 | "example": "a = 1\nb = 5\nwhile b > a:\n\ta += 1\nprint(a)\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["compare greater than", "compare", "check greater than"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/comp-eq.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Is Equal?", 3 | "tooltip": { 4 | "title": "Is Equal?", 5 | "body": "Compares two values. Returns True if they are equal; returns False otherwise." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-is-eq-1", 11 | "example": "a = 2\nb = 3\nif a == c:\n\tprint(\"a is equal to c\")\n\nif b == a:\n\tprint(\"This will not print because the condition is false.\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-is-eq-2", 16 | "example": "a = 5\nb = 5\nwhile a == b:\n\ta += 1\nprint(a)\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["compare equal", "check equal", "are equal"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/comp-lt.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Is Less Than?", 3 | "tooltip": { 4 | "title": "Is Less Than?", 5 | "body": "Compares two values. Returns True if the left value is less than the right value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-lt-1", 11 | "example": "a = 2\nb = 3\nif a < b:\n\tprint(\"a is less than b\")\n\nif c < a:\n\tprint(\"This will not print because the condition is false.\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-lt-2", 16 | "example": "a = 1\nb = 5\nwhile a < b:\n\ta += 1\nprint(a)\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["compare", "compare less than", "check less than"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/list-index.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "List Element Access", 3 | "tooltip": { 4 | "title": "Access List Element", 5 | "body": "Adds a list accessor to a list (or a text) to access an element of the list at the provided index." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-list-index-1", 11 | "example": "a = [1, 2, 3]\nprint(a[0])" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-list-index-2", 16 | "example": "a = [1, 2, 3]\nif a[1] == 2:\n\tprint(\"The second element of the list is equal to 2.\")" 17 | } 18 | ], 19 | "search-queries": ["access list item", "access list element", "access list element at index"] 20 | } 21 | -------------------------------------------------------------------------------- /src/pyodide-js/load-pyodide.js: -------------------------------------------------------------------------------- 1 | import { nova, runBtnToOutputWindow } from "../index"; 2 | import { addTextToConsole, CONSOLE_TXT_CLASS } from "../pyodide-ts/pyodide-ui"; 3 | 4 | const exportPromise = new Promise(async ($export) => { 5 | const module = await Promise.resolve({ 6 | pyodideController: loadPyodide({ 7 | indexURL: "https://cdn.jsdelivr.net/pyodide/v0.18.1/full/", 8 | stdout: (text) => { 9 | let consoleId = runBtnToOutputWindow.get(nova.globals.lastPressedRunButtonId) ?? "outputDiv"; 10 | document.getElementById("runCodeBtn").classList.remove("disabled"); 11 | 12 | if (text != "Python initialization complete") addTextToConsole(consoleId, text, CONSOLE_TXT_CLASS); 13 | }, 14 | }), 15 | }); 16 | $export(module); 17 | }); 18 | 19 | export default exportPromise; 20 | -------------------------------------------------------------------------------- /src/docs/comp-lte.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "is less than or equal?", 3 | "tooltip": { 4 | "title": "Is Less Than or Equal?", 5 | "body": "Compares two values. Returns True if the left value is less than or equal to the right value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-leq-1", 11 | "example": "a = 2\nb = 3\n c = 2\n if a <= b:\n\tprint(\"a is less than b\")\n\nif c <= a:\n\tprint(\"c is equal to a\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-leq-2", 16 | "example": "a = 1\nb = 5\nwhile a <= b:\n\ta += 1\nprint(a)\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["less than or equal", "compare", "compare less than or equal", "check"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/list-append.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "append(element: object)", 3 | "tooltip": { 4 | "title": "Append Element to List", 5 | "body": "Appends (adds to the end of) a new element to the list." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-append-1", 11 | "example": "a = [1, 2, 3]\na.append(4)\nprint(a)" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-append-2", 16 | "example": "print([1, 2, 3].append(4))" 17 | } 18 | ], 19 | "search-queries": [ 20 | "add to list", 21 | "append to list", 22 | "insert into list", 23 | "add to end list", 24 | "append to end list", 25 | "insert end list" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /src/editor/draft.ts: -------------------------------------------------------------------------------- 1 | import { HoverMessage } from "../messages/messages"; 2 | import { Statement } from "../syntax-tree/ast"; 3 | import { Module } from "../syntax-tree/module"; 4 | 5 | export class DraftRecord { 6 | code: Statement; 7 | warning: HoverMessage; 8 | 9 | private module: Module; //no point in instantiating the editor itself because it will require an instance of Module anyway 10 | 11 | constructor(code: Statement, module: Module, txt?: string) { 12 | this.code = code; 13 | this.module = module; 14 | this.warning = this.module.messageController.addHoverMessage(code, {}, txt ?? ""); 15 | this.code.message = this.warning; 16 | } 17 | 18 | removeMessage() { 19 | this.module.messageController.removeMessageFromConstruct(this.code); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/docs/comp-ne.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Is Not Equal?", 3 | "tooltip": { 4 | "title": "Is Not Equal?", 5 | "body": "Compares two values. Returns True if they are not equal; returns False otherwise." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-not-equal-1", 11 | "example": "a = 2\nb = 3\nif a != b:\n\tprint(\"a is not equal to b\")\n\nif c != a:\n\tprint(\"This will not print because the condition is false.\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-not-equal-2", 16 | "example": "a = 1\nb = 5\nwhile a != b:\n\ta += 1\nprint(a)\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["not equal", "compare not equal", "not equal to", "are not equal"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/comp-gte.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "is greater than or equal?", 3 | "tooltip": { 4 | "title": "Is Greater Than or Equal?", 5 | "body": "Compares two values. Returns True if the left value is greater than or equal to the right value." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-gte-1", 11 | "example": "a = 2\nb = 3\n c = 2\n if b >= a:\n\tprint(\"b is greater than a\")\n\nif c >= a:\n\tprint(\"c is equal to a\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-gt-1", 16 | "example": "a = 1\nb = 5\nwhile b >= a:\n\ta += 1\nprint(a)\nprint(a)" 17 | } 18 | ], 19 | "search-queries": ["compare greater than or equal", "compare", "check greater than or equal"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/list-literal.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "List", 3 | "tooltip": { 4 | "title": "Insert Editable List", 5 | "body": "Inserts an empty list. Press comma before or after each item to add a new empty item." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-list-1", 11 | "example": "a = []\nprint(a) # a is an empty list\na = [1, 2, 3]\nprint(a) # a is a list with three items" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-list-1", 16 | "example": "a = [\"cat\", \"dog\", \"parrot\"]\nb = [1, \"cat\", true]\nc = [1, [1, \"dog\"], \"cat\", [true]]" 17 | } 18 | ], 19 | "search-queries": ["empty list", "create empty list", "create list", "array", "create empty array"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/and.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "and", 3 | "tooltip": { 4 | "title": "And Operator", 5 | "body": "Used to combine conditional expressions. Results in True if both the left and right expressions are True; returns False otherwise." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-and-four-cases", 11 | "example": "if (true and true):\n\tprint(true)\n\nif (true and false):\n\tprint(\"not true\")\n\nif (false and true):\n\tprint(\"still not true\")\n\nif (false and false):\n\tprint(\"also false\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-gt-and-gt", 16 | "example": "a = 5\nb = 7\nc=2\n\nif ((a > c) and (b > c)):\n\tprint(\"Both expressions are true.\")" 17 | } 18 | ], 19 | "search-queries": ["and", "both", "and operator"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/or.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "or", 3 | "tooltip": { 4 | "title": "Or Operator", 5 | "body": "Used to combine conditional expressions. Results in True as long as at least one of the left and right expressions is True; returns False otherwise." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-or-1", 11 | "example": "if (true or true):\n\tprint(true)\n\nif (true or false):\n\tprint(\"true\")\n\nif (false or true):\n\tprint(\"still true\")\n\nif (false or false):\n\tprint(\"false\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-or-2", 16 | "example": "a = 5\nb = 7\nc=2\n\nif ((a > c) and (b < c)):\n\tprint(\"Only the first expression is true.\")" 17 | } 18 | ], 19 | "search-queries": ["conditional", "or", "logical", "boolean", "one of"] 20 | } 21 | -------------------------------------------------------------------------------- /src/docs/if.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "if statement", 3 | "tooltip": { 4 | "title": "Insert If Statement", 5 | "body": "Will only execute the indented block of code below it when the condition is true" 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-if-1", 11 | "example": "a = 3\nif a < 10:\n\tprint(\"Success!\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-if-2", 16 | "example": "a = 3\nif a > 10:\n\tprint(\"Success!\")" 17 | }, 18 | { 19 | "type": "use-case", 20 | "title": "check the value of a variable", 21 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/6-if/", 22 | "max": 13, 23 | "extension": "PNG", 24 | "prefix": "Slide", 25 | "id": "check-val-variable" 26 | } 27 | ], 28 | "search-queries": ["if", "condition", "conditional", "choose", "path"] 29 | } 30 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import "./css/index.css"; 2 | import { Module } from "./syntax-tree/module"; 3 | 4 | // @ts-ignore 5 | self.MonacoEnvironment = { 6 | getWorkerUrl: function (moduleId, label) { 7 | if (label === "json") { 8 | return "./json.worker.bundle.js"; 9 | } 10 | 11 | if (label === "css" || label === "scss" || label === "less") { 12 | return "./css.worker.bundle.js"; 13 | } 14 | 15 | if (label === "html" || label === "handlebars" || label === "razor") { 16 | return "./html.worker.bundle.js"; 17 | } 18 | 19 | if (label === "typescript" || label === "javascript") { 20 | return "./ts.worker.bundle.js"; 21 | } 22 | 23 | return "./editor.worker.bundle.js"; 24 | }, 25 | }; 26 | 27 | // retrieveUser(); 28 | const nova = new Module("editor"); 29 | const runBtnToOutputWindow = new Map(); 30 | runBtnToOutputWindow.set("runCodeBtn", "outputDiv"); 31 | 32 | export { nova, runBtnToOutputWindow }; 33 | -------------------------------------------------------------------------------- /src/css/hole.css: -------------------------------------------------------------------------------- 1 | .hole { 2 | position: absolute; 3 | pointer-events: none; 4 | 5 | /* box-shadow: 0px 0px 3px 1px #00000029 inset; */ 6 | border: solid 1px #00000029; 7 | transition-property: background; 8 | transition-duration: 0.2s; 9 | 10 | border-radius: 5px; 11 | } 12 | 13 | .editableHole { 14 | /* box-shadow: 0px 0px 3px 1px #398dfab6 inset; */ 15 | border: solid 1px #398dfab6; 16 | } 17 | 18 | .validVarIdentifierHole { 19 | background-color: rgba(58, 223, 58, 0.3); 20 | } 21 | 22 | .draftVarIdentifierHole { 23 | background-color: rgb(255, 255, 230, 0.6); 24 | } 25 | 26 | .expression-hole { 27 | border-radius: 15px !important; 28 | } 29 | 30 | .text-editable-expr-hole { 31 | border-radius: 15px !important; 32 | border-style: dashed !important; 33 | } 34 | 35 | .empty-operator-hole { 36 | border-radius: 0 !important; 37 | } 38 | 39 | .identifier-hole { 40 | border-radius: 0 !important; 41 | border-style: dashed !important; 42 | } 43 | 44 | .errorTooltipHole { 45 | position: relative; 46 | top: 5px; 47 | } 48 | -------------------------------------------------------------------------------- /src/docs/to-str.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "str(object: any)", 3 | "body": [ 4 | { 5 | "paragraph": "Converts the passed object to a text object. Useful when comparing values of different types and one of them is a text value. This type of conversion is called a cast because it is temporary." 6 | }, 7 | { "example": "a = 2\nc = \"2\"\nprint(str(a) == c)" }, 8 | { 9 | "paragraph": "In the above example you would not be able to compare a to c before performing the conversion." 10 | } 11 | ], 12 | "tooltip": { 13 | "title": "Converts Anything to Text", 14 | "body": "Converts the passed object to its textual representation." 15 | }, 16 | "tips": [ 17 | { 18 | "type": "executable", 19 | "id": "ex-str-cast", 20 | "example": "a = 2\nc = \"2\"\nprint(str(a) == c)" 21 | } 22 | ], 23 | "search-queries": ["string cast", "text convert", "convert to string", "convert to text"] 24 | } 25 | -------------------------------------------------------------------------------- /src/docs/add-var.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Create/Reassign Variable", 3 | "tooltip": { 4 | "title": "Create Variable Assignment", 5 | "body": "Allows to store a value and give it a name to reference it by later." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-declare-print-var", 11 | "example": "name = \"John\"\nprint(name)" 12 | }, 13 | { 14 | "type": "quick", 15 | "text": "A variable is created the moment you first assign a value to it." 16 | }, 17 | { 18 | "type": "bullet-point", 19 | "title": "variable naming", 20 | "bullets": [ 21 | "Variable names can only contain letters, numbers, and underscores", 22 | "Variable names are case-sensitive (\"x\" and \"X\" are different)", 23 | "A variable name must start with a letter or the underscore character", 24 | "A variable name cannot start with a number" 25 | ] 26 | } 27 | ], 28 | "search-queries": ["create new variable", "variable", "var"] 29 | } 30 | -------------------------------------------------------------------------------- /src/css/tooltip.css: -------------------------------------------------------------------------------- 1 | .tooltip-top-container { 2 | width: 100%; 3 | background-color: black; 4 | color: #fff; 5 | text-align: center; 6 | border-radius: 6px; 7 | padding: 5px 0; 8 | position: absolute; 9 | z-index: 1; 10 | top: 150%; 11 | left: 50%; 12 | margin-left: -60px; 13 | } 14 | 15 | .tooltip-top-container::after { 16 | content: ""; 17 | position: absolute; 18 | bottom: 100%; 19 | left: 50%; 20 | margin-left: -5px; 21 | border-width: 5px; 22 | border-style: solid; 23 | border-color: transparent transparent black transparent; 24 | } 25 | 26 | .tooltip-left-container { 27 | width: 100%; 28 | background-color: black; 29 | color: #fff; 30 | text-align: center; 31 | border-radius: 6px; 32 | padding: 5px 0; 33 | position: absolute; 34 | z-index: 1; 35 | top: -5px; 36 | left: 110%; 37 | } 38 | 39 | .tooltip-left-container::after { 40 | content: ""; 41 | position: absolute; 42 | top: 50%; 43 | right: 100%; 44 | margin-top: -5px; 45 | border-width: 5px; 46 | border-style: solid; 47 | border-color: transparent black transparent transparent; 48 | } 49 | -------------------------------------------------------------------------------- /src/logger/user.ts: -------------------------------------------------------------------------------- 1 | const nameRegex = RegExp("^[a-zA-Z]+$"); 2 | 3 | let user: string; 4 | let isUserRetrieved: boolean = false; 5 | 6 | export function getUser(): string { 7 | if (isUserRetrieved) return user; 8 | else { 9 | retrieveUser(); 10 | 11 | return user; 12 | } 13 | } 14 | 15 | export function retrieveUser() { 16 | const storedUser = localStorage.getItem("user-id"); 17 | 18 | if (storedUser === null || storedUser === "null") { 19 | const name = getItemPrompt("your name").toLowerCase(); 20 | const lastName = getItemPrompt("your last name").toLowerCase(); 21 | user = `${name}-${lastName}`; 22 | localStorage.setItem("user-id", user); 23 | } else { 24 | user = storedUser; 25 | console.log("welcome back, " + user); 26 | } 27 | 28 | isUserRetrieved = true; 29 | } 30 | 31 | function getItemPrompt(item: string): string { 32 | let attempt: string | null; 33 | 34 | attempt = prompt(`please enter ${item} (just letters):`, ""); 35 | 36 | while (attempt === null || attempt === "" || nameRegex.test(attempt) === false || attempt.length < 2) { 37 | attempt = prompt(`try again. please just enter letters for ${item}:`, ""); 38 | } 39 | 40 | return attempt; 41 | } 42 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nova-editor", 3 | "version": "1.0.0", 4 | "description": "A new text-based environment that helps beginners transition into conventional text-based programming environments.", 5 | "keywords": [ 6 | "programming", 7 | "cs-education", 8 | "novice", 9 | "beginner", 10 | "editor" 11 | ], 12 | "author": "Majeed Kazemitaabar, Viktar Chyhir", 13 | "license": "GPL-3.0", 14 | "scripts": { 15 | "start": "webpack serve --config webpack.config.js --open", 16 | "build": "node node_modules/webpack/bin/webpack.js --progress" 17 | }, 18 | "dependencies": { 19 | "axios": "^0.24.0", 20 | "fuse.js": "^6.4.6", 21 | "monaco-editor": "^0.25.2" 22 | }, 23 | "devDependencies": { 24 | "@webpack-cli/serve": "^1.5.1", 25 | "css-loader": "^5.2.6", 26 | "file-loader": "^6.2.0", 27 | "html-webpack-plugin": "^5.3.2", 28 | "monaco-editor-webpack-plugin": "^4.0.0", 29 | "style-loader": "^3.0.0", 30 | "terser-webpack-plugin": "^5.1.4", 31 | "ts-loader": "^9.2.3", 32 | "typescript": "^4.4.2", 33 | "webpack": "^5.43.0", 34 | "webpack-cli": "^4.7.2", 35 | "webpack-dev-server": "^3.11.3" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const HtmlWebPackPlugin = require("html-webpack-plugin"); 3 | 4 | module.exports = { 5 | mode: "development", 6 | entry: { 7 | app: ["./src/index.ts", "./src/pyodide-js/load-pyodide.js", "./src/pyodide-js/pyodide-controller.js"], 8 | "editor.worker": "monaco-editor/esm/vs/editor/editor.worker.js", 9 | "json.worker": "monaco-editor/esm/vs/language/json/json.worker", 10 | "css.worker": "monaco-editor/esm/vs/language/css/css.worker", 11 | "html.worker": "monaco-editor/esm/vs/language/html/html.worker", 12 | "ts.worker": "monaco-editor/esm/vs/language/typescript/ts.worker" 13 | }, 14 | resolve: { 15 | extensions: [".ts", ".js"], 16 | }, 17 | output: { 18 | globalObject: "self", 19 | filename: "[name].bundle.js", 20 | path: path.resolve(__dirname, "dist"), 21 | }, 22 | module: { 23 | rules: [ 24 | { 25 | test: /\.ts?$/, 26 | use: "ts-loader", 27 | exclude: /node_modules/, 28 | }, 29 | { 30 | test: /\.css$/, 31 | use: ["style-loader", "css-loader"], 32 | }, 33 | { 34 | test: /\.ttf$/, 35 | use: ["file-loader"], 36 | }, 37 | ], 38 | }, 39 | plugins: [ 40 | new HtmlWebPackPlugin({ 41 | hash: true, 42 | template: "./src/index.html", 43 | filename: "./index.html", 44 | }) 45 | ], 46 | devtool: "inline-source-map" 47 | }; 48 | -------------------------------------------------------------------------------- /src/css/notification.css: -------------------------------------------------------------------------------- 1 | .notification-container { 2 | padding: 10px; 3 | border-radius: 6px; 4 | position: fixed; 5 | bottom: calc(30% + 25px); 6 | right: 25px; 7 | width: 450px; 8 | z-index: 9999; 9 | background-color: rgb(102 65 173 / 50%); 10 | font-family: Consolas, "Courier New", monospace; 11 | 12 | opacity: 0; 13 | transform: scale(0.75); 14 | } 15 | 16 | .notification-container .message { 17 | font-size: 17px; 18 | } 19 | 20 | .notification-container .message .code { 21 | background-color: #64a; 22 | border-radius: 4px; 23 | padding: 3px 5px; 24 | color: #fff; 25 | font-weight: bold; 26 | } 27 | 28 | .animate { 29 | transition: all 0.2s ease-in-out; 30 | opacity: 1; 31 | transform: scale(1); 32 | } 33 | 34 | .key-animation-container { 35 | margin-top: 10px; 36 | } 37 | 38 | .key-animation-container .key-span { 39 | display: inline-block; 40 | margin-right: 8px; 41 | padding: 5px 5px; 42 | border-radius: 4px; 43 | background-color: #0ff; 44 | font-size: 20px; 45 | font-weight: bold; 46 | } 47 | 48 | expr-hole { 49 | border-radius: 2px; 50 | margin: 0px 3px; 51 | min-width: 21px; 52 | height: 10px; 53 | display: inline-block; 54 | } 55 | 56 | id-hole { 57 | height: 10px; 58 | width: 8px; 59 | display: inline-block; 60 | } 61 | -------------------------------------------------------------------------------- /src/css/construct-doc.css: -------------------------------------------------------------------------------- 1 | .docParent { 2 | position: absolute; 3 | left: 200px; 4 | top: 200px; 5 | 6 | max-width: 50%; 7 | max-height: 30%; 8 | min-width: 40%; 9 | min-height: 20%; 10 | width: fit-content; 11 | height: fit-content; 12 | overflow-y: scroll; 13 | 14 | border-style: solid; 15 | border-width: 2px; 16 | border-color: grey; 17 | 18 | background-color: rgb(197, 197, 197); 19 | 20 | padding: 2px 2px 2px 2px; 21 | 22 | overflow-y: scroll; 23 | scrollbar-width: none; /* Firefox */ 24 | -ms-overflow-style: none; /* Internet Explorer 10+ */ 25 | } 26 | .docParent::-webkit-scrollbar { 27 | width: 0; 28 | height: 0; 29 | } 30 | 31 | .docTitle { 32 | padding: 2px; 33 | margin: 0px; 34 | border-bottom: solid 1px; 35 | border-color: black; 36 | } 37 | 38 | .docBody { 39 | padding-left: 1px; 40 | padding-right: 1px; 41 | padding-top: 1px; 42 | padding-bottom: 1px; 43 | font-size: 10pt; 44 | } 45 | 46 | .docImageParent { 47 | display: grid; 48 | grid-template-columns: 50% 50%; 49 | grid-template-rows: auto; 50 | column-gap: 10px; 51 | row-gap: 15px; 52 | margin-top: 10px; 53 | 54 | padding-right: 10px; 55 | padding-top: 2px; 56 | padding-bottom: 1px; 57 | } 58 | 59 | .docImage { 60 | max-width: 100%; 61 | max-height: 100%; 62 | min-width: 100%; 63 | min-height: 100%; 64 | } 65 | -------------------------------------------------------------------------------- /src/syntax-tree/tree-array.ts: -------------------------------------------------------------------------------- 1 | export interface TreeNode { 2 | index: number; 3 | root: any; 4 | value: T; 5 | } 6 | 7 | /** Every single item knows their own index, updated with every operation (e.g. splice, insert) */ 8 | export class TreeArray { 9 | private array: Array>; 10 | private root: any; 11 | 12 | constructor(root: any) { 13 | this.array = []; 14 | } 15 | 16 | private reIndex(from: number) { 17 | for (let i = from; i < this.array.length; i++) this.array[i].index = i; 18 | } 19 | 20 | push(element: TreeNode) { 21 | element.root = this.root; 22 | element.index = this.array.length; 23 | this.array.push(element); 24 | } 25 | 26 | insert(element: TreeNode, index: number) { 27 | element.root = this.root; 28 | element.index = index; 29 | this.array.splice(index, 0, element); 30 | this.reIndex(index + 1); 31 | } 32 | 33 | splice(start: number, deleteCount: number, replaceItems?: TreeNode[]): TreeNode[] { 34 | let deletedItems = this.array.splice(start, deleteCount, ...replaceItems); 35 | 36 | this.reIndex(start); 37 | 38 | return deletedItems; 39 | } 40 | 41 | get(index: number): TreeNode { 42 | if (index < this.array.length && index >= 0) return this.array[index]; 43 | 44 | console.error(`error while executing TreeArray.get(${index}) -> array.length is ${this.array.length}`); 45 | return null; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/utilities/text-enhance.ts: -------------------------------------------------------------------------------- 1 | export enum CSSClasses { 2 | identifier = "identifier", 3 | type = "type", 4 | keyword = "keyword", 5 | emphasize = "emph", 6 | other = "other", 7 | } 8 | 9 | export class TextEnhance { 10 | constructor() {} 11 | 12 | getStyledSpan(content: string, styleClass: string): string { 13 | return `${content}`; 14 | } 15 | 16 | getStyledSpanAtSubstrings(content: string, styleClass: string, matches: [][]): string { 17 | let finalHTML = ""; 18 | 19 | const startIndexToLength = []; 20 | for (const listOfMatches of matches) { 21 | for (const matchRecord of listOfMatches) { 22 | startIndexToLength.push([matchRecord[0], matchRecord[1] - matchRecord[0] + 1]); 23 | } 24 | } 25 | 26 | for (let i = 0; i < content?.length; i++) { 27 | if (startIndexToLength.length > 0 && i === startIndexToLength[0][0]) { 28 | let stringToAdd = ""; 29 | for (let j = i; j < i + startIndexToLength[0][1]; j++) { 30 | stringToAdd += content[j]; 31 | } 32 | 33 | finalHTML += this.getStyledSpan(stringToAdd, styleClass); 34 | i = startIndexToLength[0][0] + startIndexToLength[0][1] - 1; 35 | startIndexToLength.splice(0, 1); 36 | } else { 37 | finalHTML += content[i]; 38 | } 39 | } 40 | 41 | return finalHTML; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/docs/elif.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "elif statement", 3 | "tooltip": { 4 | "title": "Insert Elif Statement", 5 | "body": "Short for else-if; adds another case to an existing if statement. The `elif` will only run when previous `if` or `elif` statement is false" 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-elif-1", 11 | "example": "a = 3\nif a > 10:\n\tprint(\"a is larger than 10\")\nelif a < 10:\n\tprint(\"a is smaller than 10\")" 12 | }, 13 | { 14 | "type": "executable", 15 | "id": "ex-elif-2", 16 | "example": "a = 5\nif a > 3:\n\tprint(3)\nelif a > 4:\n\tprint(4)\nelif a == 5:\n\tprint(5)\nelif a > 6:\n\tprint(6)" 17 | }, 18 | { 19 | "type": "use-case", 20 | "title": "using elif after an if statement", 21 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/7-if-single-elif/", 22 | "max": 11, 23 | "extension": "PNG", 24 | "prefix": "Slide", 25 | "id": "elif-after-if" 26 | }, 27 | { 28 | "type": "use-case", 29 | "title": "using elif after another elif statement", 30 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/7-if-double-elif/", 31 | "max": 13, 32 | "extension": "PNG", 33 | "prefix": "Slide", 34 | "id": "elif-after-elif" 35 | } 36 | ], 37 | "search-queries": ["else if", "else", "else condition", "choose", "path", "elif"] 38 | } 39 | -------------------------------------------------------------------------------- /src/css/index.css: -------------------------------------------------------------------------------- 1 | @import url("doc-box.css"); 2 | @import url("editor.css"); 3 | @import url("toolbox.css"); 4 | @import url("cursor.css"); 5 | @import url("hole.css"); 6 | @import url("messages.css"); 7 | @import url("suggestion-menu.css"); 8 | @import url("construct-doc.css"); 9 | @import url("draft-mode.css"); 10 | @import url("cascaded-menu.css"); 11 | @import url("console.css"); 12 | @import url("notification.css"); 13 | @import url("tooltip.css"); 14 | @import url("accordion.css"); 15 | 16 | @import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@0,300;0,400;0,600;0,700;1,300;1,400;1,600&display=swap"); 17 | 18 | html { 19 | height: 100%; 20 | } 21 | 22 | body { 23 | margin: 0px; 24 | width: 100%; 25 | height: 100%; 26 | overflow: hidden; 27 | font-family: Source Sans Pro; 28 | } 29 | 30 | #editor-container { 31 | display: flex; 32 | height: 100%; 33 | } 34 | 35 | .button { 36 | color: #0d0c22; 37 | cursor: pointer; 38 | border-radius: 4px; 39 | display: flex; 40 | align-items: center; 41 | justify-content: center; 42 | opacity: 1; 43 | height: -webkit-fit-content; 44 | height: -moz-fit-content; 45 | height: fit-content; 46 | margin-right: 10px; 47 | font-size: 14px; 48 | padding: 10px 14px; 49 | width: -webkit-fit-content; 50 | width: -moz-fit-content; 51 | width: fit-content; 52 | border: solid 2px #fff; 53 | } 54 | 55 | .button.button-invalid { 56 | opacity: 0.4; 57 | cursor: not-allowed; 58 | border: solid 2px #c5c5c5; 59 | } 60 | 61 | .button.button-valid { 62 | font-weight: bold; 63 | } 64 | 65 | .button.button-draft-mode { 66 | background-color: rgb(255 254 195); 67 | } 68 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Nova: text-based programming for beginners 6 | 7 | 8 | 9 |
10 |
11 |
12 |
13 |

Toolbox

14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |

Defined Variables

23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
> Run Code
34 |
Clear Console
35 |
36 |
37 |
38 |
39 |
40 | 41 | 42 | -------------------------------------------------------------------------------- /src/editor/cursor.ts: -------------------------------------------------------------------------------- 1 | import { CodeConstruct, EmptyLineStmt, TypedEmptyExpr } from "../syntax-tree/ast"; 2 | import { Editor } from "./editor"; 3 | 4 | export class Cursor { 5 | editor: Editor; 6 | element: HTMLElement; 7 | code: CodeConstruct; 8 | container: HTMLElement; 9 | 10 | constructor(editor: Editor) { 11 | this.editor = editor; 12 | this.element = document.createElement("div"); 13 | this.element.classList.add("custom-selection-cursor"); 14 | this.container = document.querySelector(".lines-content.monaco-editor-background"); 15 | this.container.append(this.element); 16 | 17 | const cursor = this; 18 | 19 | function loop() { 20 | cursor.setTransform(cursor.code); 21 | 22 | requestAnimationFrame(loop); 23 | } 24 | 25 | loop(); 26 | } 27 | 28 | setTransform(code: CodeConstruct) { 29 | let leftPadding = 0; 30 | let rightPadding = 0; 31 | 32 | const selection = code != null ? code.getSelection() : this.editor.monaco.getSelection(); 33 | 34 | if (code instanceof TypedEmptyExpr) this.element.style.borderRadius = "15px"; 35 | else this.element.style.borderRadius = "0"; 36 | 37 | this.element.style.visibility = "visible"; 38 | if (!code || code instanceof EmptyLineStmt) this.element.style.visibility = "hidden"; 39 | 40 | const transform = this.editor.computeBoundingBox(selection); 41 | 42 | this.element.style.top = `${transform.y + 5}px`; 43 | this.element.style.left = `${transform.x - leftPadding}px`; 44 | 45 | this.element.style.width = `${transform.width + rightPadding}px`; 46 | this.element.style.height = `${transform.height - 5 * 2}px`; 47 | } 48 | 49 | setSelection(code: CodeConstruct = null) { 50 | this.code = code; 51 | this.setTransform(code); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/syntax-tree/body.ts: -------------------------------------------------------------------------------- 1 | import { Statement } from "./ast"; 2 | import { CallbackType } from "./callback"; 3 | import { Module } from "./module"; 4 | 5 | export function rebuildBody(bodyContainer: Statement | Module, fromIndex: number, startLineNumber: number) { 6 | let lineNumber = startLineNumber; 7 | 8 | for (let i = fromIndex; i < bodyContainer.body.length; i++) { 9 | bodyContainer.body[i].indexInRoot = i; 10 | 11 | if (i == 0 && bodyContainer instanceof Statement) { 12 | bodyContainer.setLineNumber(lineNumber); 13 | lineNumber++; 14 | } 15 | 16 | if (bodyContainer.body[i].hasBody()) rebuildBody(bodyContainer.body[i], 0, lineNumber); 17 | else bodyContainer.body[i].setLineNumber(lineNumber); 18 | 19 | lineNumber += bodyContainer.body[i].getHeight(); 20 | } 21 | 22 | // propagate the rebuild-body process to the root node 23 | if (bodyContainer instanceof Statement) { 24 | if (bodyContainer.rootNode instanceof Module) { 25 | rebuildBody(bodyContainer.rootNode, bodyContainer.indexInRoot + 1, lineNumber); 26 | bodyContainer.notify(CallbackType.change); 27 | } else if (bodyContainer.rootNode instanceof Statement && bodyContainer.rootNode.hasBody()) { 28 | rebuildBody(bodyContainer.rootNode, bodyContainer.indexInRoot + 1, lineNumber); 29 | bodyContainer.notify(CallbackType.change); 30 | } 31 | } 32 | } 33 | 34 | export function replaceInBody(bodyContainer: Statement | Module, atIndex: number, newStatement: Statement) { 35 | const leftPos = bodyContainer.body[atIndex].getLeftPosition(); 36 | newStatement.init(leftPos); 37 | 38 | newStatement.rootNode = bodyContainer.body[atIndex].rootNode; 39 | newStatement.indexInRoot = atIndex; 40 | bodyContainer.body[atIndex] = newStatement; 41 | 42 | if (newStatement.hasScope()) newStatement.scope.parentScope = bodyContainer.scope; 43 | 44 | rebuildBody(bodyContainer, atIndex + 1, leftPos.lineNumber + newStatement.getHeight()); 45 | } 46 | -------------------------------------------------------------------------------- /src/docs/while.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "while loop", 3 | "tooltip": { 4 | "title": "repeatedly execute code while true", 5 | "body": "repeatedly executes the code block inside the while loop as long as the condition remains `True`." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "title": "infinite loop", 11 | "id": "ex-while-1", 12 | "example": "while True :\n\tprint(\"an infinite loop\")" 13 | }, 14 | { 15 | "type": "executable", 16 | "title": "count from 0 to 10", 17 | "id": "ex-while-2", 18 | "example": "i = 0\nwhile i < 10:\n\tprint(i)\n\ti = i + 1" 19 | }, 20 | { 21 | "type": "quick", 22 | "title": "compare to scratch's repeat until block", 23 | "text": "the `while` loop in Python compared to the `repeat until` block in Scratch: the `while` loop in Python repeats code as long as the condition is `True`, and stops when the condition becomes `False`. However, the `repeat until` block in Scratch repeats code as long as the condition is `False`, and stops when the condition becomes `True`." 24 | }, 25 | { 26 | "type": "use-case", 27 | "title": "repeatedly increment a variable", 28 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/1-while-counter/", 29 | "max": 30, 30 | "prefix": "Slide", 31 | "extension": "PNG", 32 | "id": "while-increment-var", 33 | "explanations": [ 34 | { "slide": 7, "text": "i is less than 3 so the condition holds true" }, 35 | { "slide": 28, "text": "i is no longer less than 3 so the condition is false" }, 36 | { "slide": 29, "text": "should execute the next line after the while loop" } 37 | ] 38 | } 39 | ], 40 | "search-queries": [ 41 | "while", 42 | "repeat", 43 | "repeat while", 44 | "repeat until", 45 | "loop", 46 | "condition", 47 | "conditional", 48 | "repeat condition" 49 | ] 50 | } 51 | -------------------------------------------------------------------------------- /src/docs/break.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Break out of loops", 3 | "tooltip": { 4 | "title": "Insert Break inside Loop", 5 | "body": "Stops the innermost running loop (for, while) and breaks out of it." 6 | }, 7 | "tips": [ 8 | { 9 | "type": "executable", 10 | "id": "ex-break-out-range", 11 | "example": "for i in range(0, 50):\n\tif i == 25:\n\t\tbreak\n\tprint(i)" 12 | }, 13 | { 14 | "type": "use-case", 15 | "title": "break out of a while loop on some condition", 16 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/3-break/", 17 | "max": 30, 18 | "extension": "PNG", 19 | "prefix": "Slide", 20 | "id": "break-while-on-condition", 21 | "explanations": [ 22 | { "slide": 5, "text": "variable i is defined and set to 0" }, 23 | { "slide": 6, "text": "should repeat the while statements if i < 10" }, 24 | { "slide": 7, "text": "i is 0 and less than 10 -> should repeat" }, 25 | { "slide": 9, "text": "i is 0, so i + 1 is 1" }, 26 | { "slide": 11, "text": "i becomes 1" }, 27 | { "slide": 12, "text": "should enter the if statements if i equals 3" }, 28 | { "slide": 13, "text": "i is 1 so shouldn't enter the if" }, 29 | { "slide": 16, "text": "i is 1, so i + 1 is 2" }, 30 | { "slide": 14, "text": "should continue repeating because i is 1" }, 31 | { "slide": 18, "text": "i becomes 2" }, 32 | { "slide": 20, "text": "i is not equal to 3" }, 33 | { "slide": 21, "text": "should continue repeating because i is 2" }, 34 | { "slide": 23, "text": "i is 2, so i + 1 is 3" }, 35 | { "slide": 25, "text": "i becomes 3" }, 36 | { "slide": 27, "text": "is equal to 3 -> should enter if" }, 37 | { "slide": 28, "text": "break out of the current loop" }, 38 | { "slide": 29, "text": "won't check the while condition as we used break" }, 39 | { "slide": 30, "text": "will print 'done'" } 40 | ] 41 | } 42 | ], 43 | "search-queries": ["exit", "loop", "break"] 44 | } 45 | -------------------------------------------------------------------------------- /src/logger/analytics.ts: -------------------------------------------------------------------------------- 1 | import { sendEventsBatch } from "./requests"; 2 | import { getUser } from "./user"; 3 | 4 | export const ANALYTICS_ENABLED = false; 5 | 6 | export enum LogType { 7 | DraftHelpUsed = "draft-help-used", // data: { type: "add-double-quotes"} 8 | InsertCode = "insert-code", // data: source: "keyboard" | "autocomplete" | "autocomplete-menu" | "draft-mode" | "defined-vars" 9 | UseCaseSlideUsage = "use-case-slide-usage", 10 | TooltipItemUsage = "tooltip-item-usage", // {type: "use-case" | "hint" | "executable", duration} 11 | TooltipHoverDuration = "tooltip-hover-duration", 12 | RunMainCode = "run-main-code", 13 | } 14 | 15 | export class LogEvent { 16 | type: string; 17 | data: any; 18 | 19 | constructor(type: string, data: any) { 20 | this.data = data; 21 | this.type = type; 22 | } 23 | } 24 | 25 | export class Logger { 26 | private interval: number; 27 | private maxSize: number; 28 | private queue: Array = []; 29 | private static instance: Logger; 30 | 31 | constructor(interval: number = 10000, maxSize: number = 25) { 32 | this.maxSize = maxSize; 33 | this.interval = interval; 34 | this.dispatchEvents = this.dispatchEvents.bind(this); 35 | 36 | if (ANALYTICS_ENABLED) setInterval(this.dispatchEvents, interval); 37 | } 38 | 39 | static Instance() { 40 | if (!Logger.instance) Logger.instance = new Logger(); 41 | 42 | return Logger.instance; 43 | } 44 | 45 | queueEvent(event: LogEvent) { 46 | if (ANALYTICS_ENABLED) { 47 | console.log(event); 48 | this.queue.push(event); 49 | 50 | if (this.queue.length >= this.maxSize) this.dispatchEvents(); 51 | } 52 | } 53 | 54 | dispatchEvents() { 55 | if (this.queue.length === 0 || !ANALYTICS_ENABLED) return; 56 | 57 | sendEventsBatch(this.queue, getUser(), "nova-editor") 58 | .then(() => { 59 | console.log(`batch of ${this.queue.length} events sent successfully`); 60 | 61 | this.queue = []; 62 | }) 63 | .catch(() => { 64 | console.error( 65 | `failed to send batch of ${this.queue.length} events. will retry ${this.interval}ms later` 66 | ); 67 | }); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/docs/for.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "for loop", 3 | "tooltip": { 4 | "title": "loop through a sequence of elements", 5 | "body": "executes a set of statements for each element in a sequence (like a `range`, a `list`, or a `string`). " 6 | }, 7 | "tips": [ 8 | { 9 | "type": "quick", 10 | "title": "for loop inputs", 11 | "text": "for loops have two inputs: a variable name, and a sequence of items. the created variable is used to hold the current item, and the sequence is the list of items to go through." 12 | }, 13 | { 14 | "type": "quick", 15 | "title": "for loop as a counter", 16 | "text": "for loops can be used with the `range` function to work like a counter" 17 | }, 18 | { 19 | "type": "executable", 20 | "title": "using a for loop to go through a list", 21 | "id": "ex-for-list-items", 22 | "example": "lst = [\"cat\", \"dog\", \"mouse\", \"parrot\"]\nfor animal in lst:\n\tprint(animal)" 23 | }, 24 | { 25 | "type": "use-case", 26 | "title": "go through a list of items", 27 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/2-for-loop-list/", 28 | "max": 25, 29 | "extension": "PNG", 30 | "prefix": "Slide", 31 | "id": "loop-list-items" 32 | }, 33 | { 34 | "type": "use-case", 35 | "title": "go through a sequence of numbers", 36 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/3-for-loop-range/", 37 | "max": 21, 38 | "extension": "PNG", 39 | "prefix": "Slide", 40 | "id": "loop-sequence-nums" 41 | }, 42 | { 43 | "type": "use-case", 44 | "title": "go through a list of items using indices", 45 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/4-for-loop-range-list/", 46 | "max": 30, 47 | "extension": "PNG", 48 | "prefix": "Slide", 49 | "id": "loop-list-items-using-indices" 50 | }, 51 | { 52 | "type": "use-case", 53 | "title": "go through every character of a string", 54 | "path": "https://cdn.majeed.cc/pydoc/images/use-cases/5-for-loop-string/", 55 | "max": 21, 56 | "extension": "PNG", 57 | "prefix": "Slide", 58 | "id": "loop-chars-of-str" 59 | } 60 | ], 61 | "search-queries": ["for", "loop", "repeat", "go through", "iterate", "list"] 62 | } 63 | -------------------------------------------------------------------------------- /src/css/console.css: -------------------------------------------------------------------------------- 1 | #console { 2 | font-family: Consolas, "Courier New", monospace; 3 | 4 | flex-shrink: 0; 5 | flex-grow: 0; 6 | flex-basis: 30%; 7 | height: 30%; 8 | width: 100%; 9 | 10 | display: flex; 11 | flex-flow: column; 12 | 13 | background-color: #ccc; 14 | box-shadow: 10px 0px 20px 0px #ccc; 15 | } 16 | 17 | .run-code-btn { 18 | justify-self: start; 19 | background-color: rgb(24 200 120); 20 | color: #fff !important; 21 | } 22 | 23 | .run-code-button-container { 24 | margin: 10px 0px 0px 20px; 25 | } 26 | 27 | .run-code-button-container .disabled { 28 | background-color: #888; 29 | cursor: not-allowed; 30 | } 31 | 32 | #outputDiv { 33 | color: #000; 34 | font-size: 14px; 35 | font-weight: bold; 36 | 37 | overflow-y: auto; 38 | border-top: solid #bcbcbc 1px; 39 | 40 | margin-top: 10px; 41 | padding-left: 20px; 42 | padding: 8px 0 8px 20px; 43 | } 44 | 45 | .consoleTxt { 46 | font-weight: 10pt; 47 | } 48 | 49 | .consoleErrTxt { 50 | color: red; 51 | } 52 | 53 | .consoleWarnTxt { 54 | color: orange; 55 | } 56 | 57 | .clear-output-btn { 58 | box-shadow: none; 59 | border: solid #4f4f4f 0.5px; 60 | } 61 | 62 | .console-button { 63 | color: #000; 64 | cursor: pointer; 65 | border-radius: 4px; 66 | 67 | display: inline-block; 68 | align-items: center; 69 | justify-content: center; 70 | 71 | opacity: 1; 72 | 73 | height: -webkit-fit-content; 74 | height: -moz-fit-content; 75 | height: fit-content; 76 | 77 | margin-right: 10px; 78 | box-shadow: rgb(0 0 0 / 20%) 0px 3px 1px -2px, rgb(0 0 0 / 14%) 0px 2px 2px 0px, rgb(0 0 0 / 12%) 0px 1px 5px 0px; 79 | 80 | font-size: 14px; 81 | font-weight: bold; 82 | 83 | padding: 8px 10px; 84 | 85 | width: -webkit-fit-content; 86 | width: -moz-fit-content; 87 | width: fit-content; 88 | 89 | transition: 0.2s ease-in-out; 90 | -webkit-transition: 0.2s ease-in-out; 91 | -moz-transition: 0.2s ease-in-out; 92 | -o-transition: 0.2s ease-in-out; 93 | -ms-transition: 0.2s ease-in-out; 94 | } 95 | 96 | .run-code-btn:hover { 97 | background-color: rgb(21 173 110); 98 | box-shadow: rgb(0 0 0 / 20%) 0px 2px 4px -1px, rgb(0 0 0 / 14%) 0px 4px 5px 0px, rgb(0 0 0 / 12%) 0px 1px 10px 0px; 99 | } 100 | 101 | .clear-output-btn:hover { 102 | background-color: #4f4f4f; 103 | color: #fff; 104 | } 105 | 106 | #outputDiv::-webkit-scrollbar { 107 | background: #ccc; 108 | margin: 5px; 109 | width: 8px; 110 | } 111 | 112 | #outputDiv::-webkit-scrollbar-track { 113 | background: #c1c1c1; 114 | } 115 | 116 | #outputDiv::-webkit-scrollbar-thumb { 117 | border: none; 118 | background-color: #8c8c8c; 119 | border-radius: 0px; 120 | } 121 | -------------------------------------------------------------------------------- /src/css/suggestion-menu.css: -------------------------------------------------------------------------------- 1 | .suggestionMenuParent { 2 | display: flex; 3 | flex-direction: column; 4 | position: absolute; 5 | width: fit-content; 6 | max-width: 50%; 7 | min-width: 2%; 8 | 9 | overflow-y: scroll; 10 | scrollbar-width: none; /* Firefox */ 11 | -ms-overflow-style: none; /* Internet Explorer 10+ */ 12 | } 13 | .suggestionMenuParent::-webkit-scrollbar { 14 | width: 0; 15 | height: 0; 16 | } 17 | 18 | .suggestionMenuParent hole1 { 19 | border-radius: 5px; 20 | box-shadow: 0px 0px 1px 1px #0000005e inset; 21 | display: inline-block; 22 | 23 | position: relative; 24 | top: 2px; 25 | margin: 0px 2px; 26 | height: 16px; 27 | min-width: 16px; 28 | } 29 | 30 | .suggestionMenuParent hole2 { 31 | border-radius: 5px; 32 | box-shadow: 0px 0px 1px 1px #0000005e inset; 33 | display: inline-block; 34 | 35 | position: relative; 36 | top: 2px; 37 | margin: 0px 2px; 38 | box-shadow: none; 39 | border: dashed 1px #777; 40 | min-width: 9px; 41 | height: 13px; 42 | border-radius: 0; 43 | } 44 | 45 | .suggestionOptionParent { 46 | padding-left: 2px; 47 | padding-top: 2px; 48 | padding-bottom: 2px; 49 | padding-right: 2px; 50 | background-color: rgba(215, 215, 215, 0.7); 51 | cursor: pointer; 52 | 53 | height: fit-content; 54 | 55 | font-family: Consolas, "Courier New", monospace; 56 | font-weight: normal; 57 | font-feature-settings: "liga" 0, "calt" 0; 58 | } 59 | 60 | :hover.suggestionOptionParent { 61 | background-color: rgba(176, 202, 243, 0.9); 62 | } 63 | 64 | .suggestionOptionText { 65 | color: black; 66 | width: fit-content; 67 | font-size: 18px; 68 | line-height: 22px; 69 | letter-spacing: -0.5px; 70 | float: left; 71 | } 72 | 73 | .suggestionOptionExtraInfo { 74 | float: right; 75 | margin-left: 30px; 76 | margin-right: 5px; 77 | color: #555; 78 | position: relative; 79 | top: 2px; 80 | } 81 | 82 | .highlighted-text { 83 | background-color: #cc00ef; 84 | color: #fff; 85 | font-weight: bold; 86 | 87 | padding: 0 5px; 88 | border-radius: 3px; 89 | } 90 | 91 | .matchingText { 92 | color: #cc00ef; 93 | font-weight: bold; 94 | } 95 | 96 | .selectedSuggestionOptionParent { 97 | background-color: rgba(93, 149, 240, 0.9) !important; 98 | } 99 | 100 | .draftModeOptionElementClass { 101 | background-color: rgba(230, 233, 202, 0.7); 102 | } 103 | 104 | .optionArrowImage { 105 | grid-column-start: 2; 106 | grid-column-end: 2; 107 | grid-row-start: 1; 108 | grid-row-end: 1; 109 | 110 | width: 8px; 111 | height: 10px; 112 | align-self: center; 113 | justify-self: end; 114 | } 115 | 116 | .categoryHeading { 117 | font-weight: bold; 118 | } 119 | 120 | .categoryOption { 121 | padding-left: 10px; 122 | } 123 | -------------------------------------------------------------------------------- /src/css/accordion.css: -------------------------------------------------------------------------------- 1 | .accordion-group-container { 2 | } 3 | 4 | .accordion-row { 5 | border-radius: 4px; 6 | margin: 8px; 7 | background-color: #fff; 8 | overflow: hidden; 9 | box-shadow: 0px 1px 3px 1px #167faa; 10 | } 11 | 12 | .accordion-row .header-container { 13 | display: flex; 14 | justify-content: space-between; 15 | font-size: 14px; 16 | cursor: pointer; 17 | 18 | transition: 0.15s ease-in-out; 19 | -webkit-transition: 0.15s ease-in-out; 20 | -moz-transition: 0.15s ease-in-out; 21 | -o-transition: 0.15s ease-in-out; 22 | -ms-transition: 0.15s ease-in-out; 23 | } 24 | 25 | .accordion-row .header-container:hover { 26 | background-color: #ccc; 27 | } 28 | 29 | .accordion-row .header-container:hover .expand-collapse-button svg { 30 | background-color: #aebbcf; 31 | color: #00f; 32 | } 33 | 34 | .accordion-row .row-icon { 35 | display: flex; 36 | margin-left: 5px; 37 | align-items: center; 38 | } 39 | .accordion-row .row-type { 40 | margin-left: 5px; 41 | margin-top: 4px; 42 | } 43 | .accordion-row .row-title { 44 | margin-left: 5px; 45 | color: #000; 46 | font-weight: bold; 47 | } 48 | .accordion-row .row-chevron-right-icon { 49 | display: flex; 50 | margin-left: 5px; 51 | } 52 | .accordion-row .expand-collapse-button { 53 | display: flex; 54 | } 55 | 56 | .accordion-row .expand-collapse-button svg { 57 | cursor: pointer; 58 | margin: 2px; 59 | cursor: pointer; 60 | border-radius: 99px; 61 | color: #000; 62 | 63 | transition: 0.15s ease-in-out; 64 | -webkit-transition: 0.15s ease-in-out; 65 | -moz-transition: 0.15s ease-in-out; 66 | -o-transition: 0.15s ease-in-out; 67 | -ms-transition: 0.15s ease-in-out; 68 | } 69 | 70 | .accordion-row .content-container { 71 | overflow: hidden; 72 | } 73 | 74 | .accordion-row .header-container .type-container { 75 | background-color: #670093; 76 | padding-right: 8px; 77 | display: flex; 78 | flex-direction: row; 79 | align-content: center; 80 | height: 100%; 81 | } 82 | .accordion-row .header-container .text-container { 83 | display: flex; 84 | flex-direction: row; 85 | align-items: center; 86 | } 87 | 88 | .accordion-row .header-container .bg-learn { 89 | background-color: #9c27b0; 90 | } 91 | .accordion-row .header-container .bg-try { 92 | background-color: #45a249; 93 | } 94 | .accordion-row .header-container .bg-hint { 95 | background-color: #cc451b; 96 | } 97 | 98 | .accordion-row .chevron { 99 | color: #000; 100 | padding: 10px; 101 | 102 | transition: background-color 0.15s ease-in-out; 103 | -webkit-transition: background-color 0.15s ease-in-out; 104 | -moz-transition: background-color 0.15s ease-in-out; 105 | -o-transition: background-color 0.15s ease-in-out; 106 | -ms-transition: background-color 0.15s ease-in-out; 107 | } 108 | 109 | .accordion-row .chevron:hover { 110 | color: #00f; 111 | } 112 | -------------------------------------------------------------------------------- /src/messages/notifications.ts: -------------------------------------------------------------------------------- 1 | import { EditCodeAction } from "../editor/action-filter"; 2 | import { Module } from "../syntax-tree/module"; 3 | 4 | export class NotificationManager { 5 | module: Module; 6 | 7 | constructor(module: Module) { 8 | this.module = module; 9 | } 10 | 11 | showTypingMessage(action: EditCodeAction) { 12 | const keys: string[] = this.generateKeys(action.matchString, action.terminatingChars); 13 | let codeHtml = action.optionName.replace(/---/g, ""); 14 | codeHtml = codeHtml.replace(/--/g, ""); 15 | 16 | const headerMessage: string = `Insert the ${codeHtml} statement by typing:`; 17 | 18 | let notificationEl = document.createElement("div"); 19 | notificationEl.classList.add("notification-container"); 20 | document.body.appendChild(notificationEl); 21 | 22 | let messageEl = document.createElement("div"); 23 | messageEl.classList.add("message"); 24 | messageEl.innerHTML = headerMessage; 25 | notificationEl.appendChild(messageEl); 26 | 27 | setTimeout(() => { 28 | notificationEl.classList.add("animate"); 29 | }, 50); 30 | 31 | setTimeout(() => { 32 | document.body.removeChild(notificationEl); 33 | }, 5000 + 500 * keys.length); 34 | 35 | let keyIndex = 0; 36 | 37 | const keyAnimationContainer = document.createElement("div"); 38 | keyAnimationContainer.classList.add("key-animation-container"); 39 | notificationEl.appendChild(keyAnimationContainer); 40 | 41 | let interval = setInterval(() => { 42 | if (keyIndex < keys.length) { 43 | const keySpan = document.createElement("span"); 44 | keySpan.classList.add("key-span"); 45 | keySpan.innerHTML = keys[keyIndex]; 46 | 47 | keyIndex++; 48 | 49 | keyAnimationContainer.appendChild(keySpan); 50 | } else { 51 | clearInterval(interval); 52 | } 53 | }, 500); 54 | } 55 | 56 | showNotification(message: string) { 57 | let notification = document.createElement("div"); 58 | notification.classList.add("notification-container"); 59 | notification.innerHTML = message; 60 | 61 | document.body.appendChild(notification); 62 | 63 | setTimeout(() => { 64 | notification.classList.add("animate"); 65 | }, 50); 66 | 67 | setTimeout(() => { 68 | document.body.removeChild(notification); 69 | }, 5000); 70 | } 71 | 72 | generateKeys(matchString: string, terminatingChars: string[]): Array { 73 | const keys: Array = []; 74 | 75 | for (let i = 0; i < matchString.length; i++) { 76 | keys.push(matchString[i]); 77 | } 78 | 79 | for (let i = 0; i < terminatingChars.length; i++) { 80 | let key = terminatingChars[i]; 81 | 82 | if (key === " ") key = "space"; 83 | 84 | keys.push(key); 85 | } 86 | 87 | return keys; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/css/messages.css: -------------------------------------------------------------------------------- 1 | .codeVisual { 2 | display: block; 3 | position: absolute; 4 | pointer-events: none; 5 | z-index: -999; 6 | } 7 | 8 | .codeVisual.highlight { 9 | border-radius: 5px; 10 | 11 | background-color: rgba(255, 255, 255, 0); 12 | 13 | transition: background-color 0.3s ease-in-out; 14 | -webkit-transition: background-color 0.3s ease-in-out; 15 | -moz-transition: background-color 0.3s ease-in-out; 16 | -o-transition: background-color 0.3s ease-in-out; 17 | -ms-transition: background-color 0.3s ease-in-out; 18 | } 19 | 20 | .scope-header-highlight { 21 | display: block; 22 | position: absolute; 23 | pointer-events: none; 24 | z-index: -999; 25 | 26 | border-top-left-radius: 6px; 27 | border-bottom-left-radius: 6px; 28 | border-top-right-radius: 6px; 29 | } 30 | 31 | .scope-body-highlight { 32 | display: block; 33 | position: absolute; 34 | pointer-events: none; 35 | z-index: -999; 36 | 37 | border-bottom-left-radius: 6px; 38 | border-bottom-right-radius: 6px; 39 | } 40 | 41 | .codeVisual.textBox { 42 | font-family: Consolas, "Courier New", monospace; 43 | color: #000; 44 | font-size: 14px; 45 | 46 | box-shadow: 0 0 7px 1px #888; 47 | background-color: #c5d2d9; 48 | overflow-y: scroll; 49 | overflow-wrap: break-word; 50 | scrollbar-width: none; 51 | 52 | max-width: 40vw; 53 | width: 40vw; 54 | height: fit-content; 55 | max-height: 40vh; 56 | 57 | display: block; 58 | height: fit-content; 59 | 60 | border-radius: 5px; 61 | 62 | pointer-events: all; 63 | z-index: 999; 64 | } 65 | 66 | .codeVisual.textBox::-webkit-scrollbar { 67 | display: none; 68 | } 69 | 70 | .codeVisual .text-container-style { 71 | margin-bottom: 5px; 72 | line-height: 18px; 73 | } 74 | 75 | .codeVisual .msg-content-container { 76 | padding: 8px; 77 | } 78 | 79 | .codeVisual.popUp { 80 | background-color: rgb(253, 198, 115); 81 | color: black; 82 | position: absolute; 83 | width: 125px; 84 | height: fit-content; 85 | max-height: 30%; 86 | } 87 | 88 | .identifier { 89 | color: blueviolet; 90 | font-weight: bold; 91 | } 92 | 93 | .type { 94 | font-weight: bold; 95 | background-color: #99a7ad; 96 | padding: 1px 5px 1px 5px; 97 | border-radius: 3px; 98 | } 99 | 100 | .keyword { 101 | color: blue; 102 | font-weight: 500; 103 | } 104 | 105 | .other { 106 | font-weight: 600; 107 | } 108 | 109 | .emph { 110 | font-weight: 700; 111 | } 112 | 113 | .codeVisual.textBox .button { 114 | display: inline-flex; 115 | margin: 7px 7px 0 0; 116 | font-size: 13px; 117 | box-shadow: 0 0 3px 1px #aaa; 118 | 119 | background-color: #ffffff; 120 | height: 17px; 121 | padding: 3px 8px 3px 8px; 122 | align-content: center; 123 | } 124 | 125 | .hover-msg-header { 126 | width: 100%; 127 | height: 20px; 128 | background-color: rgb(130 155 169); 129 | color: white; 130 | display: flex; 131 | flex-direction: row; 132 | align-items: center; 133 | padding-left: 8px; 134 | } 135 | -------------------------------------------------------------------------------- /src/css/editor.css: -------------------------------------------------------------------------------- 1 | #editorArea { 2 | width: 100%; 3 | height: 100%; 4 | display: flex; 5 | flex-direction: column; 6 | } 7 | 8 | #editor { 9 | width: 100%; 10 | flex-shrink: 0; 11 | flex-grow: 0; 12 | flex-basis: 70%; 13 | height: 70%; 14 | } 15 | 16 | #editor .monaco-editor.no-user-select.showUnused.showDeprecated.vs { 17 | height: 100%; 18 | } 19 | 20 | #editor .monaco-editor, 21 | #editor .monaco-editor-background, 22 | #editor .monaco-editor .inputarea.ime-input { 23 | background-color: rgba(0, 0, 0, 0) !important; 24 | } 25 | 26 | #editor .monaco-editor-background { 27 | /* background-color: var(--main-bg-color) !important; */ 28 | background-color: rgba(0, 0, 0, 0) !important; 29 | } 30 | 31 | #editor .monaco-editor .margin { 32 | /* background-color: var(--main-bg-color) !important; */ 33 | background-color: rgba(0, 0, 0, 0) !important; 34 | } 35 | 36 | #editor .monaco-editor .view-overlays .current-line { 37 | display: none; 38 | } 39 | 40 | #editor .execution-decoration { 41 | left: 45px !important; 42 | 43 | width: 8px !important; 44 | height: 8px !important; 45 | 46 | border-radius: 50%; 47 | border: 1px solid #bfbebe; 48 | background-color: #00000008 !important; 49 | 50 | margin-top: 10%; 51 | 52 | display: none; 53 | } 54 | 55 | #editor .monaco-editor .line-numbers { 56 | color: black !important; 57 | opacity: 0.2; 58 | font-size: 12px !important; 59 | margin-top: 2px !important; 60 | transition: 1s; 61 | transition-property: opacity; 62 | margin-left: -10px; 63 | } 64 | 65 | #editor .monaco-editor .line-numbers:hover { 66 | opacity: 1 !important; 67 | } 68 | 69 | #editor .line-selected { 70 | font-weight: 800 !important; 71 | opacity: 1 !important; 72 | } 73 | 74 | #editor .cigr { 75 | box-shadow: 0.5px 0 0 0 rgba(0, 0, 0, 0) inset !important; 76 | } 77 | 78 | #editor .cigra { 79 | box-shadow: 0.5px 0 0 0 rgba(0, 0, 0, 0) inset !important; 80 | } 81 | 82 | #editor .monaco-editor .margin-view-overlays .codicon-chevron-down { 83 | font-size: 80%; 84 | } 85 | 86 | #editor .monaco-editor .margin-view-overlays .codicon-folding-collapsed, 87 | #editor .monaco-editor .margin-view-overlays .codicon-folding-expanded { 88 | font-size: 80% !important; 89 | } 90 | 91 | #editor .cdr.bracket-match { 92 | opacity: 0.5; 93 | border: none !important; 94 | outline: none !important; 95 | border-radius: 3px; 96 | padding: 2px; 97 | background: none !important; 98 | } 99 | 100 | #editor .monaco-editor .cursors-layer .cursor { 101 | background-color: black !important; 102 | transition-property: top, left; 103 | transition: 0.1s; 104 | opacity: 0.5; 105 | height: 20px !important; 106 | margin-top: 11px !important; 107 | margin-left: 2px !important; 108 | } 109 | 110 | #editor .monaco-editor .scroll-decoration { 111 | box-shadow: none !important; 112 | } 113 | 114 | #editor .monaco-scrollable-element { 115 | overflow: visible !important; 116 | } 117 | 118 | #editor .monaco-editor .view-overlays .current-line { 119 | border: none !important; 120 | } 121 | 122 | #editor .monaco-editor .selected-text { 123 | background: none !important; 124 | } 125 | -------------------------------------------------------------------------------- /src/css/cascaded-menu.css: -------------------------------------------------------------------------------- 1 | .cascadedMenuMainDiv::-webkit-scrollbar { 2 | background: #ccc; 3 | margin: 5px; 4 | width: 8px; 5 | } 6 | 7 | .cascadedMenuMainDiv::-webkit-scrollbar-track { 8 | background: #ebebeb; 9 | } 10 | 11 | .cascadedMenuMainDiv::-webkit-scrollbar-thumb { 12 | border: none; 13 | background-color: #d1d1d1; 14 | border-radius: 0px; 15 | } 16 | 17 | .cascadedMenuMainDiv { 18 | opacity: 0; 19 | 20 | min-width: 375px; 21 | z-index: 10; 22 | position: absolute; 23 | background-color: white; 24 | box-shadow: 0px 8px 16px 0px rgb(0 0 0 / 20%); 25 | 26 | border-radius: 6px; 27 | 28 | overflow-y: auto; 29 | 30 | transition: opacity 0.1s ease-in-out; 31 | -webkit-transition: opacity 0.1s ease-in-out; 32 | -moz-transition: opacity 0.1s ease-in-out; 33 | -o-transition: opacity 0.1s ease-in-out; 34 | -ms-transition: opacity 0.1s ease-in-out; 35 | } 36 | 37 | .cascadedMenuItem { 38 | cursor: pointer; 39 | } 40 | 41 | .cascadedMenuMainDiv .cascadedMenuItem :not(:hover) { 42 | background-color: white; 43 | } 44 | 45 | .cascadedMenuContent { 46 | padding-left: 9px; 47 | } 48 | 49 | .cascadedMenuContent .inline-var-id { 50 | color: #aa5bc8; 51 | border-radius: 4px; 52 | padding: 1px 4px; 53 | border: solid 1px #bbb; 54 | } 55 | 56 | .cascadedMenuOptionTooltip { 57 | display: inline; 58 | align-self: center; 59 | font-size: 14px; 60 | color: #16b3c1; 61 | margin-right: 10px; 62 | } 63 | 64 | .valid-option-tooltip { 65 | font-weight: bold; 66 | } 67 | 68 | .hoverable:hover .cascadedMenuMainDiv { 69 | display: block; 70 | } 71 | 72 | .cascaded-menu-header { 73 | border-bottom: solid 1px #ccc; 74 | margin-bottom: 5px; 75 | height: 35px; 76 | width: 100%; 77 | display: flex; 78 | flex-direction: row; 79 | align-items: center; 80 | background-color: #006a93; 81 | color: #fff; 82 | } 83 | 84 | .cascaded-menu-header h3 { 85 | font-weight: bold; 86 | font-size: 18px; 87 | margin: 8px 10px 8px 10px; 88 | } 89 | 90 | .cascaded-menu-header .identifier { 91 | font-weight: bold; 92 | background-color: #9850b3; 93 | padding: 0px 8px 0px 8px; 94 | border-radius: 3px; 95 | color: #fff; 96 | } 97 | 98 | .cascadedMenuContent .button { 99 | font-size: 15px; 100 | padding: 6px 10px; 101 | 102 | white-space: nowrap; 103 | box-shadow: 0px 1px 5px 2px #ddd; 104 | 105 | transition: 0.15s ease-in-out; 106 | -webkit-transition: 0.15s ease-in-out; 107 | -moz-transition: 0.15s ease-in-out; 108 | -o-transition: 0.15s ease-in-out; 109 | -ms-transition: 0.15s ease-in-out; 110 | 111 | -webkit-user-select: none; /* Safari */ 112 | -moz-user-select: none; /* Firefox */ 113 | -ms-user-select: none; /* IE10+/Edge */ 114 | user-select: none; /* Standard */ 115 | } 116 | 117 | .cascadedMenuContent .button:hover { 118 | box-shadow: 0px 1px 5px 2px #ccc; 119 | } 120 | 121 | .cascadedMenuContent .var-button-container { 122 | display: inline-flex; 123 | } 124 | 125 | .cascadedMenuContent .button-id { 126 | color: #aa5bc8; 127 | } 128 | 129 | .var-more-actions-button { 130 | border: solid 1px #007acc; 131 | padding: 3px 6px; 132 | border-radius: 5px; 133 | color: #007acc; 134 | font-size: 13px; 135 | 136 | transition: background-color 0.15s ease-in-out; 137 | -webkit-transition: background-color 0.15s ease-in-out; 138 | -moz-transition: background-color 0.15s ease-in-out; 139 | -o-transition: background-color 0.15s ease-in-out; 140 | -ms-transition: background-color 0.15s ease-in-out; 141 | 142 | cursor: pointer; 143 | 144 | margin-right: 5px; 145 | } 146 | 147 | .var-more-actions-button:hover { 148 | background-color: #007acc; 149 | color: #fff; 150 | } 151 | -------------------------------------------------------------------------------- /src/suggestions/construct-doc.ts: -------------------------------------------------------------------------------- 1 | import { EDITOR_DOM_ID } from "../editor/toolbox"; 2 | import { constructKeys, Util } from "../utilities/util"; 3 | 4 | /** 5 | * Class representing a code construct's documentation that can be displayed to the user. 6 | */ 7 | export class ConstructDoc { 8 | private docElementClass = "docParent"; 9 | private imgElementClass = "docImageParent"; 10 | private bodyElementClass = "docBody"; 11 | private titleElementClass = "docTitle"; 12 | 13 | images: Array; 14 | text: string; 15 | links: Array[]; 16 | title: string; 17 | parentElement: HTMLDivElement; 18 | 19 | static updateDocsLeftOffset(offset: number) { 20 | constructKeys.forEach((key) => { 21 | if (Util.getPopulatedInstance().constructDocs.get(key)) { 22 | Util.getPopulatedInstance().constructDocs.get(key).updateLeftOffset(offset); 23 | } 24 | }); 25 | } 26 | 27 | constructor( 28 | title: string = "DOC Title", 29 | text: string = "DOC text", 30 | images: Array = [], 31 | links: Array[] = [] 32 | ) { 33 | this.images = images; 34 | this.text = text; 35 | this.title = title; 36 | this.links = links; 37 | 38 | this.parentElement = document.createElement("div"); 39 | this.parentElement.classList.add(this.docElementClass); 40 | 41 | this.buildDoc(); 42 | this.hide(); 43 | 44 | this.parentElement.addEventListener("mouseenter", () => { 45 | this.show(); 46 | }); 47 | 48 | this.parentElement.addEventListener("mouseleave", () => { 49 | this.hide(); 50 | }); 51 | } 52 | 53 | private buildDoc() { 54 | const title = document.createElement("h3"); 55 | title.textContent = this.title; 56 | title.classList.add(this.titleElementClass); 57 | 58 | const body = document.createElement("div"); 59 | body.classList.add(this.bodyElementClass); 60 | body.innerHTML = this.text; 61 | 62 | this.parentElement.appendChild(title); 63 | this.parentElement.appendChild(body); 64 | 65 | if (this.images.length > 0) this.addImageSection(); 66 | 67 | if (this.links.length > 0) this.addLinkSection(); 68 | 69 | //TODO: Should be global... 70 | this.parentElement.style.left = `${document.getElementById(EDITOR_DOM_ID).offsetLeft}px`; 71 | this.parentElement.style.top = `${parseFloat( 72 | window.getComputedStyle(document.getElementById(EDITOR_DOM_ID)).paddingTop 73 | )}px`; 74 | 75 | document.getElementById(EDITOR_DOM_ID).appendChild(this.parentElement); 76 | } 77 | 78 | private addImageSection() { 79 | const imageParent = document.createElement("div"); 80 | imageParent.classList.add(this.imgElementClass); 81 | 82 | this.images.forEach((imgSrc) => { 83 | const image = document.createElement("img"); 84 | image.classList.add("docImage"); 85 | image.src = imgSrc; 86 | imageParent.appendChild(image); 87 | }); 88 | 89 | this.parentElement.appendChild(imageParent); 90 | } 91 | 92 | private addLinkSection() { 93 | const linkParent = document.createElement("div"); 94 | linkParent.classList.add("docLinkParent"); 95 | 96 | this.parentElement.appendChild(linkParent); 97 | } 98 | 99 | show() { 100 | this.parentElement.style.visibility = "visible"; 101 | } 102 | 103 | hide() { 104 | this.parentElement.style.visibility = "hidden"; 105 | } 106 | 107 | updateLeftOffset(offset: number) { 108 | this.parentElement.style.left = `${offset}px`; 109 | } 110 | 111 | resetScroll() { 112 | this.parentElement.scrollTop = 0; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/pyodide-js/pyodide-controller.js: -------------------------------------------------------------------------------- 1 | import { CodeStatus } from "../editor/consts"; 2 | import { nova, runBtnToOutputWindow } from "../index"; 3 | import { LogEvent, Logger, LogType } from "../logger/analytics"; 4 | import { addTextToConsole, clearConsole, CONSOLE_ERR_TXT_CLASS, CONSOLE_WARN_TXT_CLASS } from "../pyodide-ts/pyodide-ui"; 5 | 6 | 7 | const jsModule = { 8 | inputPrompt: function (text) { 9 | return prompt(text); 10 | }, 11 | }; 12 | 13 | export const codeString = (code) => { 14 | return `from jsModule import inputPrompt\ninput = inputPrompt\n__builtins__.input = inputPrompt\n${code}\n` 15 | } 16 | 17 | export const attachPyodideActions = (afterPyodideLoadedActions, otherActions) => { 18 | (async () => { 19 | (await import("../pyodide-js/load-pyodide")).default 20 | .then( 21 | (res) => { 22 | return res.pyodideController; 23 | }, 24 | (err) => { 25 | console.error("Could not import load-pyodide"); 26 | console.error(err); 27 | } 28 | ) 29 | .then((res) => { 30 | let pyodideController = res; 31 | 32 | for (let i = 0; i < afterPyodideLoadedActions.length; i++) { 33 | afterPyodideLoadedActions[i](pyodideController); 34 | } 35 | }), 36 | (err) => { 37 | console.error("Could not access pyodideController"); 38 | console.error(err); 39 | }; 40 | 41 | for (let i = 0; i < otherActions.length; i++) { 42 | otherActions[i](); 43 | } 44 | })(); 45 | 46 | } 47 | 48 | const attachMainConsoleRun = (pyodideController) => { 49 | const runCodeBtn = document.getElementById("runCodeBtn"); 50 | let consoleId = runBtnToOutputWindow.get(nova.globals.lastPressedRunButtonId) ?? "outputDiv"; 51 | runCodeBtn.addEventListener("click", () => { 52 | const codeStatus = nova.getCodeStatus(true); 53 | clearConsole("outputDiv"); 54 | 55 | const eventType = LogType.RunMainCode; 56 | const eventData = {}; 57 | 58 | switch (codeStatus) { 59 | case CodeStatus.Runnable: 60 | const code = nova.editor.monaco.getValue(); 61 | eventData.code = code; 62 | 63 | try { 64 | nova.globals.lastPressedRunButtonId = "runCodeBtn"; 65 | pyodideController.runPython( 66 | codeString(code) 67 | ); 68 | } catch (err) { 69 | console.error("Unable to run python code"); 70 | addTextToConsole(consoleId, err, CONSOLE_ERR_TXT_CLASS); 71 | } 72 | 73 | eventData.status = "no-error"; 74 | 75 | break; 76 | 77 | case CodeStatus.ContainsAutocompleteTokens: 78 | addTextToConsole( 79 | consoleId, "Your code contains unfinished autocomplete elements. Remove or complete them to be able to run your code.", 80 | CONSOLE_WARN_TXT_CLASS 81 | ); 82 | 83 | eventData.status = "contains-unfinished-autocomplete"; 84 | 85 | break; 86 | 87 | case CodeStatus.ContainsDraftMode: 88 | addTextToConsole(consoleId, 89 | "Your code contains unfinished constructs. Complete the constructs to be able to run your code.", 90 | CONSOLE_WARN_TXT_CLASS 91 | ); 92 | 93 | eventData.status = "contains-draft-modes"; 94 | 95 | break; 96 | 97 | case CodeStatus.ContainsEmptyHoles: 98 | addTextToConsole(consoleId, 99 | "Your code contains empty parts that expect to be filled with values. Fill these in order to be able to run your code.", 100 | CONSOLE_WARN_TXT_CLASS 101 | ); 102 | 103 | eventData.status = "contains-empty-holes"; 104 | 105 | break; 106 | 107 | case CodeStatus.Empty: 108 | addTextToConsole(consoleId, 109 | "Your code is empty! Try inserting something from the toolbox.", 110 | CONSOLE_WARN_TXT_CLASS 111 | ); 112 | 113 | eventData.status = "no-code"; 114 | 115 | break; 116 | } 117 | 118 | Logger.Instance().queueEvent(new LogEvent(eventType, eventData)); 119 | }); 120 | } 121 | 122 | const attachMainConsoleClear = () => { 123 | //this is only for the main console so the id is hard-coded 124 | document.getElementById("clearOutputBtn").addEventListener("click", () => { 125 | clearConsole("outputDiv"); 126 | }); 127 | } 128 | 129 | attachPyodideActions([(controller) => { 130 | controller.registerJsModule("jsModule", jsModule); 131 | }, attachMainConsoleRun], [attachMainConsoleClear]); 132 | -------------------------------------------------------------------------------- /src/editor/event-stack.ts: -------------------------------------------------------------------------------- 1 | import { editor, IKeyboardEvent, IScrollEvent } from "monaco-editor"; 2 | import { Module } from "../syntax-tree/module"; 3 | 4 | const navigationKeys = ["ArrowRight", "ArrowLeft", "ArrowUp", "ArrowDown"]; 5 | 6 | export enum EventType { 7 | OnKeyDown, 8 | OnButtonDown, 9 | OnMouseMove, 10 | OnDidScrollChange, 11 | OnCursorPosChange, 12 | } 13 | 14 | export class EventAction { 15 | type: EventType; 16 | event: any; 17 | 18 | constructor(type: EventType, event: any) { 19 | this.type = type; 20 | this.event = event; 21 | } 22 | } 23 | 24 | export class EventStack { 25 | stack = []; 26 | module: Module; 27 | 28 | constructor(module: Module) { 29 | this.module = module; 30 | 31 | this.attachOnKeyDownListener(); 32 | this.attachOnButtonPress(); 33 | this.attachOnMouseMoveListener(); 34 | this.attachOnDidScrollChangeListener(); 35 | this.attachOnCursorPosChange(); 36 | } 37 | 38 | // undo() { 39 | // // Undo the 'ctrl' press after 'ctrl + z' 40 | // if ( 41 | // this.stack[this.stack.length - 1].type === EventType.OnKeyDown && 42 | // this.stack[this.stack.length - 1].event.ctrlKey 43 | // ) { 44 | // this.stack.pop(); 45 | // } 46 | 47 | // // Undo the most recent action 48 | // this.stack.pop(); 49 | 50 | // this.module.reset(); 51 | 52 | // // TODO: find why this needs a timeout, I think its because 53 | // // monaco's selection doesn't update synchronously after this.module.reset() 54 | // // If there is a callback on monaco like onUpdateComplete then subscribe to that 55 | // // and execute this then 56 | // setTimeout(() => { 57 | // for (const action of this.stack) this.apply(action); 58 | // }); 59 | // } 60 | 61 | attachOnButtonPress() { 62 | const buttons: Array = Array(...(document.querySelectorAll("#editor-toolbox .button") as any)); 63 | 64 | for (const button of buttons) { 65 | button.addEventListener("click", () => { 66 | const action = new EventAction(EventType.OnButtonDown, button.id); 67 | this.stack.push(action); 68 | this.apply(action); 69 | }); 70 | } 71 | } 72 | 73 | attachOnCursorPosChange() { 74 | const module = this.module; 75 | 76 | module.editor.monaco.onDidChangeCursorPosition((e: editor.ICursorPositionChangedEvent) => { 77 | const action = new EventAction(EventType.OnCursorPosChange, e); 78 | this.apply(action); 79 | }); 80 | } 81 | 82 | attachOnKeyDownListener() { 83 | const module = this.module; 84 | 85 | module.editor.monaco.onKeyDown((e: IKeyboardEvent) => { 86 | if (e.ctrlKey && e.code == "KeyZ") { 87 | // TODO: Temporarily disable undo for now - refer to https://github.com/MajeedKazemi/nova-editor/issues/509 88 | // this.undo(); 89 | 90 | return; 91 | } 92 | 93 | const action = new EventAction(EventType.OnKeyDown, e); 94 | 95 | //exclude navigation 96 | if (navigationKeys.indexOf(e.code) === -1) this.stack.push(action); 97 | 98 | this.apply(action); 99 | }); 100 | } 101 | 102 | attachOnMouseMoveListener() { 103 | const module = this.module; 104 | 105 | //x,y pos of mouse within window 106 | document.onmousemove = function (e) { 107 | module.editor.mousePosWindow[0] = e.x; 108 | module.editor.mousePosWindow[1] = e.y; 109 | }; 110 | } 111 | 112 | attachOnDidScrollChangeListener() { 113 | const module = this.module; 114 | 115 | module.editor.monaco.onDidScrollChange((e: IScrollEvent) => { 116 | const action = new EventAction(EventType.OnDidScrollChange, e); 117 | this.apply(action); 118 | }); 119 | } 120 | 121 | apply(action: EventAction) { 122 | switch (action.type) { 123 | case EventType.OnKeyDown: 124 | this.module.eventRouter.onKeyDown(action.event); 125 | 126 | break; 127 | 128 | case EventType.OnButtonDown: 129 | this.module.eventRouter.onButtonDown(action.event); 130 | 131 | break; 132 | 133 | case EventType.OnCursorPosChange: 134 | this.module.eventRouter.onCursorPosChange(action.event); 135 | 136 | break; 137 | 138 | case EventType.OnDidScrollChange: 139 | this.module.eventRouter.onDidScrollChange(action.event); 140 | 141 | break; 142 | 143 | default: 144 | break; 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/messages/message-controller.ts: -------------------------------------------------------------------------------- 1 | import { Editor } from "../editor/editor"; 2 | import { CodeConstruct } from "../syntax-tree/ast"; 3 | import { Module } from "../syntax-tree/module"; 4 | import { ErrorMessage, ErrorMessageGenerator } from "./error-msg-generator"; 5 | import { HoverMessage, InlineMessage, PopUpMessage } from "./messages"; 6 | 7 | const popUpMessageTime = 3000; //ms 8 | 9 | const defaultHighlightColour: [number, number, number, number] = [255, 191, 94, 0.3]; 10 | 11 | /** 12 | * Class representing the main entry point of the code into the MessageController. 13 | * Top-level class for handling workflow; message system logic is in MessageController. 14 | */ 15 | export class MessageController { 16 | editor: Editor; 17 | messages: InlineMessage[]; 18 | msgGenerator: ErrorMessageGenerator; 19 | module: Module; //TODO: Find some other way to get this. Probably should not be passing this around, maybe make it a method argument for methods that need it, instead of each instance holding a reference 20 | 21 | constructor(editor: Editor, module: Module) { 22 | this.editor = editor; 23 | this.messages = []; 24 | this.msgGenerator = new ErrorMessageGenerator(); 25 | this.module = module; 26 | } 27 | 28 | /** 29 | * Add a hover message to a code construct. 30 | * 31 | * @param code code construct being added to (hole, empty line, etc... Not the code being added) 32 | * @param args context for constructing appropriate message. See error-msg-generator.ts for more info 33 | * @param errMsgType type of error message that should be displayed when hovered over 34 | */ 35 | addHoverMessage( 36 | codeToHighlight: CodeConstruct, 37 | args: any, 38 | warningText?: string, 39 | errMsgType?: ErrorMessage, 40 | highlightColour: [number, number, number, number] = defaultHighlightColour 41 | ): HoverMessage { 42 | if (!codeToHighlight.message) { 43 | const message = new HoverMessage( 44 | this.editor, 45 | codeToHighlight, 46 | errMsgType ? this.msgGenerator.generateMsg(errMsgType, args) : warningText ?? "Placeholder Text", 47 | highlightColour, 48 | this.messages.length 49 | ); 50 | 51 | this.messages.push(message); 52 | codeToHighlight.message = message; 53 | 54 | return message; 55 | } else { 56 | this.removeMessageFromConstruct(codeToHighlight); 57 | 58 | return this.addHoverMessage(codeToHighlight, args, warningText, errMsgType, highlightColour); 59 | } 60 | } 61 | 62 | /** 63 | * Add a pop-up message to the editor at the specified position. 64 | * 65 | * If args and errMsgType are specified, there is no need to specify text as it will be auto-generated. 66 | */ 67 | addPopUpMessage(code: CodeConstruct, args: any, errMsgType?: ErrorMessage, text?: string) { 68 | if (text) { 69 | this.messages.push( 70 | new PopUpMessage( 71 | this.editor, 72 | code, 73 | this.msgGenerator.generateMsg(errMsgType, args) ?? text, 74 | this.messages.length 75 | ) 76 | ); 77 | } else { 78 | this.messages.push( 79 | new PopUpMessage( 80 | this.editor, 81 | code, 82 | this.msgGenerator.generateMsg(errMsgType, args) ?? text, 83 | this.messages.length 84 | ) 85 | ); 86 | } 87 | 88 | const message = this.messages[this.messages.length - 1]; 89 | 90 | setTimeout(() => { 91 | message.removeFromDOM(); 92 | this.messages.splice(message.systemIndex); 93 | }, popUpMessageTime); 94 | } 95 | 96 | /** 97 | * Remove message from given code construct if it exists. 98 | * 99 | * @param code code construct to remove message from 100 | */ 101 | removeMessageFromConstruct(code: CodeConstruct) { 102 | if (code?.message) { 103 | const indexOfMessage = this.messages.indexOf(code.message); 104 | this.messages[code.message.systemIndex].removeFromDOM(); 105 | this.messages.splice(code.message.systemIndex, 1); 106 | code.message = null; 107 | 108 | for (let i = indexOfMessage; i < this.messages.length; i++) { 109 | this.messages[i].systemIndex--; 110 | } 111 | } else { 112 | console.warn("Could not remove message from construct: " + code); 113 | } 114 | } 115 | 116 | /** 117 | * Remove all currently open messages from the editor. 118 | */ 119 | clearAllMessages() { 120 | this.messages.forEach((message) => { 121 | message.removeFromDOM(); 122 | }); 123 | 124 | this.messages = []; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/css/doc-box.css: -------------------------------------------------------------------------------- 1 | .doc-box-container { 2 | position: absolute; 3 | box-shadow: 0px 0px 20px 0px #5d5d5d; 4 | width: 400px; 5 | height: 330px; 6 | left: calc(50% - 150px); 7 | top: calc(50% - 125px); 8 | background-color: #fff; 9 | border-radius: 7px; 10 | overflow: hidden; 11 | resize: both; 12 | 13 | font-family: Consolas, "Courier New", monospace; 14 | } 15 | 16 | .focused-header { 17 | background-color: #6699aa !important; 18 | } 19 | 20 | .doc-box-header { 21 | height: 25px; 22 | display: flex; 23 | flex-direction: row; 24 | align-items: center; 25 | 26 | background-color: #6699aa70; 27 | 28 | transition: background-color 0.15s ease-in-out; 29 | -webkit-transition: background-color 0.15s ease-in-out; 30 | -moz-transition: background-color 0.15s ease-in-out; 31 | -o-transition: background-color 0.15s ease-in-out; 32 | -ms-transition: background-color 0.15s ease-in-out; 33 | 34 | cursor: grab; 35 | } 36 | 37 | .doc-box-header:hover { 38 | background-color: #578; 39 | } 40 | 41 | .doc-title { 42 | color: #fff; 43 | font-size: 16px; 44 | margin: 0 0 0 15px; 45 | } 46 | 47 | .close-button { 48 | margin-left: auto; 49 | margin-top: 1px; 50 | font-weight: bold; 51 | color: #fff; 52 | font-size: 27px; 53 | 54 | transition: background-color 0.15s ease-in-out; 55 | -webkit-transition: background-color 0.15s ease-in-out; 56 | -moz-transition: background-color 0.15s ease-in-out; 57 | -o-transition: background-color 0.15s ease-in-out; 58 | -ms-transition: background-color 0.15s ease-in-out; 59 | 60 | cursor: pointer; 61 | padding: 0px 10px; 62 | } 63 | 64 | .close-button:hover { 65 | color: #000; 66 | } 67 | 68 | .doc-body { 69 | overflow-y: auto; 70 | width: calc(100% - 30px); 71 | height: calc(100% - 25px); 72 | padding: 0 15px 0 15px; 73 | font-family: monospace; 74 | font-size: 15px; 75 | } 76 | 77 | .doc-editor { 78 | width: 100%; 79 | border: solid 1px #eee; 80 | } 81 | 82 | .doc-body::-webkit-scrollbar { 83 | background: #ccc; 84 | margin: 5px; 85 | width: 8px; 86 | } 87 | 88 | .doc-body::-webkit-scrollbar-track { 89 | background: #ebebeb; 90 | } 91 | 92 | .doc-body::-webkit-scrollbar-thumb { 93 | border: none; 94 | background-color: #b8ccd1; 95 | border-radius: 0px; 96 | } 97 | 98 | div.doc-body p span.italics { 99 | font-style: italic; 100 | } 101 | 102 | div.doc-body p span.code { 103 | background-color: #ddd; 104 | border-radius: 3px; 105 | padding: 1px 5px; 106 | font-weight: bold; 107 | } 108 | 109 | div.doc-body p span.bold { 110 | font-weight: bold; 111 | } 112 | 113 | div.doc-body > div.doc-editor:nth-last-child(1) { 114 | margin-bottom: 7%; 115 | } 116 | 117 | .doc-editor-container { 118 | border-top: solid 1px #ccc; 119 | } 120 | 121 | .console-output::-webkit-scrollbar { 122 | background: #ccc; 123 | margin: 5px; 124 | width: 8px; 125 | } 126 | 127 | .console-output::-webkit-scrollbar-track { 128 | background: #c1c1c1; 129 | } 130 | 131 | .console-output::-webkit-scrollbar-thumb { 132 | border: none; 133 | background-color: #8c8c8c; 134 | border-radius: 0px; 135 | } 136 | 137 | .doc-example-console { 138 | background-color: #ccc; 139 | font-size: 14px; 140 | font-weight: bold; 141 | } 142 | 143 | .doc-example-console p { 144 | padding: 0; 145 | margin: 0; 146 | } 147 | 148 | .doc-editor-header { 149 | background-color: #17a564; 150 | color: #fff; 151 | font-weight: bold; 152 | padding: 4px 8px; 153 | font-size: 14px; 154 | } 155 | 156 | .doc-example-btn { 157 | padding: 5px 10px !important; 158 | font-size: 12px !important; 159 | } 160 | 161 | .reset-editor-btn { 162 | visibility: hidden; 163 | } 164 | 165 | .block-vs-text-table-container { 166 | border-radius: 5px; 167 | box-shadow: 0 0 5px 1px #888; 168 | } 169 | 170 | .block-vs-text-table-header { 171 | height: 20px; 172 | background-color: #d9e7ee; 173 | display: flex; 174 | flex-direction: row; 175 | justify-content: space-between; 176 | align-items: center; 177 | padding: 5px 15px; 178 | font-size: 12px; 179 | font-weight: bold; 180 | } 181 | 182 | .image-container { 183 | flex-direction: row; 184 | justify-content: space-between; 185 | display: flex; 186 | align-items: start; 187 | padding: 15px; 188 | } 189 | 190 | .image-container img { 191 | width: 48%; 192 | } 193 | 194 | .console-output { 195 | height: 100px; 196 | max-height: 0px; 197 | overflow-y: scroll; 198 | 199 | color: #000; 200 | 201 | transition: max-height 0.2s ease-in-out; 202 | -webkit-transition: max-height 0.2s ease-in-out; 203 | -moz-transition: max-height 0.2s ease-in-out; 204 | -o-transition: max-height 0.2s ease-in-out; 205 | -ms-transition: max-height 0.2s ease-in-out; 206 | } 207 | 208 | .console-output-open { 209 | padding: 5px; 210 | max-height: 100px; 211 | } 212 | 213 | .doc-example-console-button-container { 214 | border-bottom: solid 1px#bbb; 215 | padding: 5px; 216 | } 217 | -------------------------------------------------------------------------------- /src/utilities/util.ts: -------------------------------------------------------------------------------- 1 | import { ConstructDoc } from "../suggestions/construct-doc"; 2 | import { CodeConstruct, Importable } from "../syntax-tree/ast"; 3 | import { Module } from "../syntax-tree/module"; 4 | import { addClassToDraftModeResolutionButton, DataType, ListTypes } from "./../syntax-tree/consts"; 5 | 6 | /** 7 | * IMPORTANT!!! 8 | * 9 | * constructKeys and ConstructKeys need to have the same values. 10 | * 11 | * The enum is so that we can get a dummy construct anywhere in the code. 12 | * The list is so that we can loop over all dumy constructs since Map does not have a public keys property. 13 | * 14 | * In regular JS we could always call Object.keys(ConstructKeys), but not in TS. 15 | */ 16 | export const constructKeys = [ 17 | "VarAssign", 18 | "print()", 19 | "randint()", 20 | "range()", 21 | "len()", 22 | "string", 23 | "int", 24 | "True", 25 | "False", 26 | "+", 27 | "-", 28 | "*", 29 | "/", 30 | "And", 31 | "Or", 32 | "Not", 33 | "==", 34 | "!=", 35 | "<", 36 | "<=", 37 | ">", 38 | ">=", 39 | "while", 40 | "If", 41 | "Elif", 42 | "Else", 43 | "For", 44 | "List Literal", 45 | ".append()", 46 | "List Element Access", 47 | ".split()", 48 | ".join()", 49 | ".replace()", 50 | ".find()", 51 | "List Element Assignment", 52 | ]; 53 | 54 | export class Util { 55 | private static instance: Util; 56 | 57 | constructDocs: Map; 58 | typeConversionMap: Map>; 59 | 60 | module: Module; 61 | 62 | private constructor(module?: Module) { 63 | if (module) { 64 | this.module = module; 65 | } 66 | 67 | const context = this.module.focus.getContext(); 68 | 69 | //these cannot exist on their own, need to wrap them in a class. Otherwise they does not see the imports for the construct classes. 70 | 71 | //stores information about what types an object or literal of a given type can be converted to either through casting or 72 | //some other manipulation such as [number] or number === --- or accessing some property such as list.length > 0 73 | this.typeConversionMap = new Map>([ 74 | [DataType.Void, []], 75 | [DataType.Number, [DataType.String, DataType.NumberList, DataType.Boolean]], 76 | [DataType.String, [DataType.StringList, DataType.Boolean, DataType.Number]], 77 | [DataType.Boolean, [DataType.BooleanList]], 78 | [DataType.AnyList, [DataType.Any, DataType.Number, DataType.Number]], 79 | [DataType.NumberList, [DataType.Number, DataType.Boolean]], 80 | [DataType.BooleanList, [DataType.Number, DataType.Boolean]], 81 | [DataType.StringList, [DataType.Number, DataType.String, DataType.Boolean]], 82 | [DataType.Any, [DataType.AnyList]], 83 | ]); 84 | 85 | this.constructDocs = new Map(); 86 | } 87 | 88 | static getInstance(module?: Module) { 89 | if (!Util.instance) Util.instance = new Util(module); 90 | 91 | return Util.instance; 92 | } 93 | 94 | static getPopulatedInstance() { 95 | return Util.instance; 96 | } 97 | } 98 | 99 | export function areEqualTypes(incoming: DataType, receiving: DataType): boolean { 100 | if (receiving == DataType.Any) return true; 101 | else if (receiving == DataType.AnyList && ListTypes.indexOf(incoming) > -1) return true; 102 | else if (receiving == incoming) return true; 103 | 104 | return false; 105 | } 106 | 107 | /** 108 | * Return whether list1 contains at least one item from list2. 109 | */ 110 | export function hasMatch(list1: any[], list2: any[]): boolean { 111 | if (list2?.length == 0 || list1?.length == 0) return false; 112 | 113 | if (list2) { 114 | for (const item of list2) { 115 | if (list1?.indexOf(item) > -1) return true; 116 | } 117 | } 118 | 119 | return false; 120 | } 121 | 122 | export function hasMatchWithIndex(list1: T[], list2: T[]): [number, number] { 123 | const matchingIndices: [number, number] = [-1, -1]; 124 | 125 | if (list1.length === 0 || list2.length === 0) { 126 | return matchingIndices; 127 | } 128 | 129 | for (let i = 0; i < list2.length; i++) { 130 | if (list1.indexOf(list2[i]) > -1) { 131 | matchingIndices[0] = list1.indexOf(list2[i]); 132 | matchingIndices[1] = i; 133 | } 134 | } 135 | 136 | return matchingIndices; 137 | } 138 | 139 | export function isImportable(object: unknown): object is Importable { 140 | return Object.prototype.hasOwnProperty.call(object, "requiredModule"); //calling hasOwnProperty with call() because 'object' is not necessarily an object 141 | } 142 | 143 | export function getUserFriendlyType(type: DataType): string { 144 | switch (type) { 145 | case DataType.Any: 146 | return "any"; 147 | 148 | case DataType.AnyList: 149 | return "list"; 150 | 151 | case DataType.Boolean: 152 | return "boolean"; 153 | 154 | case DataType.BooleanList: 155 | return "boolean list"; 156 | 157 | case DataType.Number: 158 | return "number"; 159 | 160 | case DataType.NumberList: 161 | return "number list"; 162 | 163 | case DataType.String: 164 | return "text"; 165 | 166 | case DataType.StringList: 167 | return "text list"; 168 | 169 | case DataType.Iterator: 170 | return "iterator"; 171 | 172 | default: 173 | return type; 174 | } 175 | } 176 | 177 | export function createWarningButton(buttonTxt: string, warningCode: CodeConstruct, action: Function): HTMLDivElement { 178 | const button = document.createElement("div"); 179 | button.innerHTML = buttonTxt; 180 | button.classList.add("button"); 181 | button.onclick = () => { 182 | action(); 183 | }; 184 | addClassToDraftModeResolutionButton(button, warningCode); 185 | 186 | return button; 187 | } 188 | -------------------------------------------------------------------------------- /src/syntax-tree/type-checker.ts: -------------------------------------------------------------------------------- 1 | import { BinaryOperatorExpr, CodeConstruct, Expression, TypedEmptyExpr } from "./ast"; 2 | import { 3 | BinaryOperator, 4 | DataType, 5 | definedBinOpsBetweenType, 6 | definedBinOpsForType, 7 | definedUnaryOpsForType, 8 | ListTypes, 9 | TypeConversionRecord, 10 | typeToConversionRecord, 11 | UnaryOperator, 12 | } from "./consts"; 13 | import { Module } from "./module"; 14 | 15 | export class TypeChecker { 16 | static varTypeMap: Map = new Map(); 17 | static listTypes: Array; 18 | 19 | module: Module; 20 | 21 | constructor(module: Module) { 22 | if (!TypeChecker.listTypes) { 23 | //it does not recognize the imports unless they are assigned inside the constructor 24 | TypeChecker.listTypes = [ 25 | DataType.AnyList, 26 | DataType.StringList, 27 | DataType.NumberList, 28 | DataType.BooleanList, 29 | DataType.String, 30 | ]; 31 | } 32 | 33 | this.module = module; 34 | } 35 | 36 | /** 37 | * Recursively set all empty holes (TypedEmptyExpr) in an expression to the provided type newTypes. 38 | * 39 | * @param parentConstruct parent Statement of the expression 40 | * @param newTypes types to use 41 | */ 42 | static setAllHolesToType(parentConstruct: Expression, newTypes: DataType[], setParentType: boolean = false) { 43 | if (setParentType) parentConstruct.returns = newTypes[0]; 44 | 45 | for (const tkn of parentConstruct.tokens) { 46 | if (tkn instanceof BinaryOperatorExpr) { 47 | this.setAllHolesToType(tkn, newTypes); 48 | } else if (tkn instanceof TypedEmptyExpr) { 49 | tkn.type = newTypes; 50 | } 51 | } 52 | } 53 | 54 | /** 55 | * Return the corresponding type of list given the type of element. 56 | * 57 | * @param type element type 58 | * @returns corresponding list type (one of: StringList, NumberList, BooleanList, AnyList) 59 | */ 60 | static getListTypeFromElementType(type: DataType) { 61 | switch (type) { 62 | case DataType.String: 63 | return DataType.StringList; 64 | 65 | case DataType.Number: 66 | return DataType.NumberList; 67 | 68 | case DataType.Boolean: 69 | return DataType.BooleanList; 70 | 71 | default: 72 | return DataType.AnyList; 73 | } 74 | } 75 | 76 | /** 77 | * Deduce element type from list type and return it. 78 | * 79 | * @param listType type of list 80 | * @returns type of elements contained in listType 81 | */ 82 | static getElementTypeFromListType(listType: DataType) { 83 | switch (listType) { 84 | case DataType.String: 85 | return DataType.String; 86 | 87 | case DataType.AnyList: 88 | return DataType.Any; 89 | 90 | case DataType.StringList: 91 | return DataType.String; 92 | 93 | case DataType.BooleanList: 94 | return DataType.Boolean; 95 | 96 | case DataType.NumberList: 97 | return DataType.Number; 98 | 99 | default: 100 | return DataType.Any; 101 | } 102 | } 103 | 104 | //get conversion records for a construct of type convertFrom to type convertTo 105 | static getTypeConversionRecords(convertFrom: DataType, convertTo: DataType): TypeConversionRecord[] { 106 | const records = []; 107 | if (typeToConversionRecord.has(convertFrom)) { 108 | records.push(...typeToConversionRecord.get(convertFrom).filter((record) => record.convertTo === convertTo)); 109 | 110 | //Anything can be converted to a list of that type and lists of different types usually still have operations defined for them (ex. you can add [True] and [1]) 111 | if (ListTypes.indexOf(convertFrom) === -1 && ListTypes.indexOf(convertTo) > -1) { 112 | records.push( 113 | ...typeToConversionRecord 114 | .get(convertFrom) 115 | .filter((record) => ListTypes.indexOf(record.convertTo) > -1) 116 | ); 117 | } 118 | } 119 | 120 | return records; 121 | } 122 | 123 | //get all conversion buttons for a particular construct given its conversion records for each type 124 | static getConversionButtons( 125 | conversionRecords: TypeConversionRecord[], 126 | module: Module, 127 | itemToConvertKeyword: string, 128 | codeToReplaceOnConversion: CodeConstruct 129 | ) { 130 | if (conversionRecords.length === 0) return []; 131 | 132 | const buttons = []; 133 | for (const record of conversionRecords) { 134 | buttons.push(record.getConversionButton(itemToConvertKeyword, module, codeToReplaceOnConversion)); 135 | } 136 | 137 | return buttons; 138 | } 139 | 140 | static isBinOpAllowed(op: BinaryOperator, type1: DataType, type2: DataType): boolean { 141 | const typeCombinationsForOp = definedBinOpsBetweenType.has(op) ? definedBinOpsBetweenType.get(op) : []; 142 | 143 | for (const combination of typeCombinationsForOp) { 144 | if ( 145 | (combination[0] === type1 && combination[1] === type2) || 146 | (combination[0] === type2 && combination[1] === type1) 147 | ) 148 | return true; 149 | } 150 | 151 | return ( 152 | type1 === type2 && 153 | definedBinOpsForType.has(type1) && 154 | definedBinOpsForType.get(type1).indexOf(op) > -1 && 155 | definedBinOpsForType.has(type2) && 156 | definedBinOpsForType.get(type2).indexOf(op) > -1 157 | ); 158 | } 159 | 160 | static getAllowedBinaryOperatorsForType(type: DataType): BinaryOperator[] { 161 | if (definedBinOpsForType.has(type)) return definedBinOpsForType.get(type); 162 | 163 | return []; 164 | } 165 | 166 | static getAllowedUnaryOperatorsForType(type: DataType): UnaryOperator[] { 167 | if (definedBinOpsForType.has(type)) return definedUnaryOpsForType.get(type); 168 | 169 | return []; 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/editor/accordion.ts: -------------------------------------------------------------------------------- 1 | import { LogEvent, Logger, LogType } from "./../logger/analytics"; 2 | export enum TooltipType { 3 | StepByStepExample = "step-by-step-example", 4 | UsageHint = "usage-hint", 5 | RunnableExample = "runnable-example", 6 | } 7 | 8 | export class AccordionRow { 9 | private accordion: Accordion; 10 | private isOpen: boolean = false; 11 | private chevronElement: HTMLElement; 12 | private contentContainer: HTMLDivElement; 13 | element: HTMLDivElement; 14 | id: string; 15 | usageTime: number = 0; 16 | type: TooltipType; 17 | 18 | constructor( 19 | accordion: Accordion, 20 | id: string, 21 | type: TooltipType, 22 | title: string, 23 | content: HTMLDivElement, 24 | onClick: () => void = () => {} 25 | ) { 26 | this.type = type; 27 | this.id = id; 28 | this.accordion = accordion; 29 | 30 | this.element = document.createElement("div"); 31 | this.element.classList.add("accordion-row"); 32 | 33 | const headerContainer = document.createElement("div"); 34 | headerContainer.classList.add("header-container"); 35 | 36 | this.contentContainer = document.createElement("div"); 37 | this.contentContainer.classList.add("content-container"); 38 | this.contentContainer.style.maxHeight = "0px"; 39 | this.contentContainer.appendChild(content); 40 | 41 | this.element.appendChild(headerContainer); 42 | this.element.appendChild(this.contentContainer); 43 | 44 | const textContainer = document.createElement("div"); 45 | textContainer.classList.add("text-container"); 46 | 47 | const typeContainer = document.createElement("div"); 48 | typeContainer.classList.add("type-container"); 49 | 50 | const icon = document.createElement("i"); 51 | icon.classList.add("row-icon"); 52 | let typeText = ""; 53 | 54 | switch (type) { 55 | case TooltipType.StepByStepExample: { 56 | icon.innerHTML = zapIconSVG; 57 | typeText = "learn"; 58 | typeContainer.classList.add("bg-learn"); 59 | 60 | break; 61 | } 62 | 63 | case TooltipType.UsageHint: { 64 | icon.innerHTML = lightBulbIconSVG; 65 | typeText = "hint"; 66 | typeContainer.classList.add("bg-hint"); 67 | 68 | break; 69 | } 70 | 71 | case TooltipType.RunnableExample: { 72 | icon.innerHTML = playIconSVG; 73 | typeText = "try"; 74 | typeContainer.classList.add("bg-try"); 75 | 76 | break; 77 | } 78 | } 79 | 80 | const typeElement = document.createElement("span"); 81 | typeElement.classList.add("row-type"); 82 | typeElement.innerHTML = typeText; 83 | 84 | const titleElement = document.createElement("span"); 85 | titleElement.classList.add("row-title"); 86 | titleElement.innerHTML = title; 87 | 88 | const chevronRightIcon = document.createElement("i"); 89 | chevronRightIcon.classList.add("row-chevron-right-icon"); 90 | chevronRightIcon.innerHTML = chevronRightIconSVG; 91 | 92 | typeContainer.appendChild(icon); 93 | typeContainer.appendChild(typeElement); 94 | textContainer.appendChild(typeContainer); 95 | textContainer.appendChild(titleElement); 96 | 97 | this.chevronElement = document.createElement("i"); 98 | this.chevronElement.classList.add("expand-collapse-button"); 99 | this.chevronElement.innerHTML = chevronDownIconSVG; 100 | 101 | headerContainer.addEventListener("click", () => { 102 | if (this.isOpen) { 103 | this.close(); 104 | 105 | this.sendUsageDuration(); 106 | } else { 107 | this.open(); 108 | onClick(); 109 | 110 | this.usageTime = Date.now(); 111 | } 112 | }); 113 | 114 | headerContainer.appendChild(textContainer); 115 | headerContainer.appendChild(this.chevronElement); 116 | } 117 | 118 | sendUsageDuration = () => { 119 | const duration = Date.now() - this.usageTime; 120 | 121 | if (duration > 1500) { 122 | Logger.Instance().queueEvent(new LogEvent(LogType.TooltipItemUsage, { type: this.type, duration })); 123 | 124 | this.usageTime = 0; 125 | } 126 | }; 127 | 128 | open() { 129 | this.contentContainer.style.maxHeight = this.contentContainer.scrollHeight + "px"; 130 | 131 | setTimeout(() => { 132 | this.contentContainer.style.maxHeight = "1000px"; 133 | }, 350); 134 | 135 | this.chevronElement.innerHTML = chevronUpIconSVG; 136 | 137 | this.accordion.rows.forEach((row) => { 138 | if (row !== this) { 139 | row.close(); 140 | } 141 | }); 142 | 143 | this.isOpen = true; 144 | } 145 | 146 | close() { 147 | this.contentContainer.style.maxHeight = "0px"; 148 | this.chevronElement.innerHTML = chevronDownIconSVG; 149 | 150 | this.isOpen = false; 151 | } 152 | 153 | onRemove() { 154 | this.sendUsageDuration(); 155 | } 156 | } 157 | 158 | export class Accordion { 159 | rows = new Array(); 160 | private id: string; 161 | container: HTMLDivElement; 162 | 163 | constructor(id: string) { 164 | this.id = id; 165 | 166 | this.container = document.createElement("div"); 167 | this.container.classList.add("accordion-group-container"); 168 | } 169 | 170 | addRow(type: TooltipType, title: string, content: HTMLDivElement, onClick: () => void = () => {}) { 171 | const id = this.id + "-" + this.rows.length; 172 | const row = new AccordionRow(this, id, type, title, content, onClick); 173 | this.rows.push(row); 174 | this.container.appendChild(row.element); 175 | } 176 | 177 | onRemove() { 178 | if (this?.rows) { 179 | this.rows.forEach((row) => { 180 | row.onRemove(); 181 | }); 182 | } 183 | } 184 | } 185 | 186 | const playIconSVG = ``; 187 | const lightBulbIconSVG = ``; 188 | const zapIconSVG = ``; 189 | const chevronUpIconSVG = ``; 190 | const chevronDownIconSVG = ``; 191 | const chevronRightIconSVG = ``; 192 | -------------------------------------------------------------------------------- /src/editor/hole.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CodeConstruct, 3 | EditableTextTkn, 4 | EmptyOperatorTkn, 5 | ForStatement, 6 | IdentifierTkn, 7 | OperatorTkn, 8 | TypedEmptyExpr, 9 | VarAssignmentStmt, 10 | } from "../syntax-tree/ast"; 11 | import { Callback, CallbackType } from "../syntax-tree/callback"; 12 | import { InsertionType } from "../syntax-tree/consts"; 13 | import { Module } from "../syntax-tree/module"; 14 | import { Reference } from "../syntax-tree/scope"; 15 | import { Editor } from "./editor"; 16 | import { Context } from "./focus"; 17 | import { Validator } from "./validator"; 18 | 19 | export class Hole { 20 | static editableHoleClass = "editableHole"; 21 | static validVarIdentifierHole = "validVarIdentifierHole"; 22 | static draftVarIdentifierHole = "draftVarIdentifierHole"; 23 | static holes: Hole[] = []; 24 | static module: Module; 25 | 26 | element: HTMLDivElement; 27 | editor: Editor; 28 | code: CodeConstruct; 29 | container: HTMLElement; 30 | 31 | constructor(editor: Editor, code: CodeConstruct) { 32 | this.editor = editor; 33 | this.code = code; 34 | 35 | // DOM elements 36 | const element = document.createElement("div"); 37 | element.classList.add("hole"); 38 | 39 | this.container = document.querySelector(".lines-content.monaco-editor-background"); 40 | this.container.append(element); 41 | 42 | this.element = element; 43 | const hole = this; 44 | 45 | Hole.holes.push(hole); 46 | 47 | if (code instanceof EmptyOperatorTkn) this.element.classList.add("empty-operator-hole"); 48 | else if (code instanceof IdentifierTkn) this.element.classList.add("identifier-hole"); 49 | else if (code instanceof EditableTextTkn) { 50 | this.element.classList.add("text-editable-expr-hole"); 51 | } else if (code instanceof TypedEmptyExpr) { 52 | this.element.classList.add("expression-hole"); 53 | } 54 | 55 | if (code instanceof EditableTextTkn || code instanceof IdentifierTkn || code instanceof OperatorTkn) { 56 | code.subscribe( 57 | CallbackType.focusEditableHole, 58 | new Callback(() => { 59 | this.element.classList.add(Hole.editableHoleClass); 60 | }) 61 | ); 62 | } else if (code instanceof TypedEmptyExpr) { 63 | code.subscribe( 64 | CallbackType.showAvailableVars, 65 | new Callback(() => { 66 | const c = Hole.module.focus.getContext(); 67 | const focusedNode = c.token && c.selected ? c.token : c.lineStatement; 68 | 69 | const refInsertionTypes = Validator.getValidVariableReferences( 70 | focusedNode, 71 | Hole.module.variableController 72 | ); 73 | 74 | const validIdentifierIds = refInsertionTypes.map((ref) => [ 75 | ((ref[0] as Reference).statement as VarAssignmentStmt).buttonId, 76 | (ref[0] as Reference).line(), 77 | ]); 78 | 79 | const refInsertionTypeMap = new Map(); 80 | for (let i = 0; i < validIdentifierIds.length; i++) { 81 | refInsertionTypeMap.set(validIdentifierIds[i][0] as string, [ 82 | refInsertionTypes[i][1], 83 | validIdentifierIds[i][1] as number, 84 | ]); 85 | } 86 | 87 | for (const hole of Hole.holes) { 88 | if ( 89 | (hole.code.rootNode instanceof VarAssignmentStmt || 90 | hole.code.rootNode instanceof ForStatement) && 91 | hole.code instanceof IdentifierTkn && 92 | refInsertionTypeMap.has(hole.code.rootNode.buttonId) 93 | ) { 94 | if (hole.code.getLineNumber() < this.editor.monaco.getPosition().lineNumber) { 95 | if (refInsertionTypeMap.get(hole.code.rootNode.buttonId)[0] === InsertionType.Valid) { 96 | hole.element.classList.add(Hole.validVarIdentifierHole); 97 | } else if ( 98 | refInsertionTypeMap.get(hole.code.rootNode.buttonId)[0] === InsertionType.DraftMode 99 | ) { 100 | hole.element.classList.add(Hole.draftVarIdentifierHole); 101 | } 102 | } 103 | } 104 | } 105 | }) 106 | ); 107 | } 108 | 109 | code.subscribe( 110 | CallbackType.delete, 111 | new Callback(() => { 112 | hole.setTransform(null); 113 | hole.remove(); 114 | }) 115 | ); 116 | 117 | code.subscribe( 118 | CallbackType.replace, 119 | new Callback(() => { 120 | hole.setTransform(null); 121 | hole.remove(); 122 | }) 123 | ); 124 | 125 | code.subscribe( 126 | CallbackType.fail, 127 | new Callback(() => { 128 | hole.element.style.background = `rgba(255, 0, 0, 0.06)`; 129 | 130 | setTimeout(() => { 131 | hole.element.style.background = `rgba(255, 0, 0, 0)`; 132 | }, 1000); 133 | }) 134 | ); 135 | 136 | function loop() { 137 | hole.setTransform(code); 138 | requestAnimationFrame(loop); 139 | } 140 | 141 | loop(); 142 | } 143 | 144 | setTransform(code: CodeConstruct) { 145 | let leftPadding = 0; 146 | let rightPadding = 0; 147 | let transform = { x: 0, y: 0, width: 0, height: 0 }; 148 | 149 | if (code) { 150 | transform = this.editor.computeBoundingBox(code.getSelection()); 151 | 152 | if (transform.width == 0) { 153 | transform.x -= 7; 154 | transform.width = 14; 155 | } 156 | } 157 | 158 | this.element.style.top = `${transform.y + 5}px`; 159 | this.element.style.left = `${transform.x - leftPadding}px`; 160 | 161 | this.element.style.width = `${transform.width + rightPadding}px`; 162 | this.element.style.height = `${transform.height - 5 * 2}px`; 163 | } 164 | 165 | remove() { 166 | this.element.remove(); 167 | Hole.holes.splice(Hole.holes.indexOf(this), 1); 168 | } 169 | 170 | static setModule(module: Module) { 171 | this.module = module; 172 | } 173 | 174 | static disableEditableHoleOutlines() { 175 | Hole.holes.forEach((hole) => { 176 | hole.element.classList.remove(Hole.editableHoleClass); 177 | }); 178 | } 179 | 180 | static disableVarHighlights() { 181 | Hole.holes.forEach((hole) => { 182 | hole.element.classList.remove(Hole.validVarIdentifierHole); 183 | hole.element.classList.remove(Hole.draftVarIdentifierHole); 184 | }); 185 | } 186 | 187 | static outlineTextEditableHole(context: Context) { 188 | if (context.token && (context.token instanceof IdentifierTkn || context.token instanceof EditableTextTkn)) { 189 | context.token.notify(CallbackType.focusEditableHole); 190 | } else if ( 191 | context.tokenToRight && 192 | (context.tokenToRight instanceof IdentifierTkn || context.tokenToRight instanceof EditableTextTkn) 193 | ) { 194 | context.tokenToRight.notify(CallbackType.focusEditableHole); 195 | } else if ( 196 | context.tokenToLeft && 197 | (context.tokenToLeft instanceof IdentifierTkn || context.tokenToLeft instanceof EditableTextTkn) 198 | ) { 199 | context.tokenToLeft.notify(CallbackType.focusEditableHole); 200 | } 201 | } 202 | 203 | static highlightValidVarHoles(context: Context) { 204 | if (context.selected && context.token && context.token instanceof TypedEmptyExpr) { 205 | context.token.notify(CallbackType.showAvailableVars); 206 | } 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/syntax-tree/scope.ts: -------------------------------------------------------------------------------- 1 | import { hasMatchWithIndex } from "../utilities/util"; 2 | import { CodeConstruct, ForStatement, Statement, VarAssignmentStmt } from "./ast"; 3 | import { Module } from "./module"; 4 | 5 | /** 6 | * These scopes are created by multi-line statements 7 | */ 8 | export class Scope { 9 | parentScope: Scope = null; 10 | references = new Array(); 11 | 12 | isValidReference(uniqueId: string, line: number): boolean { 13 | const validReferences = this.getValidReferences(line); 14 | 15 | for (let ref of validReferences) { 16 | if ( 17 | (ref.statement instanceof VarAssignmentStmt && ref.statement.buttonId == uniqueId) || 18 | (ref.statement instanceof ForStatement && ref.statement.buttonId == uniqueId) 19 | ) { 20 | return true; 21 | } 22 | } 23 | 24 | return false; 25 | } 26 | 27 | getValidReferences(line: number): Array { 28 | let validReferences = this.references.filter((ref) => ref.line() < line); 29 | 30 | if (this.parentScope != null) { 31 | validReferences = validReferences.concat(this.parentScope.getValidReferences(line)); 32 | } 33 | 34 | return validReferences; 35 | } 36 | 37 | //return all existing references to the variable with the given identifier in this scope 38 | //we can be sure that there is at most one variable with this identifier in the scope 39 | //because we disallow creation of duplicates through checks when a new variable is created 40 | //NOTE: the references are tied to variable assignment statements so this is equivalent to finding all assignments to a variable 41 | getAllAssignmentsToVariableWithinScope(identifier: string, excludeStmt?: VarAssignmentStmt | ForStatement) { 42 | let validReferences = this.references.filter((ref) => { 43 | if (ref.statement instanceof ForStatement) { 44 | return ref.statement.loopVar.getIdentifier() === identifier && excludeStmt !== ref.statement; 45 | } else if (ref.statement instanceof VarAssignmentStmt) { 46 | return ref.statement.getIdentifier() === identifier && excludeStmt !== ref.statement; 47 | } 48 | }); 49 | 50 | if (this.parentScope != null) { 51 | validReferences = validReferences.concat( 52 | this.parentScope.getAllAssignmentsToVariableWithinScope(identifier) 53 | ); 54 | } 55 | 56 | return validReferences; 57 | } 58 | 59 | static getAllScopesOfStmt(stmt: Statement) { 60 | let currStatement: Statement | Module = stmt; 61 | const scopes: Scope[] = []; 62 | 63 | while (currStatement && !(currStatement instanceof Module)) { 64 | scopes.push((currStatement.rootNode as Statement | Module).scope); 65 | currStatement = currStatement.rootNode as Statement | Module; 66 | } 67 | 68 | return scopes; 69 | } 70 | 71 | private getAllAssignmentsToVar(identifier: string, module: Module) { 72 | const assignments: VarAssignmentStmt[] = []; 73 | //Find all assignments to vars with this identifier 74 | const Q: CodeConstruct[] = []; 75 | Q.push(...module.body); 76 | 77 | let currNode; 78 | while (Q.length > 0) { 79 | currNode = Q.splice(0, 1)[0]; 80 | 81 | if (currNode instanceof VarAssignmentStmt && currNode.getIdentifier() === identifier) { 82 | assignments.push(currNode); 83 | } else if (currNode instanceof ForStatement && currNode.loopVar.getIdentifier() === identifier) { 84 | assignments.push(currNode.loopVar); 85 | } 86 | 87 | if (currNode instanceof Statement) { 88 | Q.push(...currNode.tokens); 89 | Q.push(...currNode.body); 90 | } 91 | } 92 | 93 | return assignments; 94 | } 95 | 96 | /** 97 | * This method determines whether an assignment to a given variable exists and would be covered by the scope at 98 | * lineNumber. If not, then we are creating a new variable. It returns all such assignments in an array. 99 | */ 100 | getAllVarAssignmentsToNewVar( 101 | identifier: string, 102 | module: Module, 103 | lineNumber: number, 104 | excludeStmt: VarAssignmentStmt = null 105 | ) { 106 | let assignments: VarAssignmentStmt[] = this.getAllAssignmentsToVar(identifier, module); 107 | 108 | //We know these are the same vaiable if their scopes match at some point 109 | let statement = module.focus.getStatementAtLineNumber(lineNumber); 110 | 111 | //find the scope that contains the current line 112 | let workingScope = statement.scope; 113 | let currStatement = statement; 114 | while (!workingScope && currStatement && currStatement.rootNode) { 115 | workingScope = (currStatement.rootNode as Module | Statement).scope; 116 | 117 | if (currStatement.rootNode instanceof Module) { 118 | break; 119 | } else { 120 | currStatement = currStatement.rootNode as Statement; 121 | } 122 | } 123 | 124 | //filter out variable assignments that are not in this scope 125 | assignments = assignments.filter((assignmentStmt) => { 126 | if (assignmentStmt !== excludeStmt) { 127 | const newAssignmentScopes = Scope.getAllScopesOfStmt(excludeStmt); 128 | const oldAssignmentScopes = Scope.getAllScopesOfStmt(assignmentStmt); 129 | const matchInfo = hasMatchWithIndex(newAssignmentScopes, oldAssignmentScopes); 130 | 131 | if (lineNumber < assignmentStmt.lineNumber) { 132 | //new var is above old var assignment; new is in-scope of old 133 | return true; 134 | } else if (lineNumber > assignmentStmt.lineNumber && matchInfo[0] < matchInfo[1]) { 135 | //new is below old assignment, if scope of old assignment is at least one level deeper than the scope of the new var assign, they are diff vars 136 | return false; 137 | } else if (matchInfo[0] === matchInfo[1]) { 138 | //if var scopes are on the same level, then they are the same as long as the roots of both assignments match 139 | return excludeStmt ? assignmentStmt.rootNode === excludeStmt.rootNode : false; 140 | } else { 141 | return excludeStmt ? assignmentStmt.scope === excludeStmt.scope : false; //two vars are in same scope 142 | } 143 | } 144 | }); 145 | 146 | return assignments; 147 | } 148 | 149 | getAllAssignmentsToVarAboveLine( 150 | identifier: string, 151 | module: Module, 152 | lineNumber: number, 153 | excludeCurrentLine: boolean = true 154 | ) { 155 | if (excludeCurrentLine) { 156 | return this.getAllAssignmentsToVar(identifier, module).filter((stmt) => stmt.lineNumber < lineNumber); 157 | } 158 | 159 | return this.getAllAssignmentsToVar(identifier, module).filter((stmt) => stmt.lineNumber <= lineNumber); 160 | } 161 | 162 | replaceReferenceStatement(currStmt: VarAssignmentStmt, newStmt: VarAssignmentStmt) { 163 | const ref = this.references.filter((ref) => ref.statement === currStmt)[0]; //only one reference per var in scope 164 | ref.statement = newStmt; 165 | } 166 | 167 | isParent(potentialChild: Scope): boolean { 168 | if (!potentialChild) return false; 169 | 170 | let curr = potentialChild.parentScope; 171 | while (curr) { 172 | if (curr === this) return true; 173 | 174 | curr = curr.parentScope; 175 | } 176 | 177 | return false; 178 | } 179 | } 180 | 181 | export class Reference { 182 | /** 183 | * Currently, either a variable or a function declaration. Could later be a class declaration. 184 | */ 185 | statement: Statement; 186 | 187 | /** 188 | * The valid scope in which this item could be referenced. 189 | */ 190 | scope: Scope; 191 | 192 | constructor(statement: Statement, scope: Scope) { 193 | this.statement = statement; 194 | this.scope = scope; 195 | } 196 | 197 | line(): number { 198 | return this.statement.lineNumber; 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /src/editor/doc-box.ts: -------------------------------------------------------------------------------- 1 | import { editor } from "monaco-editor"; 2 | import { nova, runBtnToOutputWindow } from "../index"; 3 | import { attachPyodideActions, codeString } from "../pyodide-js/pyodide-controller"; 4 | import { addTextToConsole, clearConsole, CONSOLE_ERR_TXT_CLASS } from "../pyodide-ts/pyodide-ui"; 5 | 6 | const INITIAL_Z_INDEX = 500; 7 | 8 | export const docBoxRunButtons = new Map(); 9 | 10 | export class ExecutableCode { 11 | private static exampleCounter = 0; 12 | private static openBoxes: DocBoxMeta[] = []; 13 | private static pressedEscape = false; 14 | 15 | constructor(uniqueId: string, documentation: any) { 16 | const container = document.createElement("div"); 17 | container.classList.add("doc-box-container"); 18 | container.id = `doc-box-${uniqueId}`; 19 | docBoxRunButtons.set(container.id, []); 20 | 21 | const headerDiv = document.createElement("div"); 22 | headerDiv.classList.add("doc-box-header"); 23 | 24 | const closeButton = document.createElement("div"); 25 | closeButton.classList.add("close-button"); 26 | closeButton.innerHTML = `×`; 27 | 28 | const docTitle = document.createElement("h3"); 29 | docTitle.classList.add("doc-title"); 30 | docTitle.innerText = documentation.title; 31 | headerDiv.appendChild(docTitle); 32 | 33 | headerDiv.appendChild(closeButton); 34 | container.appendChild(headerDiv); 35 | 36 | document.body.appendChild(container); 37 | 38 | // the documentation: 39 | const docBody = document.createElement("div"); 40 | docBody.classList.add("doc-body"); 41 | container.appendChild(docBody); 42 | 43 | for (const item of documentation.body) { 44 | if (item.hasOwnProperty("paragraph")) { 45 | const p = document.createElement("p"); 46 | p.innerHTML = item.paragraph; 47 | 48 | docBody.appendChild(p); 49 | } else if (item.hasOwnProperty("example")) { 50 | const ex = createExample(item); 51 | docBody.appendChild(ex[0]); 52 | docBoxRunButtons.set(container.id, ex[1]); 53 | 54 | attachPyodideActions( 55 | (() => { 56 | const actions = []; 57 | 58 | for (const buttonId of ex[1]) { 59 | actions.push((pyodideController) => { 60 | const button = document.getElementById(buttonId); 61 | 62 | button.addEventListener("click", () => { 63 | try { 64 | nova.globals.lastPressedRunButtonId = button.id; 65 | 66 | clearConsole(ex[3]); 67 | pyodideController.runPython(codeString(ex[2].getValue())); 68 | } catch (err) { 69 | console.error("Unable to run python code"); 70 | 71 | addTextToConsole( 72 | runBtnToOutputWindow.get(button.id), 73 | err, 74 | CONSOLE_ERR_TXT_CLASS 75 | ); 76 | } 77 | }); 78 | }); 79 | } 80 | 81 | return actions; 82 | })(), 83 | [] 84 | ); 85 | } else if (item.hasOwnProperty("block-based-image")) { 86 | docBody.appendChild(createImage(item)); 87 | } 88 | } 89 | 90 | window.addEventListener("mousedown", function (e) { 91 | if (container.contains(e.target as Element)) ExecutableCode.focusBox(container.id); 92 | else headerDiv.classList.remove("focused-header"); 93 | }); 94 | 95 | closeButton.onclick = () => { 96 | ExecutableCode.closeBox(container.id); 97 | }; 98 | 99 | document.addEventListener("keydown", (ev) => { 100 | if (ev.key == "Escape") { 101 | ExecutableCode.pressedEscape = true; 102 | } 103 | }); 104 | 105 | document.addEventListener("keyup", (ev) => { 106 | if (ev.key == "Escape" && ExecutableCode.pressedEscape) { 107 | const focusedBox = ExecutableCode.openBoxes.find((box) => box.isFocused); 108 | if (focusedBox) ExecutableCode.closeBox(focusedBox.id); 109 | 110 | ExecutableCode.pressedEscape = false; 111 | } 112 | }); 113 | 114 | ExecutableCode.addNewBox(container.id); 115 | } 116 | 117 | static getNewConsoleId(): string { 118 | return "console-id-" + ExecutableCode.exampleCounter++; 119 | } 120 | 121 | static addNewBox(id: string) { 122 | let newZIndex = INITIAL_Z_INDEX; 123 | 124 | if (ExecutableCode.openBoxes.length > 0) { 125 | newZIndex = Math.max(...ExecutableCode.openBoxes.map((box) => box.zIndex)) + 1; 126 | } 127 | 128 | ExecutableCode.openBoxes.push(new DocBoxMeta(id, true, newZIndex)); 129 | ExecutableCode.setZIndex(id, newZIndex); 130 | ExecutableCode.focusBox(id); 131 | } 132 | 133 | static closeBox(id: string) { 134 | // should become the highest 135 | ExecutableCode.focusBox(id); 136 | 137 | document.getElementById(id).remove(); 138 | ExecutableCode.openBoxes.splice( 139 | ExecutableCode.openBoxes.findIndex((box) => box.id == id), 140 | 1 141 | ); 142 | 143 | const maxZIndex = Math.max(...ExecutableCode.openBoxes.map((box) => box.zIndex)); 144 | const maxZIndexId = ExecutableCode.openBoxes.find((box) => box.zIndex == maxZIndex)?.id; 145 | 146 | if (maxZIndexId) ExecutableCode.focusBox(maxZIndexId); 147 | 148 | for (const buttonId of docBoxRunButtons.get(id)) { 149 | runBtnToOutputWindow.delete(buttonId); 150 | } 151 | docBoxRunButtons.delete(id); 152 | } 153 | 154 | static setZIndex(id: string, zIndex: number) { 155 | document.getElementById(id).style.zIndex = `${zIndex}`; 156 | } 157 | 158 | static focusBox(id: string) { 159 | const box = ExecutableCode.openBoxes.find((box) => box.id == id); 160 | const boxElement = document.getElementById(box?.id); 161 | 162 | if (box && boxElement) { 163 | const boxHeader = boxElement.getElementsByClassName("doc-box-header")[0]; 164 | boxHeader.classList.add("focused-header"); 165 | 166 | const maxZIndex = Math.max(...ExecutableCode.openBoxes.map((box) => box.zIndex)); 167 | const maxZIndexId = ExecutableCode.openBoxes.find((box) => box.zIndex == maxZIndex)?.id; 168 | 169 | box.zIndex = maxZIndex; 170 | box.isFocused = true; 171 | ExecutableCode.setZIndex(box.id, box.zIndex); 172 | 173 | ExecutableCode.openBoxes.forEach((box) => { 174 | if (box.id != id) { 175 | box.isFocused = false; 176 | 177 | if (maxZIndexId != id && box.zIndex != INITIAL_Z_INDEX) box.zIndex--; 178 | ExecutableCode.setZIndex(box.id, box.zIndex); 179 | } 180 | }); 181 | } 182 | } 183 | } 184 | 185 | class DocBoxMeta { 186 | id: string; 187 | isFocused: boolean; 188 | zIndex: number; 189 | 190 | constructor(id: string, isFocused: boolean, zIndex: number) { 191 | this.id = id; 192 | this.isFocused = isFocused; 193 | this.zIndex = zIndex; 194 | } 195 | } 196 | 197 | function createImage(image): HTMLDivElement { 198 | const tableElement = document.createElement("div"); 199 | tableElement.classList.add("block-vs-text-table-container"); 200 | const tableHeader = document.createElement("div"); 201 | tableHeader.classList.add("block-vs-text-table-header"); 202 | tableElement.appendChild(tableHeader); 203 | 204 | const blockHeader = document.createElement("span"); 205 | blockHeader.innerText = "block-based"; 206 | blockHeader.classList.add("block-based-header"); 207 | tableHeader.appendChild(blockHeader); 208 | 209 | const textHeader = document.createElement("span"); 210 | textHeader.innerText = "text-based"; 211 | textHeader.classList.add("text-based-header"); 212 | tableHeader.appendChild(textHeader); 213 | 214 | const imageContainer = document.createElement("div"); 215 | imageContainer.classList.add("image-container"); 216 | 217 | const blockImage = document.createElement("img"); 218 | blockImage.src = image["block-based-image"]; 219 | blockImage.alt = image.alt; 220 | blockImage.classList.add("block-image"); 221 | imageContainer.appendChild(blockImage); 222 | 223 | const textImage = document.createElement("img"); 224 | textImage.src = image["text-based-image"]; 225 | textImage.alt = image.alt; 226 | textImage.classList.add("text-image"); 227 | imageContainer.appendChild(textImage); 228 | 229 | tableElement.appendChild(imageContainer); 230 | 231 | return tableElement; 232 | } 233 | 234 | export function createExample(example: string): [HTMLDivElement, string[], editor.IStandaloneCodeEditor, string] { 235 | const codeLines = example.split("\n").length; 236 | const runButtons = []; 237 | 238 | const editorContainer = document.createElement("div"); 239 | editorContainer.classList.add("doc-editor-container"); 240 | 241 | const exampleEditor = document.createElement("div"); 242 | exampleEditor.classList.add("doc-editor"); 243 | exampleEditor.style.height = codeLines * 20 + "px"; 244 | editorContainer.appendChild(exampleEditor); 245 | 246 | const exampleConsole = document.createElement("div"); 247 | exampleConsole.classList.add("doc-example-console"); 248 | editorContainer.appendChild(exampleConsole); 249 | 250 | const buttonContainer = document.createElement("div"); 251 | buttonContainer.classList.add("doc-example-console-button-container"); 252 | exampleConsole.appendChild(buttonContainer); 253 | 254 | const consoleId = ExecutableCode.getNewConsoleId(); 255 | 256 | const runButton = document.createElement("div"); 257 | runButton.innerText = "> Run"; 258 | runButton.id = `run-${consoleId}`; 259 | runButton.classList.add(...["console-button", "run-code-btn", "doc-example-btn"]); 260 | buttonContainer.appendChild(runButton); 261 | 262 | const clearConsoleButton = document.createElement("div"); 263 | clearConsoleButton.innerText = "Clear"; 264 | clearConsoleButton.id = `clear-${consoleId}`; 265 | clearConsoleButton.classList.add(...["doc-example-btn", "console-button", "clear-output-btn"]); 266 | buttonContainer.appendChild(clearConsoleButton); 267 | 268 | const resetConsoleButton = document.createElement("div"); 269 | resetConsoleButton.innerText = "Reset"; 270 | resetConsoleButton.id = `reset-${consoleId}`; 271 | resetConsoleButton.classList.add(...["doc-example-btn", "console-button", "reset-editor-btn"]); 272 | buttonContainer.appendChild(resetConsoleButton); 273 | 274 | const consoleOutput = document.createElement("div"); 275 | consoleOutput.id = `console-output-${consoleId}`; 276 | consoleOutput.classList.add("console-output"); 277 | exampleConsole.appendChild(consoleOutput); 278 | 279 | runBtnToOutputWindow.set(runButton.id, consoleOutput.id); 280 | clearConsoleButton.addEventListener("click", () => { 281 | clearConsole(consoleOutput.id); 282 | }); 283 | runButtons.push(runButton.id); 284 | 285 | const codeEditor = editor.create(exampleEditor, { 286 | folding: false, 287 | value: example, 288 | language: "python3.6", 289 | dimension: { width: 200, height: codeLines * 20 }, 290 | minimap: { 291 | enabled: false, 292 | }, 293 | overviewRulerLanes: 0, 294 | overviewRulerBorder: false, 295 | contextmenu: false, 296 | codeLens: false, 297 | dragAndDrop: false, 298 | mouseWheelScrollSensitivity: 0, 299 | automaticLayout: true, 300 | scrollBeyondLastLine: false, 301 | scrollbar: { 302 | vertical: "auto", 303 | horizontal: "auto", 304 | verticalSliderSize: 5, 305 | horizontalSliderSize: 5, 306 | scrollByPage: false, 307 | }, 308 | occurrencesHighlight: false, 309 | fontSize: 14, 310 | lineHeight: 20, 311 | }); 312 | 313 | codeEditor.onDidChangeModelContent(() => { 314 | resetConsoleButton.style.visibility = "visible"; 315 | }); 316 | 317 | resetConsoleButton.addEventListener("click", () => { 318 | codeEditor.setValue(example); 319 | }); 320 | 321 | runButton.addEventListener("click", () => { 322 | consoleOutput.classList.add("console-output-open"); 323 | }); 324 | 325 | clearConsoleButton.addEventListener("click", () => { 326 | consoleOutput.classList.remove("console-output-open"); 327 | }); 328 | 329 | return [editorContainer, runButtons, codeEditor, consoleOutput.id]; 330 | } 331 | -------------------------------------------------------------------------------- /src/editor/editor.ts: -------------------------------------------------------------------------------- 1 | import { editor, KeyCode, KeyMod, languages, Range, Selection } from "monaco-editor"; 2 | import { 3 | CodeConstruct, 4 | EditableTextTkn, 5 | EmptyOperatorTkn, 6 | IdentifierTkn, 7 | Statement, 8 | TypedEmptyExpr, 9 | } from "../syntax-tree/ast"; 10 | import { TAB_SPACES } from "../syntax-tree/consts"; 11 | import { Module } from "../syntax-tree/module"; 12 | import { Cursor } from "./cursor"; 13 | import { Hole } from "./hole"; 14 | 15 | const FONT_SIZE = 20; 16 | 17 | export class Editor { 18 | module: Module; 19 | cursor: Cursor; 20 | monaco: editor.IStandaloneCodeEditor; 21 | holes: Hole[]; 22 | mousePosWindow: number[] = [0, 0]; 23 | scrollOffsetTop: number = 0; 24 | oldCursorLineNumber: number = 1; 25 | mousePosMonaco: any; 26 | 27 | constructor(parentEl: HTMLElement, module: Module) { 28 | languages.register({ id: "python3.6" }); 29 | languages.setMonarchTokensProvider("python3.6", { 30 | defaultToken: "", 31 | tokenPostfix: ".python", 32 | 33 | keywords: [ 34 | "and", 35 | "as", 36 | "assert", 37 | "break", 38 | "class", 39 | "continue", 40 | "def", 41 | "del", 42 | "elif", 43 | "else", 44 | "except", 45 | "exec", 46 | "finally", 47 | "for", 48 | "from", 49 | "global", 50 | "if", 51 | "import", 52 | "in", 53 | "is", 54 | "lambda", 55 | "None", 56 | "not", 57 | "or", 58 | "pass", 59 | "print", 60 | "raise", 61 | "return", 62 | "self", 63 | "try", 64 | "while", 65 | "with", 66 | "yield", 67 | 68 | "int", 69 | "float", 70 | "long", 71 | "complex", 72 | "hex", 73 | 74 | "abs", 75 | "all", 76 | "any", 77 | "apply", 78 | "basestring", 79 | "bin", 80 | "bool", 81 | "buffer", 82 | "bytearray", 83 | "callable", 84 | "chr", 85 | "classmethod", 86 | "cmp", 87 | "coerce", 88 | "compile", 89 | "complex", 90 | "delattr", 91 | "dict", 92 | "dir", 93 | "divmod", 94 | "enumerate", 95 | "eval", 96 | "execfile", 97 | "file", 98 | "filter", 99 | "format", 100 | "frozenset", 101 | "getattr", 102 | "globals", 103 | "hasattr", 104 | "hash", 105 | "help", 106 | "id", 107 | "input", 108 | "intern", 109 | "isinstance", 110 | "issubclass", 111 | "iter", 112 | "len", 113 | "locals", 114 | "list", 115 | "map", 116 | "max", 117 | "memoryview", 118 | "min", 119 | "next", 120 | "object", 121 | "oct", 122 | "open", 123 | "ord", 124 | "pow", 125 | "print", 126 | "property", 127 | "reversed", 128 | "range", 129 | "raw_input", 130 | "reduce", 131 | "reload", 132 | "repr", 133 | "reversed", 134 | "round", 135 | "set", 136 | "setattr", 137 | "slice", 138 | "sorted", 139 | "staticmethod", 140 | "str", 141 | "sum", 142 | "super", 143 | "tuple", 144 | "type", 145 | "unichr", 146 | "unicode", 147 | "vars", 148 | "xrange", 149 | "zip", 150 | 151 | "True", 152 | "False", 153 | 154 | "__dict__", 155 | "__methods__", 156 | "__members__", 157 | "__class__", 158 | "__bases__", 159 | "__name__", 160 | "__mro__", 161 | "__subclasses__", 162 | "__init__", 163 | "__import__", 164 | ], 165 | 166 | escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, 167 | 168 | brackets: [ 169 | { open: "{", close: "}", token: "delimiter.curly" }, 170 | { open: "[", close: "]", token: "delimiter.bracket" }, 171 | { open: "(", close: ")", token: "delimiter.parenthesis" }, 172 | ], 173 | 174 | tokenizer: { 175 | root: [ 176 | { include: "@whitespace" }, 177 | { include: "@numbers" }, 178 | { include: "@strings" }, 179 | 180 | [/[,:;]/, "delimiter"], 181 | [/[{}\[\]()]/, "@brackets"], 182 | 183 | [/@[a-zA-Z]\w*/, "tag"], 184 | [ 185 | /[a-zA-Z]\w*/, 186 | { 187 | cases: { 188 | "@keywords": "keyword", 189 | "@default": "identifier", 190 | }, 191 | }, 192 | ], 193 | ], 194 | 195 | // Deal with white space, including single and multi-line comments 196 | whitespace: [ 197 | [/\s+/, "white"], 198 | [/(^#.*$)/, "comment"], 199 | [/('''.*''')|(""".*""")/, "string"], 200 | [/'''.*$/, "string", "@endDocString"], 201 | [/""".*$/, "string", "@endDblDocString"], 202 | ], 203 | endDocString: [ 204 | [/\\'/, "string"], 205 | [/.*'''/, "string", "@popall"], 206 | [/.*$/, "string"], 207 | ], 208 | endDblDocString: [ 209 | [/\\"/, "string"], 210 | [/.*"""/, "string", "@popall"], 211 | [/.*$/, "string"], 212 | ], 213 | 214 | // Recognize hex, negatives, decimals, imaginaries, longs, and scientific notation 215 | numbers: [ 216 | [/-?0x([abcdef]|[ABCDEF]|\d)+[lL]?/, "number.hex"], 217 | [/-?(\d*\.)?\d+([eE][+\-]?\d+)?[jJ]?[lL]?/, "number"], 218 | ], 219 | 220 | // Recognize strings, including those broken across lines with \ (but not without) 221 | strings: [ 222 | [/'$/, "string.escape", "@popall"], 223 | [/'/, "string.escape", "@stringBody"], 224 | [/"/, "string", "@string_double"], 225 | [/"/, "string.escape", "@dblStringBody"], 226 | [/f'/, "string", "@string_backtick"], 227 | ], 228 | stringBody: [ 229 | [/[^\\']+$/, "string", "@popall"], 230 | [/[^\\']+/, "string"], 231 | [/\\./, "string"], 232 | [/'/, "string.escape", "@popall"], 233 | [/\\$/, "string"], 234 | ], 235 | dblStringBody: [ 236 | [/[^\\"]+$/, "string", "@popall"], 237 | [/[^\\"]+/, "string"], 238 | [/\\./, "string"], 239 | [/"/, "string.escape", "@popall"], 240 | [/\\$/, "string"], 241 | ], 242 | 243 | string_double: [ 244 | [/[^\\"]+/, "string"], 245 | [/\\./, "string.escape.invalid"], 246 | [/"/, "string", "@pop"], 247 | ], 248 | 249 | string_backtick: [ 250 | [/\{/, { token: "delimiter.curly", next: "@bracketCounting" }], 251 | [/[^\\']/, "string"], 252 | [/@escapes/, "string.escape"], 253 | [/\\./, "string.escape.invalid"], 254 | [/'/, "string", "@pop"], 255 | ], 256 | 257 | bracketCounting: [ 258 | [/\{/, "delimiter.curly", "@bracketCounting"], 259 | [/\}/, "delimiter.curly", "@pop"], 260 | { include: "root" }, 261 | ], 262 | }, 263 | }); 264 | 265 | this.monaco = editor.create(parentEl, { 266 | folding: false, 267 | dimension: { height: 500, width: 700 }, 268 | value: "", 269 | language: "python3.6", 270 | theme: "vs", 271 | minimap: { 272 | enabled: false, 273 | }, 274 | find: { autoFindInSelection: "never" }, 275 | overviewRulerLanes: 0, 276 | automaticLayout: true, 277 | scrollbar: { 278 | vertical: "auto", 279 | horizontal: "auto", 280 | verticalSliderSize: 5, 281 | scrollByPage: false, 282 | }, 283 | overviewRulerBorder: false, 284 | fontSize: FONT_SIZE, 285 | contextmenu: false, 286 | mouseWheelScrollSensitivity: 0, 287 | lineHeight: 40, 288 | selectOnLineNumbers: false, 289 | letterSpacing: -0.5, 290 | codeLens: false, 291 | dragAndDrop: false, 292 | quickSuggestions: { 293 | other: false, 294 | comments: false, 295 | strings: false, 296 | }, 297 | parameterHints: { 298 | enabled: false, 299 | }, 300 | suggestOnTriggerCharacters: false, 301 | acceptSuggestionOnEnter: "off", 302 | tabCompletion: "off", 303 | wordBasedSuggestions: false, 304 | renderWhitespace: "none", 305 | occurrencesHighlight: false, 306 | }); 307 | 308 | this.monaco.addCommand(KeyMod.CtrlCmd | KeyCode.KEY_Z, () => { 309 | return; 310 | }); 311 | 312 | this.cursor = new Cursor(this); 313 | this.holes = []; 314 | this.module = module; 315 | } 316 | 317 | getLineEl(ln: number) { 318 | const lines = document.body.getElementsByClassName("view-lines")[0]; 319 | const line = lines.children[ln - 1]; 320 | 321 | return line?.children[0]; 322 | } 323 | 324 | addHoles(code: CodeConstruct) { 325 | for (const hole of this.holes) if (hole.code == code) return; 326 | 327 | if ( 328 | code instanceof EditableTextTkn || 329 | code instanceof TypedEmptyExpr || 330 | code instanceof IdentifierTkn || 331 | code instanceof EmptyOperatorTkn 332 | ) { 333 | this.holes.push(new Hole(this, code)); 334 | } else if (code instanceof Statement) { 335 | const statement = code; 336 | statement.tokens.forEach((token) => this.addHoles(token)); 337 | } 338 | } 339 | 340 | executeEdits(range: Range, code: CodeConstruct, overwrite: string = null) { 341 | let text = overwrite; 342 | 343 | if (overwrite == null) text = code?.getRenderText() ? code.getRenderText() : ""; 344 | 345 | this.monaco.executeEdits("module", [{ range: range, text, forceMoveMarkers: true }]); 346 | 347 | if (code) this.addHoles(code); 348 | 349 | this.monaco.focus(); 350 | } 351 | 352 | indentRecursively(statement: Statement, { backward = false }) { 353 | this.module.editor.executeEdits( 354 | new Range( 355 | statement.lineNumber, 356 | statement.left, 357 | statement.lineNumber, 358 | statement.left - (backward ? TAB_SPACES : 0) 359 | ), 360 | null, 361 | backward ? "" : " " 362 | ); 363 | 364 | if (statement.hasBody()) { 365 | const stmtStack = new Array(); 366 | 367 | stmtStack.unshift(...statement.body); 368 | 369 | while (stmtStack.length > 0) { 370 | const curStmt = stmtStack.pop(); 371 | 372 | this.module.editor.executeEdits( 373 | new Range( 374 | curStmt.lineNumber, 375 | curStmt.left, 376 | curStmt.lineNumber, 377 | curStmt.left - (backward ? TAB_SPACES : 0) 378 | ), 379 | null, 380 | backward ? "" : " " 381 | ); 382 | 383 | if (curStmt.hasBody()) stmtStack.unshift(...curStmt.body); 384 | } 385 | } 386 | } 387 | 388 | insertAtCurPos(codeList: Array) { 389 | const curPos = this.monaco.getPosition(); 390 | let text = ""; 391 | 392 | for (const code of codeList) text += code.getRenderText(); 393 | 394 | const range = new Range(curPos.lineNumber, curPos.column, curPos.lineNumber, curPos.column); 395 | 396 | this.monaco.executeEdits("module", [{ range: range, text, forceMoveMarkers: true }]); 397 | 398 | for (const code of codeList) this.addHoles(code); 399 | } 400 | 401 | computeBoundingBox(selection: Selection) { 402 | const x = this.monaco.getOffsetForColumn(selection.startLineNumber, selection.startColumn); 403 | const y = this.monaco.getTopForLineNumber(selection.startLineNumber); 404 | 405 | const width = this.monaco.getOffsetForColumn(selection.startLineNumber, selection.endColumn) - x; 406 | const height = this.computeCharHeight(); 407 | 408 | return { x, y, width, height }; 409 | } 410 | 411 | computeCharHeight() { 412 | const lines = document.getElementsByClassName("view-lines")[0]; 413 | const line = lines.children[0]; 414 | const boundingBox = line?.getBoundingClientRect(); 415 | 416 | return boundingBox?.height || 0; 417 | } 418 | 419 | computeCharWidth(ln = 1) { 420 | const lines = document.getElementsByClassName("view-lines")[0]; 421 | 422 | const line = lines.children[ln - 1]?.children[0]; 423 | if (line == null) return 0; 424 | 425 | if (line.getBoundingClientRect().width === 0 && line.innerText.length === 0) { 426 | return 0; 427 | } 428 | 429 | return line.getBoundingClientRect().width / line.innerText.length; 430 | } 431 | 432 | computeCharWidthGlobal() { 433 | const lines = document.getElementsByClassName("view-lines")[0]; 434 | 435 | for (let i = 0; i < lines.children.length; i++) { 436 | const line = lines.children[i]?.children[0]; 437 | 438 | if (line.getBoundingClientRect().width !== 0 && line.innerText.length !== 0) { 439 | return line.getBoundingClientRect().width / line.innerText.length; 440 | } 441 | } 442 | 443 | return 0; 444 | } 445 | 446 | computeCharWidthInvisible(ln = 1): number { 447 | let width = this.computeCharWidth(ln); 448 | if (width > 0) return width; 449 | 450 | const lines = Array.from(document.getElementsByClassName("view-lines")[0].children); 451 | 452 | for (const line of lines) { 453 | if (line.children[0] && (line.children[0] as HTMLElement).innerText.length > 0) { 454 | return ( 455 | line.children[0].getBoundingClientRect().width / (line.children[0] as HTMLElement).innerText.length 456 | ); 457 | } 458 | } 459 | return FONT_SIZE / 1.92; //Major hack that probably won't always work, but there is no other way than to manually set 460 | //the value because monaco does not allow you to get font size unless you have a line within 461 | //the viewport of the editor that also has text in it. 462 | } 463 | 464 | reset() { 465 | this.monaco.getModel().setValue(""); 466 | this.holes.forEach((hole) => hole.remove()); 467 | this.holes = []; 468 | } 469 | } 470 | -------------------------------------------------------------------------------- /src/css/toolbox.css: -------------------------------------------------------------------------------- 1 | #toolbox-container { 2 | display: flex; 3 | flex-direction: column; 4 | 5 | box-shadow: 20px -50px 50px -15px #ccc; 6 | 7 | min-width: 375px; 8 | 9 | font-family: Consolas, "Courier New", monospace; 10 | } 11 | 12 | #editor-toolbox { 13 | display: flex; 14 | flex-direction: column; 15 | 16 | overflow-x: hidden; 17 | overflow-y: scroll; 18 | 19 | border-left: solid 1px #ddd; 20 | 21 | height: calc(100% - 75px); 22 | } 23 | 24 | #editor-toolbox .button { 25 | font-size: 15px; 26 | padding: 6px 10px; 27 | 28 | white-space: nowrap; 29 | box-shadow: 0px 1px 5px 2px #ddd; 30 | 31 | transition: 0.15s ease-in-out; 32 | -webkit-transition: 0.15s ease-in-out; 33 | -moz-transition: 0.15s ease-in-out; 34 | -o-transition: 0.15s ease-in-out; 35 | -ms-transition: 0.15s ease-in-out; 36 | 37 | -webkit-user-select: none; /* Safari */ 38 | -moz-user-select: none; /* Firefox */ 39 | -ms-user-select: none; /* IE10+/Edge */ 40 | user-select: none; /* Standard */ 41 | } 42 | 43 | #editor-toolbox .button:hover { 44 | box-shadow: 0px 1px 5px 2px #ccc; 45 | } 46 | 47 | hole1 { 48 | min-width: 25px; 49 | height: 15px; 50 | border-radius: 10px; 51 | box-shadow: 0px 0px 1px 1px #0000005e inset; 52 | margin: 0px 3px; 53 | display: inline-block; 54 | } 55 | 56 | hole2 { 57 | margin: 0px 3px; 58 | display: inline-block; 59 | box-shadow: none; 60 | border: dashed 1px #c7c7c7; 61 | min-width: 12px; 62 | height: 16px; 63 | } 64 | 65 | #user-variables { 66 | height: calc(100% - 25px); 67 | overflow-y: auto; 68 | } 69 | 70 | .var-button { 71 | font-size: 16px; 72 | padding: 3px 14px; 73 | white-space: nowrap; 74 | box-shadow: 0px 1px 5px 2px #ddd; 75 | transition: 0.15s ease-in-out; 76 | -webkit-transition: 0.15s ease-in-out; 77 | font-weight: bold; 78 | background-color: #b200c4; 79 | border-radius: 25px; 80 | cursor: pointer; 81 | color: #fff; 82 | } 83 | 84 | .var-button:hover { 85 | box-shadow: 0px 1px 5px 2px #b200c499; 86 | } 87 | 88 | .var-container-wrapper { 89 | display: flex; 90 | margin-left: 5px; 91 | } 92 | 93 | .var-button-container { 94 | display: flex; 95 | align-items: center; 96 | justify-content: space-between; 97 | 98 | padding: 5px 0; 99 | border-radius: 6px; 100 | 101 | box-shadow: 0 0 0 0 #5de1a5; 102 | 103 | transition: 0.5s ease-in-out; 104 | -webkit-transition: 0.5s ease-in-out; 105 | -moz-transition: 0.5s ease-in-out; 106 | -o-transition: 0.5s ease-in-out; 107 | -ms-transition: 0.5s ease-in-out; 108 | } 109 | 110 | .glowing { 111 | box-shadow: 0 0 10px 6px #5de1a5; 112 | background-color: #c6f5e0; 113 | } 114 | 115 | #editor-toolbox .group { 116 | justify-items: start; 117 | margin: 0 0 20px 10px; 118 | } 119 | 120 | #editor-toolbox .group > p { 121 | grid-column: 1 / span 2; 122 | grid-row: 1 / span 1; 123 | font-weight: bold; 124 | font-size: 20px; 125 | 126 | margin: 5px 0 5px 0; 127 | } 128 | 129 | #editor-toolbox::-webkit-scrollbar { 130 | background: #ccc; 131 | margin: 5px; 132 | width: 8px; 133 | } 134 | 135 | #editor-toolbox::-webkit-scrollbar-track { 136 | background: #ebebeb; 137 | } 138 | 139 | #editor-toolbox::-webkit-scrollbar-thumb { 140 | border: none; 141 | background-color: #b8ccd1; 142 | border-radius: 0px; 143 | } 144 | 145 | #user-variables::-webkit-scrollbar { 146 | background: #ccc; 147 | margin: 5px; 148 | width: 8px; 149 | } 150 | 151 | #user-variables::-webkit-scrollbar-track { 152 | background: #ebebeb; 153 | } 154 | 155 | #user-variables::-webkit-scrollbar-thumb { 156 | border: none; 157 | background-color: #b8ccd1; 158 | border-radius: 0px; 159 | } 160 | 161 | #toolbox-menu { 162 | float: left; 163 | } 164 | 165 | #toolbox-menu .menu-button { 166 | border-radius: 3px; 167 | padding: 5px 10px 5px 10px; 168 | cursor: pointer; 169 | color: #26265a; 170 | font-size: 16px; 171 | 172 | transition: 0.15s ease-in-out; 173 | -webkit-transition: 0.15s ease-in-out; 174 | -moz-transition: 0.15s ease-in-out; 175 | -o-transition: 0.15s ease-in-out; 176 | -ms-transition: 0.15s ease-in-out; 177 | } 178 | 179 | #toolbox-menu .menu-button:hover { 180 | background-color: #e0efff; 181 | font-weight: bold; 182 | } 183 | 184 | #static-toolbox { 185 | height: 70%; 186 | } 187 | 188 | #dynamic-toolbox { 189 | height: 30%; 190 | } 191 | 192 | .box-header { 193 | height: 25px; 194 | background-color: #69a; 195 | color: #fff; 196 | 197 | display: flex; 198 | flex-direction: column; 199 | justify-content: center; 200 | } 201 | 202 | .box-header h2 { 203 | display: block; 204 | margin-block-end: 0px; 205 | margin-block-start: 0px; 206 | font-size: 18px; 207 | font-weight: bold; 208 | margin-left: 10px; 209 | } 210 | 211 | #vars-button-grid { 212 | margin: 5px; 213 | } 214 | 215 | .learn-button { 216 | position: relative; 217 | border-radius: 5px; 218 | border: solid 1px #fff; 219 | padding: 0px 10px; 220 | margin-right: 10px; 221 | font-size: 14px; 222 | color: #006a93; 223 | display: inline-flex; 224 | flex-direction: column; 225 | justify-content: center; 226 | font-weight: bold; 227 | align-items: center; 228 | box-shadow: 0 0 6px 1px rgb(0 71 99); 229 | font-family: Consolas, "Courier New", monospace; 230 | height: 20px; 231 | cursor: pointer; 232 | background-color: #fff; 233 | 234 | transition: background-color 0.15s ease-in-out; 235 | -webkit-transition: background-color 0.15s ease-in-out; 236 | -moz-transition: background-color 0.15s ease-in-out; 237 | -o-transition: background-color 0.15s ease-in-out; 238 | -ms-transition: background-color 0.15s ease-in-out; 239 | } 240 | 241 | .tooltip-container { 242 | font-family: Consolas, "Courier New", monospace; 243 | position: fixed; 244 | display: none; 245 | color: #fff; 246 | border-radius: 10px; 247 | width: 500px; 248 | overflow: hidden; 249 | background: rgb(0 162 225); 250 | box-shadow: 0px 8px 16px 0px rgb(0 0 0 / 20%); 251 | opacity: 0; 252 | 253 | transition: opacity 0.1s ease-in-out; 254 | -webkit-transition: opacity 0.1s ease-in-out; 255 | -moz-transition: opacity 0.1s ease-in-out; 256 | -o-transition: opacity 0.1s ease-in-out; 257 | -ms-transition: opacity 0.1s ease-in-out; 258 | } 259 | 260 | .tooltip-container .tooltip-top { 261 | background-color: rgb(0 106 147); 262 | font-size: 14px; 263 | } 264 | 265 | .tooltip-container .tooltip-header { 266 | display: flex; 267 | flex-direction: row; 268 | align-items: center; 269 | justify-content: space-between; 270 | } 271 | 272 | .tooltip-container .tooltip-header h4 { 273 | font-weight: bold; 274 | font-size: 16px; 275 | margin: 0; 276 | padding: 10px; 277 | } 278 | 279 | .tooltip-container .tooltip-text { 280 | font-size: 14px; 281 | padding: 0 10px 10px; 282 | margin: 0; 283 | } 284 | 285 | .tooltip-container .error-text { 286 | padding: 5px 10px; 287 | color: #000; 288 | background-color: rgb(255 200 200); 289 | box-shadow: 0px 0px 10px 0px rgb(0 65 72); 290 | } 291 | 292 | .tooltip-container .warning-text { 293 | padding: 5px 10px; 294 | color: #000; 295 | background-color: rgb(255 255 205); 296 | box-shadow: 0px 0px 10px 0px rgb(0 65 72); 297 | } 298 | 299 | .tooltip-container .return-type-text { 300 | padding: 5px 10px; 301 | background-color: rgb(0 133 147); 302 | box-shadow: 0px 0px 10px 0px rgb(0 65 72); 303 | } 304 | 305 | .tooltip-container .return-type-text .return-type { 306 | padding: 0 5px; 307 | border-radius: 3px; 308 | background-color: #8d97a3; 309 | color: #000; 310 | font-weight: bold; 311 | } 312 | 313 | .tooltip-container .learn-button:hover { 314 | background-color: rgb(0 106 147); 315 | color: #fff; 316 | } 317 | 318 | .tooltip-container .use-cases-container { 319 | max-height: 300px; 320 | overflow-y: scroll; 321 | background-color: #fff; 322 | padding-bottom: 10px; 323 | } 324 | 325 | .tooltip-container .spacing { 326 | height: 5px; 327 | } 328 | 329 | .tooltip-container .use-cases-container::-webkit-scrollbar { 330 | background: #ccc; 331 | margin: 5px; 332 | width: 8px; 333 | } 334 | 335 | .tooltip-container .use-cases-container::-webkit-scrollbar-track { 336 | background: #ebebeb; 337 | } 338 | 339 | .tooltip-container .use-cases-container::-webkit-scrollbar-thumb { 340 | border: none; 341 | background-color: #b8ccd1; 342 | border-radius: 0px; 343 | } 344 | 345 | .tooltip-container .quick-tip { 346 | border-top: solid 1px #ccc; 347 | padding: 5px; 348 | color: #000; 349 | font-size: 14px; 350 | } 351 | 352 | .tooltip-container .quick-tip .quick-tip-text { 353 | font-size: 13px; 354 | color: #000; 355 | } 356 | 357 | .tooltip-container .quick-tip .quick-tip-title { 358 | font-size: 13px; 359 | color: #fff; 360 | background-color: #00aeae; 361 | padding: 1px 4px; 362 | border-radius: 3px; 363 | margin-right: 5px; 364 | font-weight: bold; 365 | } 366 | 367 | .tooltip-container .single-use-case-container { 368 | color: #000; 369 | font-weight: bold; 370 | border-top: solid 1px #ccc; 371 | } 372 | 373 | .tooltip-container .single-use-case-container .use-case-title { 374 | padding: 5px 5px 5px 10px; 375 | font-weight: bold; 376 | font-size: 13px; 377 | cursor: pointer; 378 | display: flex; 379 | justify-content: space-between; 380 | 381 | transition: background-color 0.15s ease-in-out; 382 | -webkit-transition: background-color 0.15s ease-in-out; 383 | -moz-transition: background-color 0.15s ease-in-out; 384 | -o-transition: background-color 0.15s ease-in-out; 385 | -ms-transition: background-color 0.15s ease-in-out; 386 | } 387 | 388 | .tooltip-container .single-use-case-container .use-case-title:hover { 389 | background-color: #cfe3eb !important; 390 | } 391 | 392 | .tooltip-container .single-use-case-container .use-case-title .use-case-title-header { 393 | /* margin-top: 4px; */ 394 | } 395 | 396 | .tooltip-container .single-use-case-container .use-case-learn-button { 397 | color: #000000; 398 | cursor: pointer; 399 | border-radius: 4px; 400 | font-size: 14px; 401 | padding: 3px 10px; 402 | border: solid 1px #006a938c; 403 | background-color: #006a931f; 404 | 405 | transition: background-color 0.2s ease-in-out; 406 | -webkit-transition: background-color 0.2s ease-in-out; 407 | -moz-transition: background-color 0.2s ease-in-out; 408 | -o-transition: background-color 0.2s ease-in-out; 409 | -ms-transition: background-color 0.2s ease-in-out; 410 | 411 | transition: opacity 0.4 ease-in-out; 412 | -webkit-transition: opacity 0.4 ease-in-out; 413 | -moz-transition: opacity 0.4 ease-in-out; 414 | -o-transition: opacity 0.4 ease-in-out; 415 | -ms-transition: opacity 0.4 ease-in-out; 416 | } 417 | 418 | .tooltip-container .single-use-case-container .use-case-learn-button:hover { 419 | background-color: #006a9338; 420 | } 421 | 422 | .tooltip-container .slider-container { 423 | font-family: Consolas, "Courier New", monospace; 424 | 425 | transition: max-height 0.15s ease-in-out; 426 | -webkit-transition: max-height 0.15s ease-in-out; 427 | -moz-transition: max-height 0.15s ease-in-out; 428 | -o-transition: max-height 0.15s ease-in-out; 429 | -ms-transition: max-height 0.15s ease-in-out; 430 | } 431 | 432 | .tooltip-container .slider-container .range-slider { 433 | display: inline-block; 434 | flex-grow: 1; 435 | } 436 | 437 | .tooltip-container .slider-container .slider-btn { 438 | display: inline-block; 439 | cursor: pointer; 440 | -webkit-user-select: none; 441 | -moz-user-select: none; 442 | -ms-user-select: none; 443 | user-select: none; 444 | background-color: #7017ff; 445 | margin: 0 10px 0; 446 | padding: 5px 10px; 447 | border-radius: 5px; 448 | font-weight: bold; 449 | box-shadow: rgb(0 0 0 / 20%) 0px 3px 1px -2px, rgb(0 0 0 / 14%) 0px 2px 2px 0px, rgb(0 0 0 / 12%) 0px 1px 5px 0px; 450 | color: #fff; 451 | } 452 | 453 | .tooltip-container .slider-container .slider-image { 454 | width: 470px; 455 | display: block; 456 | } 457 | 458 | .tooltip-container .slider-container .labels-container { 459 | display: flex; 460 | font-size: 14px; 461 | justify-content: center; 462 | } 463 | 464 | .tooltip-container .slider-container .slider-label { 465 | border: solid 2px #00719e; 466 | margin: 10px 0 10px 10px; 467 | padding: 3px 7px; 468 | border-radius: 5px; 469 | background-color: #0a82b1; 470 | color: #ffffff; 471 | } 472 | 473 | .tooltip-container .slider-container .explanation-container { 474 | margin: 5px; 475 | padding: 3px 7px; 476 | border-radius: 5px; 477 | background-color: #7017ff; 478 | color: #ffffff; 479 | position: relative; 480 | } 481 | 482 | .tooltip-container .slider-container .explanation-container::after { 483 | content: ""; 484 | position: absolute; 485 | bottom: 98%; 486 | left: 49%; 487 | margin-left: -5px; 488 | border-width: 7px; 489 | border-style: solid; 490 | border-color: transparent transparent #7017ff transparent; 491 | } 492 | 493 | .tooltip-container .slider-container .buttons-container { 494 | display: flex; 495 | margin-bottom: 5px; 496 | } 497 | 498 | .statement-button { 499 | border-bottom: solid #fff0 3.5px; 500 | 501 | transition: border 0.15s ease-in-out; 502 | -webkit-transition: border 0.15s ease-in-out; 503 | -moz-transition: border 0.15s ease-in-out; 504 | -o-transition: border 0.15s ease-in-out; 505 | -ms-transition: border 0.15s ease-in-out; 506 | } 507 | 508 | .statement-button:hover { 509 | border-bottom: solid #05c8ac 3.5px !important; 510 | } 511 | 512 | .expression-button { 513 | border: solid #fff0 3px; 514 | padding-left: 10px !important; 515 | padding-right: 10px !important; 516 | border-radius: 25px !important; 517 | 518 | transition: border 0.15s ease-in-out; 519 | -webkit-transition: border 0.15s ease-in-out; 520 | -moz-transition: border 0.15s ease-in-out; 521 | -o-transition: border 0.15s ease-in-out; 522 | -ms-transition: border 0.15s ease-in-out; 523 | } 524 | 525 | .expression-button:hover { 526 | border: solid #05c8ac 3px !important; 527 | } 528 | 529 | .modifier-button { 530 | border-left: solid #fff0 3.5px; 531 | 532 | transition: border 0.15s ease-in-out; 533 | -webkit-transition: border 0.15s ease-in-out; 534 | -moz-transition: border 0.15s ease-in-out; 535 | -o-transition: border 0.15s ease-in-out; 536 | -ms-transition: border 0.15s ease-in-out; 537 | } 538 | 539 | .modifier-button:hover { 540 | border-left: solid #05c8ac 3.5px !important; 541 | } 542 | 543 | .var-type-text { 544 | align-self: center; 545 | font-size: 14px; 546 | margin-left: 10px; 547 | } 548 | 549 | .search-box { 550 | height: 30px; 551 | width: calc(100% - 20px); 552 | margin: 10px; 553 | box-shadow: 0px 0px 6px 1px #ccc inset; 554 | border: 1px solid #ccc; 555 | border-radius: 6px; 556 | padding: 7px; 557 | font-family: Consolas, "Courier New", monospace; 558 | 559 | transition: box-shadow 0.15s ease-in-out; 560 | -webkit-transition: box-shadow 0.15s ease-in-out; 561 | -moz-transition: box-shadow 0.15s ease-in-out; 562 | -o-transition: box-shadow 0.15s ease-in-out; 563 | -ms-transition: box-shadow 0.15s ease-in-out; 564 | } 565 | 566 | .search-box:hover { 567 | box-shadow: 0px 0px 6px 1px #aaa inset; 568 | font-weight: bold; 569 | } 570 | 571 | .search-box:focus-visible { 572 | border: 1px solid #bbb; 573 | outline: none; 574 | font-weight: bold; 575 | } 576 | 577 | .def-vars-type-title-span { 578 | font-style: italic; 579 | } 580 | 581 | .def-vars-type-span { 582 | font-style: normal; 583 | font-weight: bold; 584 | color: #006bff; 585 | } 586 | 587 | .defined-var-container { 588 | border-bottom: solid #ccc 1px; 589 | flex-direction: column; 590 | display: flex; 591 | } 592 | 593 | .immediate-tooltip { 594 | display: inline-block; 595 | box-shadow: 0px 1px 5px 2px #ddd; 596 | padding: 3px 8px; 597 | border-radius: 2px; 598 | margin-left: 6px; 599 | } 600 | 601 | .immediate-tooltips-container { 602 | font-size: 13px; 603 | } 604 | 605 | .cascaded-menu-extra-container { 606 | background-color: #008593; 607 | padding: 10px; 608 | } 609 | 610 | .cascaded-menu-extra-item { 611 | border-radius: 4px; 612 | border: solid 1px #ddd; 613 | padding: 5px 10px; 614 | color: #fff; 615 | } 616 | 617 | .cascaded-menu-extra-item:not(:last-child) { 618 | margin-bottom: 5px; 619 | } 620 | 621 | .cascaded-menu-extra-item .code { 622 | color: #0f0fff; 623 | border-radius: 4px; 624 | padding: 0px 6px; 625 | background-color: #fff; 626 | font-weight: bold; 627 | } 628 | 629 | .cascaded-menu-extra-item .inline-var { 630 | color: #aa5bc8; 631 | } 632 | -------------------------------------------------------------------------------- /src/editor/action-filter.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Expression, 3 | ForStatement, 4 | ListComma, 5 | Modifier, 6 | Statement, 7 | TypedEmptyExpr, 8 | ValueOperationExpr, 9 | VarAssignmentStmt, 10 | VariableReferenceExpr, 11 | VarOperationStmt, 12 | } from "../syntax-tree/ast"; 13 | import { InsertionType, TypeConversionRecord } from "../syntax-tree/consts"; 14 | import { Module } from "../syntax-tree/module"; 15 | import { Reference } from "../syntax-tree/scope"; 16 | import { getUserFriendlyType } from "../utilities/util"; 17 | import { ActionExecutor } from "./action-executor"; 18 | import { Actions, InsertActionType } from "./consts"; 19 | import { EventRouter } from "./event-router"; 20 | import { Context } from "./focus"; 21 | import { Validator } from "./validator"; 22 | 23 | export class ActionFilter { 24 | module: Module; 25 | 26 | constructor(module: Module) { 27 | this.module = module; 28 | } 29 | 30 | validateInsertions(): Map { 31 | const context = this.module.focus.getContext(); 32 | const validOptionMap: Map = new Map(); 33 | //need to know InsertionType in case we want to make any visual changes to those options in the suggestion menu 34 | 35 | // loop over all code-constructs and call their validateContext() + typeValidation() => insertionType 36 | // we are assuming that the action executor will calculate the insertionType again in the exectue() function 37 | for (const action of Actions.instance().actionsList) { 38 | validOptionMap.set( 39 | action.optionName, 40 | EditCodeAction.createDynamicEditCodeAction( 41 | action.optionName, 42 | action.cssId, 43 | action.getCodeFunction, 44 | action.insertActionType, 45 | action.insertData, 46 | action.validateAction(this.module.validator, context), 47 | action.terminatingChars, 48 | action.matchString, 49 | action.matchRegex, 50 | action.insertableTerminatingCharRegex 51 | ) 52 | ); 53 | } 54 | 55 | return validOptionMap; 56 | } 57 | 58 | validateEdits(): Map { 59 | // console.warn("validateEdits() is not implemented."); 60 | 61 | return new Map(); 62 | } 63 | 64 | validateVariableInsertions(): Map { 65 | const context = this.module.focus.getContext(); 66 | const validOptionMap: Map = new Map(); //