Browse Source

Added ide to github pages (initial)

tags/gm/2021-09-23T00Z/github.com--lark-parser-lark/0.8.6
Erez Sh 4 years ago
parent
commit
87bc7aa914
17 changed files with 4701 additions and 0 deletions
  1. +8
    -0
      docs/ide/__init__.py
  2. +105
    -0
      docs/ide/app.js
  3. +76
    -0
      docs/ide/app.py
  4. +150
    -0
      docs/ide/examples.py
  5. +10
    -0
      docs/ide/files.json
  6. +4
    -0
      docs/ide/html5/.gitignore
  7. +93
    -0
      docs/ide/html5/CHANGELOG.md
  8. +165
    -0
      docs/ide/html5/LICENSE
  9. +69
    -0
      docs/ide/html5/README.md
  10. +6
    -0
      docs/ide/html5/__init__.py
  11. +3152
    -0
      docs/ide/html5/core.py
  12. +475
    -0
      docs/ide/html5/ext.py
  13. +186
    -0
      docs/ide/html5/ignite.py
  14. +101
    -0
      docs/ide/html5/utils.py
  15. +101
    -0
      docs/ide/index.html
  16. BIN
      docs/ide/is-loading.gif
  17. BIN
      docs/ide/lark-logo.png

+ 8
- 0
docs/ide/__init__.py View File

@@ -0,0 +1,8 @@
from . import html5, app


def start():
html5.Body().appendChild(
app.App()
)


+ 105
- 0
docs/ide/app.js View File

@@ -0,0 +1,105 @@
class app {

constructor(modules, invocation){
languagePluginLoader.then(() => {
// If you don't require for pre-loaded Python packages, remove this promise below.
window.pyodide.runPythonAsync("import setuptools, micropip").then(()=>{
window.pyodide.runPythonAsync("micropip.install('lark-parser')").then(()=>{
this.fetchSources(modules).then(() => {
window.pyodide.runPythonAsync("import " + Object.keys(modules).join("\nimport ") + "\n" + invocation + "\n").then(() => this.initializingComplete());
});
});
});
});
}

loadSources(module, baseURL, files) {
let promises = [];

for (let f in files) {
promises.push(
new Promise((resolve, reject) => {
let file = files[f];
let url = (baseURL ? baseURL + "/" : "") + file;

fetch(url, {}).then((response) => {
if (response.status === 200)
return response.text().then((code) => {
let path = ("/lib/python3.7/site-packages/" + module + "/" + file).split("/");
let lookup = "";

for (let i in path) {
if (!path[i]) {
continue;
}

lookup += (lookup ? "/" : "") + path[i];

if (parseInt(i) === path.length - 1) {
window.pyodide._module.FS.writeFile(lookup, code);
console.debug(`fetched ${lookup}`);
} else {
try {
window.pyodide._module.FS.lookupPath(lookup);
} catch {
window.pyodide._module.FS.mkdir(lookup);
console.debug(`created ${lookup}`);
}
}
}

resolve();
});
else
reject();
});
})
);
}

return Promise.all(promises);
}

fetchSources(modules) {
let promises = [];

for( let module of Object.keys(modules) )
{
promises.push(
new Promise((resolve, reject) => {
fetch(`${modules[module]}/files.json`, {}).then((response) => {
if (response.status === 200) {
response.text().then((list) => {
let files = JSON.parse(list);

this.loadSources(module, modules[module], files).then(() => {
resolve();
})
})
} else {
reject();
}
})
}));
}

return Promise.all(promises).then(() => {
for( let module of Object.keys(modules) ) {
window.pyodide.loadedPackages[module] = "default channel";
}

window.pyodide.runPython(
'import importlib as _importlib\n' +
'_importlib.invalidate_caches()\n'
);
});
}

initializingComplete() {
document.body.classList.remove("is-loading")
}
}

(function () {
window.top.app = new app({"app": "."}, "app.start()");
})();

+ 76
- 0
docs/ide/app.py View File

@@ -0,0 +1,76 @@
from . import html5
from .examples import examples

from lark import Lark
from lark.tree import Tree


class App(html5.Div):
def __init__(self):
super().__init__("""
<h1>
<img src="lark-logo.png"> IDE
</h1>

<main>
<menu>
<select [name]="examples">
<option disabled selected>Examples</option>
</select>
<select [name]="parser">
<option value="earley" selected>Earley (default)</option>
<option value="lalr">LALR</option>
<option value="cyk">CYK</option>
</select>
</menu>
<div id="inputs">
<div>
Grammar:
<textarea [name]="grammar" id="grammar" placeholder="Lark Grammar..."></textarea>
</div>
<div>
Input:
<textarea [name]="input" id="input" placeholder="Parser input..."></textarea>
</div>
</div>
<div id="result">
<ul [name]="ast" />
</div>
</main>
""")
self.sinkEvent("onKeyUp", "onChange")

self.parser = "earley"

# Pre-load examples
for name, (grammar, input) in examples.items():
option = html5.Option(name)
option.grammar = grammar
option.input = input

self.examples.appendChild(option)

def onChange(self, e):
if html5.utils.doesEventHitWidgetOrChildren(e, self.examples):
example = self.examples.children(self.examples["selectedIndex"])
self.grammar["value"] = example.grammar.strip()
self.input["value"] = example.input.strip()
self.onKeyUp()

elif html5.utils.doesEventHitWidgetOrChildren(e, self.parser):
self.parser = self.parser.children(self.parser["selectedIndex"])["value"]
self.onKeyUp()

def onKeyUp(self, e=None):
l = Lark(self.grammar["value"], parser=self.parser)

try:
ast = l.parse(self.input["value"])
except Exception as e:
self.ast.appendChild(
html5.Li(str(e)), replace=True
)

print(ast)
traverse = lambda node: html5.Li([node.data, html5.Ul([traverse(c) for c in node.children])] if isinstance(node, Tree) else node)
self.ast.appendChild(traverse(ast), replace=True)

+ 150
- 0
docs/ide/examples.py View File

@@ -0,0 +1,150 @@

# Examples formattet this way:
# "name": ("grammar", "demo-input")

examples = {

# --- hello.lark ---
"hello.lark": ("""
start: WORD "," WORD "!"

%import common.WORD // imports from terminal library
%ignore " " // Disregard spaces in text
""", "Hello, World!"),

# --- calc.lark ---
"calc.lark": ("""
?start: sum
| NAME "=" sum -> assign_var

?sum: product
| sum "+" product -> add
| sum "-" product -> sub

?product: atom
| product "*" atom -> mul
| product "/" atom -> div

?atom: NUMBER -> number
| "-" atom -> neg
| NAME -> var
| "(" sum ")"

%import common.CNAME -> NAME
%import common.NUMBER
%import common.WS_INLINE
%ignore WS_INLINE""",
"1 + 2 * 3 + 4"),

# --- json.lark ---
"json.lark": ("""
?start: value
?value: object
| array
| string
| SIGNED_NUMBER -> number
| "true" -> true
| "false" -> false
| "null" -> null
array : "[" [value ("," value)*] "]"
object : "{" [pair ("," pair)*] "}"
pair : string ":" value
string : ESCAPED_STRING
%import common.ESCAPED_STRING
%import common.SIGNED_NUMBER
%import common.WS
%ignore WS""",
"""
[
{
"_id": "5edb875cf3d764da55602437",
"index": 0,
"guid": "3dae2206-5d4d-41fe-b81d-dc8cdba7acaa",
"isActive": false,
"balance": "$2,872.54",
"picture": "http://placehold.it/32x32",
"age": 24,
"eyeColor": "blue",
"name": "Theresa Vargas",
"gender": "female",
"company": "GEEKOL",
"email": "theresavargas@geekol.com",
"phone": "+1 (930) 450-3445",
"address": "418 Herbert Street, Sexton, Florida, 1375",
"about": "Id minim deserunt laborum enim. Veniam commodo incididunt amet aute esse duis veniam occaecat nulla esse aute et deserunt eiusmod. Anim elit ullamco minim magna sint laboris. Est consequat quis deserunt excepteur in magna pariatur laborum quis eu. Ex quis tempor elit qui qui et culpa sunt sit esse mollit cupidatat. Fugiat cillum deserunt enim minim irure reprehenderit est. Voluptate nisi quis amet quis incididunt pariatur nostrud Lorem consectetur adipisicing voluptate.\\r\\n",
"registered": "2016-11-19T01:02:42 -01:00",
"latitude": -25.65267,
"longitude": 104.19531,
"tags": [
"eiusmod",
"reprehenderit",
"anim",
"sunt",
"esse",
"proident",
"esse"
],
"friends": [
{
"id": 0,
"name": "Roth Herrera"
},
{
"id": 1,
"name": "Callie Christian"
},
{
"id": 2,
"name": "Gracie Whitfield"
}
],
"greeting": "Hello, Theresa Vargas! You have 6 unread messages.",
"favoriteFruit": "banana"
},
{
"_id": "5edb875c845eb08161a83e64",
"index": 1,
"guid": "a8ada2c1-e2c7-40d3-96b4-52c93baff7f0",
"isActive": false,
"balance": "$2,717.04",
"picture": "http://placehold.it/32x32",
"age": 23,
"eyeColor": "green",
"name": "Lily Ross",
"gender": "female",
"company": "RODEOMAD",
"email": "lilyross@rodeomad.com",
"phone": "+1 (941) 465-3561",
"address": "525 Beekman Place, Blodgett, Marshall Islands, 3173",
"about": "Aliquip duis proident excepteur eiusmod in quis officia consequat culpa eu et ut. Occaecat reprehenderit tempor mollit do eu magna qui et magna exercitation aliqua. Incididunt exercitation dolor proident eiusmod minim occaecat. Sunt et minim mollit et veniam sint ex. Duis ullamco elit aute eu excepteur reprehenderit officia.\\r\\n",
"registered": "2019-11-02T04:06:42 -01:00",
"latitude": 17.031701,
"longitude": -42.657106,
"tags": [
"id",
"non",
"culpa",
"reprehenderit",
"esse",
"elit",
"sit"
],
"friends": [
{
"id": 0,
"name": "Ursula Maldonado"
},
{
"id": 1,
"name": "Traci Huff"
},
{
"id": 2,
"name": "Taylor Holt"
}
],
"greeting": "Hello, Lily Ross! You have 3 unread messages.",
"favoriteFruit": "strawberry"
}
]""")
}

+ 10
- 0
docs/ide/files.json View File

@@ -0,0 +1,10 @@
[
"__init__.py",
"app.py",
"examples.py",
"html5/__init__.py",
"html5/core.py",
"html5/ext.py",
"html5/ignite.py",
"html5/utils.py"
]

+ 4
- 0
docs/ide/html5/.gitignore View File

@@ -0,0 +1,4 @@
__target__
__pycache__
*.pyc
.idea

+ 93
- 0
docs/ide/html5/CHANGELOG.md View File

@@ -0,0 +1,93 @@
# Changelog

This file documents any relevant changes done to ViUR html5 since version 2.

## 3.0.0 [develop]

This is the current development version.

- Feature: Ported framework to Python 3 using [Pyodide](https://github.com/iodide-project/pyodide), with a full source code and library cleanup
- Feature: `html5.Widget.__init__()` now allows parameters equal to `Widget.appendChild()` to directly stack widgets together.
Additionally, the following parameters are available:
- `appendTo`: Directly append the newly created widget to another widget.
- `style`: Provide class attributes for styling added to the new Widget, using `Widget.addClass()`.
- Feature: `html5.Widget.appendChild()` and `html5.Widget.prependChild()` can handle arbitrary input now, including HTML, lists of widgets or just text, in any order. `html5.Widget.insertChild()` runs slightly different, but shares same features. This change mostly supersedes `html5.Widget.fromHTML()`.
- Feature: New `replace`-parameter for `html5.Widget.appendChild()` and `html5.Widget.prependChild()` which clears the content.
- Feature: `html5.ext.InputDialog` refactored & disables OK-Button when no value is present.
- Feature: `html5.utils.doesEventHitWidgetOrChildren()` and `html5.utils.doesEventHitWidgetOrParent()` now return the Widget or None instead of a boolean, to avoid creating loops and directly work with the recognized Widget.
- Feature: New function `html5.Widget.onBind()` enables widgets to react when bound to other widgets using the HTML parser.
- Feature: Replace HTML-parsing-related `vars`-parameter generally by `**kwargs`, with backward-compatibility.
- Speed-improvement: Hold static `_WidgetClassWrapper` per `html5.Widget` instead of creating one each time on the fly.

## [2.5.0] Vesuv

Release date: Jul 26, 2019

- Bugfix: `Widget.Th()` now supporting full col-/rowspan getting and setting.
- Bugfix: HTML-parser accepts tags in upper-/camel-case order now.
- Bugfix: HTML-parser handles table tags with tbody/thead tags inside more gracefully.
- Feature: Split HTML-parser into separate stages to compile and run; This allows to pre-compile HTML into a list/dict-structure and render it later on without parsing it again. `parseHTML()` is the new function, `fromHTML()` works like before and handles pre-compiled or raw HTML as parameter.
- Feature: `fromHTML()` extended to `vars` parameter to replace key-value pairs in text-nodes and attribute values expressed as `{{key}}`.
- Feature: HTML-parser dynamically reconizes void elements
- Feature: `html5.registerTag()` can be used to define new or override existing HTML elements in the HTML parser by custom implementations based on `html5.Widget()`
- Feature: New function `Widget.isVisible()` as counterpart for `Widget.isHidden()`.

## [2.4.0] Agung

Release date: May 17, 2019

- Bugfix: Fixed bug with disabling of input widgets.
- Feature: Fully refactored the librarys source base into just two single files, to reduce number of required files to download and make the library easier to access.
- Feature: New function `Widget.isHidden()` to check if a widget is currently shown.
- Feature: Improved handling of key-events.
- Feature: Allow to close popups by pressing `ESC`.
- Feature: Improvements for SVG and TextNode.

## [2.3.0] Kilauea

Release date: Oct 2, 2018

- Refactored `html5.ext.SelectDialog`
- Extended html parser to apply data-attributes
- Switching event handling to newer JavaScript event listener API
- Added `onFocusIn` and `onFocusOut` events

## [2.2.0] Etna

Release date: Apr 23, 2018

- Implemented `html5.Head()` to access the document's head object within the library.
- Directly append text in construction of Li().

## [2.1.0]

Release date: Nov 2, 2017

- Introduced a build-in HTML parser (`Widget.fromHTML()`) that is capable to compile HTML-code into DOM-objects of the html5 library, and an extra-feature to bind them to their root node for further access. This attempt makes it possible to create PyJS apps using the HTML5 library without creating every single element by hand.
- A more distinct way for `Widget.hide()` and `Widget.show()` that cannot be overridden by styling. (setting "hidden" does not work when another display value is set).
- Utility functions `Widget.enable() and `Widget.disable()`.
- Directly append text in construction of Div() and Span().
- Allow for tuple and list processing in table cell assignments.
- Adding `utils.parseFloat()` and `utils.parseInt()` utility functions.
- Implemented `colspan` attribute for Th()
- New README.md and CHANGELOG.md.

## 2.0

Release date: Dec 22, 2016

- v[2.0.1]: Directly append text in construction of Option().
- v[2.0.1]: Anything added to Widget.appendChild() or Widget.prependChild() which is not a widget is handled as text (TextNode() is automatically created).
- New functions `Widget.prependChild()`, `Widget.insertBefore()`, `Widget.children()`, `Widget.removeAllChildren()`,
`Widget.addClass()`, `Widget.removeClass()`, `Widget.toggleClass()`
- Utility functions `utils.doesEventHitWidgetOrParents()`, `utils.doesEventHitWidgetOrChildren()` taken from vi77
- Insert text blocks easier with `utils.textToHtml()`
- Several bugfixes

[develop]: https://github.com/viur-framework/html5/compare/v2.5.0...develop
[2.5.0]: https://github.com/viur-framework/html5/compare/v2.4.0...v2.5.0
[2.4.0]: https://github.com/viur-framework/html5/compare/v2.3.0...v2.4.0
[2.3.0]: https://github.com/viur-framework/html5/compare/v2.2.0...v2.3.0
[2.2.0]: https://github.com/viur-framework/html5/compare/v2.1.0...v2.2.0
[2.1.0]: https://github.com/viur-framework/html5/compare/v2.0.0...v2.1.0
[2.0.1]: https://github.com/viur-framework/html5/compare/v2.0.0...v2.0.1

+ 165
- 0
docs/ide/html5/LICENSE View File

@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.


This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

0. Additional Definitions.

As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

1. Exception to Section 3 of the GNU GPL.

You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

2. Conveying Modified Versions.

If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or

b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.

3. Object Code Incorporating Material from Library Header Files.

The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.

b) Accompany the object code with a copy of the GNU GPL and this license
document.

4. Combined Works.

You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.

b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.

c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.

d) Do one of the following:

0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.

1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.

e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)

5. Combined Libraries.

You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.

b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.

6. Revised Versions of the GNU Lesser General Public License.

The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

+ 69
- 0
docs/ide/html5/README.md View File

@@ -0,0 +1,69 @@
# ViUR html5

**html5** is a DOM-abstraction layer and API that is used to create client-side Web-Apps running in the browser and written in Python.

Look [here](https://www.viur.dev/blog/html5-library) for a short introduction.

## About

This API and framework is used to implement HTML5 web-apps using the Python programming language. The framework is an abstraction layer for a DOM running in [Pyodide](https://github.com/iodide-project/pyodide), a Python 3 interpreter compiled to web-assembly.

It provides

- class abstraction for all HTML5-DOM-elements, e.g. `html5.Div()`
- a built-in HTML parser and executor to generate DOM objects from HTML-code
- helpers for adding/removing classes, arrange children, handling events etc.

The most prominent software completely established on this library is [ViUR-vi](https://github.com/viur-framework/viur-vi/), the visual administration interface for ViUR-based applications.

[ViUR](https://www.viur.dev) is a free software development framework for the [Google App Engine](https://appengine.google.com).

## Quick Start

**Warning: This section is incomplete, a working example will follow soon!**

```python
import html5

class Game(html5.Div):
def __init__(self):
super().__init__(
"""
<label>
Your Name:
<input [name]="myInput" type="text" placeholder="Name">
</label>
<h1>Hello <span [name]="mySpan" class="name">Enter Name</span>!</h1>
""")
self.sinkEvent("onChange")

def onChange(self, event):
if html5.utils.doesEventHitWidgetOrChildren(event, self.myInput):
self.mySpan.appendChild(self.myInput["value"], replace=True)

Game()
```

## Contributing

We take a great interest in your opinion about ViUR. We appreciate your feedback and are looking forward to hear about your ideas. Share your visions or questions with us and participate in ongoing discussions.

- [ViUR website](https://www.viur.dev)
- [#ViUR on freenode IRC](https://webchat.freenode.net/?channels=viur)
- [ViUR on GitHub](https://github.com/viur-framework)
- [ViUR on Twitter](https://twitter.com/weloveViUR)

## Credits

ViUR is developed and maintained by [Mausbrand Informationssysteme GmbH](https://www.mausbrand.de/en), from Dortmund in Germany. We are a software company consisting of young, enthusiastic software developers, designers and social media experts, working on exciting projects for different kinds of customers. All of our newer projects are implemented with ViUR, from tiny web-pages to huge company intranets with hundreds of users.

Help of any kind to extend and improve or enhance this project in any kind or way is always appreciated.

## License

Copyright (C) 2012-2020 by Mausbrand Informationssysteme GmbH.

Mausbrand and ViUR are registered trademarks of Mausbrand Informationssysteme GmbH.

You may use, modify and distribute this software under the terms and conditions of the GNU Lesser General Public License (LGPL). See the file LICENSE provided within this package for more information.

+ 6
- 0
docs/ide/html5/__init__.py View File

@@ -0,0 +1,6 @@
#-*- coding: utf-8 -*-

from .core import *
from . import ext, utils, ignite



+ 3152
- 0
docs/ide/html5/core.py
File diff suppressed because it is too large
View File


+ 475
- 0
docs/ide/html5/ext.py View File

@@ -0,0 +1,475 @@
# -*- coding: utf-8 -*-
from . import core as html5
from . import utils

class Button(html5.Button):

def __init__(self, txt=None, callback=None, className=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self["class"] = "btn"

if className:
self.addClass(className)

self["type"] = "button"

if txt is not None:
self.setText(txt)

self.callback = callback
self.sinkEvent("onClick")

def setText(self, txt):
if txt is not None:
self.element.innerHTML = txt
self["title"] = txt
else:
self.element.innerHTML = ""
self["title"] = ""

def onClick(self, event):
event.stopPropagation()
event.preventDefault()
if self.callback is not None:
self.callback(self)


class Input(html5.Input):
def __init__(self, type="text", placeholder=None, callback=None, id=None, focusCallback=None, *args, **kwargs):
"""

:param type: Input type. Default: "text
:param placeholder: Placeholder text. Default: None
:param callback: Function to be called onChanged: callback(id, value)
:param id: Optional id of the input element. Will be passed to callback
:return:
"""
super().__init__(*args, **kwargs)
self["class"] = "input"
self["type"] = type
if placeholder is not None:
self["placeholder"] = placeholder

self.callback = callback
if id is not None:
self["id"] = id
self.sinkEvent("onChange")

self.focusCallback = focusCallback
if focusCallback:
self.sinkEvent("onFocus")

def onChange(self, event):
event.stopPropagation()
event.preventDefault()
if self.callback is not None:
self.callback(self, self["id"], self["value"])

def onFocus(self, event):
event.stopPropagation()
event.preventDefault()
if self.focusCallback is not None:
self.focusCallback(self, self["id"], self["value"])

def onDetach(self):
super().onDetach()
self.callback = None


class Popup(html5.Div):
def __init__(self, title=None, id=None, className=None, icon=None, enableShortcuts=True, closeable=True, *args, **kwargs):
super().__init__("""
<div class="box" [name]="popupBox">
<div class="box-head" [name]="popupHead">
<div class="item" [name]="popupHeadItem">
<div class="item-image">
<i class="i i--small" [name]="popupIcon"></i>
</div>
<div class="item-content">
<div class="item-headline" [name]="popupHeadline"></div>
</div>
</div>
</div>
<div class="box-body box--content" [name]="popupBody"></div>
<div class="box-foot box--content bar" [name]="popupFoot"></div>
</div>
""")

self.appendChild = self.popupBody.appendChild
self.fromHTML = lambda *args, **kwargs: self.popupBody.fromHTML(*args, **kwargs) if kwargs.get("bindTo") else self.popupBody.fromHTML(bindTo=self, *args, **kwargs)

self["class"] = "popup popup--center is-active"
if className:
self.addClass(className)

if closeable:
closeBtn = Button("&times;", self.close, className="item-action")
closeBtn.removeClass("btn")
self.popupHeadItem.appendChild(closeBtn)

if title:
self.popupHeadline.appendChild(title)

if icon:
self.popupIcon.appendChild(icon[0])
elif title:
self.popupIcon.appendChild(title[0])
else:
self.popupIcon.appendChild("Vi") #fixme!!! this _LIBRARY_ is not only used in the Vi...

# id can be used to pass information to callbacks
self.id = id

#FIXME: Implement a global overlay! One popupOverlay next to a list of popups.
self.popupOverlay = html5.Div()
self.popupOverlay["class"] = "popup-overlay is-active"

self.enableShortcuts = enableShortcuts
self.onDocumentKeyDownMethod = None

self.popupOverlay.appendChild(self)
html5.Body().appendChild(self.popupOverlay)

#FIXME: Close/Cancel every popup with click on popupCloseBtn without removing the global overlay.

def onAttach(self):
super(Popup, self).onAttach()

if self.enableShortcuts:
self.onDocumentKeyDownMethod = self.onDocumentKeyDown # safe reference to method
html5.document.addEventListener("keydown", self.onDocumentKeyDownMethod)

def onDetach(self):
super(Popup, self).onDetach()

if self.enableShortcuts:
html5.document.removeEventListener("keydown", self.onDocumentKeyDownMethod)

def onDocumentKeyDown(self, event):
if html5.isEscape(event):
self.close()

def close(self, *args, **kwargs):
html5.Body().removeChild(self.popupOverlay)
self.popupOverlay = None



class InputDialog(Popup):
def __init__(self, text, value="", successHandler=None, abortHandler=None,
successLbl="OK", abortLbl="Cancel", placeholder="", *args, **kwargs):

super().__init__(*args, **kwargs)
self.addClass("popup--inputdialog")

self.sinkEvent("onKeyDown", "onKeyUp")

self.successHandler = successHandler
self.abortHandler = abortHandler

self.fromHTML(
"""
<div class="input-group">
<label class="label">
{{text}}
</label>
<input class="input" [name]="inputElem" value="{{value}}" placeholder="{{placeholder}}" />
</div>
""",
vars={
"text": text,
"value": value,
"placeholder": placeholder
}
)

# Cancel
self.popupFoot.appendChild(Button(abortLbl, self.onCancel, className="btn--cancel btn--danger"))

# Okay
self.okayBtn = Button(successLbl, self.onOkay, className="btn--okay btn--primary")
if not value:
self.okayBtn.disable()

self.popupFoot.appendChild(self.okayBtn)

self.inputElem.focus()

def onKeyDown(self, event):
if html5.isReturn(event) and self.inputElem["value"]:
event.stopPropagation()
event.preventDefault()
self.onOkay()

def onKeyUp(self, event):
if self.inputElem["value"]:
self.okayBtn.enable()
else:
self.okayBtn.disable()

def onDocumentKeyDown(self, event):
if html5.isEscape(event):
event.stopPropagation()
event.preventDefault()
self.onCancel()

def onOkay(self, *args, **kwargs):
if self.successHandler:
self.successHandler(self, self.inputElem["value"])
self.close()

def onCancel(self, *args, **kwargs):
if self.abortHandler:
self.abortHandler(self, self.inputElem["value"])
self.close()


class Alert(Popup):
"""
Just displaying an alerting message box with OK-button.
"""

def __init__(self, msg, title=None, className=None, okCallback=None, okLabel="OK", icon="!", closeable=True, *args, **kwargs):
super().__init__(title, className=None, icon=icon, closeable=closeable, *args, **kwargs)
self.addClass("popup--alert")

if className:
self.addClass(className)

self.okCallback = okCallback

message = html5.Span()
message.addClass("alert-msg")
self.popupBody.appendChild(message)

if isinstance(msg, str):
msg = msg.replace("\n", "<br>")

message.appendChild(msg, bindTo=False)

self.sinkEvent("onKeyDown")

if closeable:
okBtn = Button(okLabel, callback=self.onOkBtnClick)
okBtn.addClass("btn--okay btn--primary")
self.popupFoot.appendChild(okBtn)

okBtn.focus()

def drop(self):
self.okCallback = None
self.close()

def onOkBtnClick(self, sender=None):
if self.okCallback:
self.okCallback(self)

self.drop()

def onKeyDown(self, event):
if html5.isReturn(event):
event.stopPropagation()
event.preventDefault()
self.onOkBtnClick()


class YesNoDialog(Popup):
def __init__(self, question, title=None, yesCallback=None, noCallback=None,
yesLabel="Yes", noLabel="No", icon="?",
closeable=False, *args, **kwargs):
super().__init__(title, closeable=closeable, icon=icon, *args, **kwargs)
self.addClass("popup--yesnodialog")

self.yesCallback = yesCallback
self.noCallback = noCallback

lbl = html5.Span()
lbl["class"].append("question")
self.popupBody.appendChild(lbl)

if isinstance(question, html5.Widget):
lbl.appendChild(question)
else:
utils.textToHtml(lbl, question)

if len(noLabel):
btnNo = Button(noLabel, className="btn--no", callback=self.onNoClicked)
#btnNo["class"].append("btn--no")
self.popupFoot.appendChild(btnNo)

btnYes = Button(yesLabel, callback=self.onYesClicked)
btnYes["class"].append("btn--yes")
self.popupFoot.appendChild(btnYes)

self.sinkEvent("onKeyDown")
btnYes.focus()

def onKeyDown(self, event):
if html5.isReturn(event):
event.stopPropagation()
event.preventDefault()
self.onYesClicked()

def onDocumentKeyDown(self, event):
if html5.isEscape(event):
event.stopPropagation()
event.preventDefault()
self.onNoClicked()

def drop(self):
self.yesCallback = None
self.noCallback = None
self.close()

def onYesClicked(self, *args, **kwargs):
if self.yesCallback:
self.yesCallback(self)

self.drop()

def onNoClicked(self, *args, **kwargs):
if self.noCallback:
self.noCallback(self)

self.drop()


class SelectDialog(Popup):

def __init__(self, prompt, items=None, title=None, okBtn="OK", cancelBtn="Cancel", forceSelect=False,
callback=None, *args, **kwargs):
super().__init__(title, *args, **kwargs)
self["class"].append("popup--selectdialog")

self.callback = callback
self.items = items
assert isinstance(self.items, list)

# Prompt
if prompt:
lbl = html5.Span()
lbl["class"].append("prompt")

if isinstance(prompt, html5.Widget):
lbl.appendChild(prompt)
else:
utils.textToHtml(lbl, prompt)

self.popupBody.appendChild(lbl)

# Items
if not forceSelect and len(items) <= 3:
for idx, item in enumerate(items):
if isinstance(item, dict):
title = item.get("title")
cssc = item.get("class")
elif isinstance(item, tuple):
title = item[1]
cssc = None
else:
title = item

btn = Button(title, callback=self.onAnyBtnClick)
btn.idx = idx

if cssc:
btn.addClass(cssc)

self.popupBody.appendChild(btn)
else:
self.select = html5.Select()
self.popupBody.appendChild(self.select)

for idx, item in enumerate(items):
if isinstance(item, dict):
title = item.get("title")
elif isinstance(item, tuple):
title = item[1]
else:
title = item

opt = html5.Option(title)
opt["value"] = str(idx)

self.select.appendChild(opt)

if okBtn:
self.popupFoot.appendChild(Button(okBtn, callback=self.onOkClick))

if cancelBtn:
self.popupFoot.appendChild(Button(cancelBtn, callback=self.onCancelClick))

def onAnyBtnClick(self, sender):
item = self.items[sender.idx]

if isinstance(item, dict) and item.get("callback") and callable(item["callback"]):
item["callback"](item)

if self.callback:
self.callback(item)

self.items = None
self.close()

def onCancelClick(self, sender=None):
self.close()

def onOkClick(self, sender=None):
assert self.select["selectedIndex"] >= 0
item = self.items[int(self.select.children(self.select["selectedIndex"])["value"])]

if isinstance(item, dict) and item.get("callback") and callable(item["callback"]):
item["callback"](item)

if self.callback:
self.callback(item)

self.items = None
self.select = None
self.close()


class TextareaDialog(Popup):
def __init__(self, text, value="", successHandler=None, abortHandler=None, successLbl="OK", abortLbl="Cancel",
*args, **kwargs):
super().__init__(*args, **kwargs)
self["class"].append("popup--textareadialog")

self.successHandler = successHandler
self.abortHandler = abortHandler

span = html5.Span()
span.element.innerHTML = text
self.popupBody.appendChild(span)

self.inputElem = html5.Textarea()
self.inputElem["value"] = value
self.popupBody.appendChild(self.inputElem)

okayBtn = Button(successLbl, self.onOkay)
okayBtn["class"].append("btn--okay")
self.popupFoot.appendChild(okayBtn)

cancelBtn = Button(abortLbl, self.onCancel)
cancelBtn["class"].append("btn--cancel")
self.popupFoot.appendChild(cancelBtn)

self.sinkEvent("onKeyDown")

self.inputElem.focus()

def onDocumentKeyDown(self, event):
if html5.isEscape(event):
event.stopPropagation()
event.preventDefault()
self.onCancel()

def onOkay(self, *args, **kwargs):
if self.successHandler:
self.successHandler(self, self.inputElem["value"])
self.close()

def onCancel(self, *args, **kwargs):
if self.abortHandler:
self.abortHandler(self, self.inputElem["value"])
self.close()

+ 186
- 0
docs/ide/html5/ignite.py View File

@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
from . import core as html5


@html5.tag
class Label(html5.Label):
_parserTagName = "ignite-label"

def __init__(self, *args, **kwargs):
super(Label, self).__init__(style="label ignt-label", *args, **kwargs)


@html5.tag
class Input(html5.Input):
_parserTagName = "ignite-input"

def __init__(self, *args, **kwargs):
super(Input, self).__init__(style="input ignt-input", *args, **kwargs)


@html5.tag
class Switch(html5.Div):
_parserTagName = "ignite-switch"

def __init__(self, *args, **kwargs):
super(Switch, self).__init__(style="switch ignt-switch", *args, **kwargs)

self.input = html5.Input(style="switch-input")
self.appendChild(self.input)
self.input["type"] = "checkbox"

switchLabel = html5.Label(forElem=self.input)
switchLabel.addClass("switch-label")
self.appendChild(switchLabel)

def _setChecked(self, value):
self.input["checked"] = bool(value)

def _getChecked(self):
return self.input["checked"]


@html5.tag
class Check(html5.Input):
_parserTagName = "ignite-check"

def __init__(self, *args, **kwargs):
super(Check, self).__init__(style="check ignt-check", *args, **kwargs)

checkInput = html5.Input()
checkInput.addClass("check-input")
checkInput["type"] = "checkbox"
self.appendChild(checkInput)

checkLabel = html5.Label(forElem=checkInput)
checkLabel.addClass("check-label")
self.appendChild(checkLabel)


@html5.tag
class Radio(html5.Div):
_parserTagName = "ignite-radio"

def __init__(self, *args, **kwargs):
super(Radio, self).__init__(style="radio ignt-radio", *args, **kwargs)

radioInput = html5.Input()
radioInput.addClass("radio-input")
radioInput["type"] = "radio"
self.appendChild(radioInput)

radioLabel = html5.Label(forElem=radioInput)
radioLabel.addClass("radio-label")
self.appendChild(radioLabel)


@html5.tag
class Select(html5.Select):
_parserTagName = "ignite-select"

def __init__(self, *args, **kwargs):
super(Select, self).__init__(style="select ignt-select", *args, **kwargs)

defaultOpt = html5.Option()
defaultOpt["selected"] = True
defaultOpt["disabled"] = True
defaultOpt.element.innerHTML = ""
self.appendChild(defaultOpt)


@html5.tag
class Textarea(html5.Textarea):
_parserTagName = "ignite-textarea"

def __init__(self, *args, **kwargs):
super(Textarea, self).__init__(style="textarea ignt-textarea", *args, **kwargs)


@html5.tag
class Progress(html5.Progress):
_parserTagName = "ignite-progress"

def __init__(self, *args, **kwargs):
super(Progress, self).__init__(style="progress ignt-progress", *args, **kwargs)


@html5.tag
class Item(html5.Div):
_parserTagName = "ignite-item"

def __init__(self, title=None, descr=None, className=None, *args, **kwargs):
super(Item, self).__init__(style="item ignt-item", *args, **kwargs)
if className:
self.addClass(className)

self.fromHTML("""
<div class="item-image ignt-item-image" [name]="itemImage">
</div>
<div class="item-content ignt-item-content" [name]="itemContent">
<div class="item-headline ignt-item-headline" [name]="itemHeadline">
</div>
</div>
""")

if title:
self.itemHeadline.appendChild(html5.TextNode(title))

if descr:
self.itemSubline = html5.Div()
self.addClass("item-subline ignt-item-subline")
self.itemSubline.appendChild(html5.TextNode(descr))
self.appendChild(self.itemSubline)


@html5.tag
class Table(html5.Table):
_parserTagName = "ignite-table"

def __init__(self, *args, **kwargs):
super(Table, self).__init__(*args, **kwargs)
self.head.addClass("ignt-table-head")
self.body.addClass("ignt-table-body")

def prepareRow(self, row):
assert row >= 0, "Cannot create rows with negative index"

for child in self.body._children:
row -= child["rowspan"]
if row < 0:
return

while row >= 0:
tableRow = html5.Tr()
tableRow.addClass("ignt-table-body-row")
self.body.appendChild(tableRow)
row -= 1

def prepareCol(self, row, col):
assert col >= 0, "Cannot create cols with negative index"
self.prepareRow(row)

for rowChild in self.body._children:
row -= rowChild["rowspan"]

if row < 0:
for colChild in rowChild._children:
col -= colChild["colspan"]
if col < 0:
return

while col >= 0:
tableCell = html5.Td()
tableCell.addClass("ignt-table-body-cell")
rowChild.appendChild(tableCell)
col -= 1

return
def fastGrid( self, rows, cols, createHidden=False ):
colsstr = "".join(['<td class="ignt-table-body-cell"></td>' for i in range(0, cols)])
tblstr = '<tbody [name]="body" class="ignt-table-body" >'

for r in range(0, rows):
tblstr += '<tr class="ignt-table-body-row %s">%s</tr>' %("is-hidden" if createHidden else "",colsstr)
tblstr +="</tbody>"

self.fromHTML(tblstr)

+ 101
- 0
docs/ide/html5/utils.py View File

@@ -0,0 +1,101 @@
# -*- coding: utf-8 -*-
from . import core as html5

def unescape(val, maxLength = 0):
"""
Unquotes several HTML-quoted characters in a string.

:param val: The value to be unescaped.
:type val: str

:param maxLength: Cut-off after maxLength characters.
A value of 0 means "unlimited". (default)
:type maxLength: int

:returns: The unquoted string.
:rtype: str
"""
val = val \
.replace("&lt;", "<") \
.replace("&gt;", ">") \
.replace("&quot;", "\"") \
.replace("&#39;", "'")

if maxLength > 0:
return val[0:maxLength]

return val

def doesEventHitWidgetOrParents(event, widget):
"""
Test if event 'event' hits widget 'widget' (or *any* of its parents)
"""
while widget:
if event.target == widget.element:
return widget

widget = widget.parent()

return None

def doesEventHitWidgetOrChildren(event, widget):
"""
Test if event 'event' hits widget 'widget' (or *any* of its children)
"""
if event.target == widget.element:
return widget

for child in widget.children():
if doesEventHitWidgetOrChildren(event, child):
return child

return None

def textToHtml(node, text):
"""
Generates html nodes from text by splitting text into content and into
line breaks html5.Br.

:param node: The node where the nodes are appended to.
:param text: The text to be inserted.
"""

for (i, part) in enumerate(text.split("\n")):
if i > 0:
node.appendChild(html5.Br())

node.appendChild(html5.TextNode(part))

def parseInt(s, ret = 0):
"""
Parses a value as int
"""
if not isinstance(s, str):
return int(s)
elif s:
if s[0] in "+-":
ts = s[1:]
else:
ts = s

if ts and all([_ in "0123456789" for _ in ts]):
return int(s)

return ret

def parseFloat(s, ret = 0.0):
"""
Parses a value as float.
"""
if not isinstance(s, str):
return float(s)
elif s:
if s[0] in "+-":
ts = s[1:]
else:
ts = s

if ts and ts.count(".") <= 1 and all([_ in ".0123456789" for _ in ts]):
return float(s)

return ret

+ 101
- 0
docs/ide/index.html View File

@@ -0,0 +1,101 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">

<!-- flip comment below to use local pyodide -->
<script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script>
<!-- <script src="./pyodide/pyodide.js"></script> -->

<link rel="stylesheet" href="https://unpkg.com/purecss@1.0.1/build/base-min.css">
<link href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@500&display=swap" rel="stylesheet">

<script src="app.js"></script>
<style>
.is-loading:after {
background-image: url(is-loading.gif);
background-position: center 35%;
background-repeat: no-repeat;
background-color: hsla(0, 0%, 100%, .6);
position: absolute;
z-index: 700;
content: " ";
width: 100%;
height: 100%;
display: block;
left: 0;
right: 0;
top: 0;
bottom: 0
}

h1 {
text-align: center;
}

textarea, select, body > div > ul {
/* display: block;
margin: 15px auto;
width: 90%;
font-weight: bold;
color: #052569; */
font-family: 'Inconsolata', monospace;
}

textarea {
margin: 10px;
width: 90%;
padding: 10px;
font-size: 1.4em;
}

#grammar {
min-height: 300px;
}
#input {
min-height: 100px;
}

ul ul {
border-left: 1px dotted silver;
margin-left: -16px;
}

li {
list-style: circle;
margin-left: 10px;
}

select {
padding: 5px;
}

#inputs {
text-align: center;
}

#result {
display: flex;
justify-content: center;
}

#result > ul {
margin: 10px;
width: 90%;
padding: 10px;
font-size: 1.2em;
}

menu {
display: flex;
}

main {
margin: auto;
}

</style>
</head>
<body class="is-loading">
</body>
</html>

BIN
docs/ide/is-loading.gif View File

Before After
Width: 43  |  Height: 11  |  Size: 404 B

BIN
docs/ide/lark-logo.png View File

Before After
Width: 198  |  Height: 98  |  Size: 13 KiB

Loading…
Cancel
Save