simplydoc 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,85 @@
1
+ name: Create Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+
8
+ env:
9
+ RELEASE_NAME: ${{ gitea.ref_name }}
10
+ VERSION: ${{ gitea.ref_name }}
11
+ SRC_FOLDER: src/simplydoc
12
+ PYTHON_COMMAND: python3
13
+
14
+ jobs:
15
+
16
+ Release:
17
+
18
+ runs-on: node20
19
+
20
+ steps:
21
+
22
+ # Versions
23
+
24
+ - name: Ldd Version
25
+ run: ldd --version
26
+
27
+ - name: Node Version
28
+ run: node --version
29
+
30
+ - name: Python Version
31
+ run: ${{ env.PYTHON_COMMAND }} --version
32
+
33
+ - name: Echo `env.VERSION`
34
+ run: |
35
+ echo "VERSION: ${{ env.VERSION }}"
36
+
37
+ # Checkout
38
+
39
+ - name: Check out
40
+ uses: actions/checkout@v4
41
+
42
+ # Check versions
43
+
44
+ - name: Checks versions
45
+ run: |
46
+ PKG_VERSION=$(${{ env.PYTHON_COMMAND }} -c "
47
+ import tomllib
48
+ with open('pyproject.toml', 'rb') as f:
49
+ print(tomllib.load(f)['project']['version'])
50
+ ")
51
+ GIT_VERSION=${GITHUB_REF_NAME#v}
52
+ echo "Package: $PKG_VERSION | Tag: $GIT_VERSION"
53
+ [ "$PKG_VERSION" = "$GIT_VERSION" ] || { echo "❌ Mismatch $PKG_VERSION <> $GIT_VERSION!"; exit 1; }
54
+
55
+ # Install pip zip
56
+
57
+ - name: Install pip zip
58
+ run: |
59
+ apt update && apt install -y python3-pip zip
60
+
61
+
62
+ # ###############
63
+ # Package - Build
64
+
65
+ # Package - Prerequisites
66
+
67
+ - name: Package - Prerequisites
68
+ run: |
69
+ pip install python-minifier --break-system-packages
70
+
71
+ - name: Package - Minify
72
+ run: |
73
+ pyminify --in-place --remove-literal-statements ${{ env.SRC_FOLDER }}
74
+
75
+ - name: Package - Build
76
+ run: |
77
+ pip install build twine --break-system-packages
78
+ ${{ env.PYTHON_COMMAND }} -m build
79
+
80
+ - name: Package - Publish to PyPI
81
+ env:
82
+ TWINE_USERNAME: __token__
83
+ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
84
+ run: twine upload dist/*
85
+
@@ -0,0 +1,166 @@
1
+ # ---> Python
2
+ # Byte-compiled / optimized / DLL files
3
+ __pycache__/
4
+ *.py[cod]
5
+ *$py.class
6
+
7
+ # C extensions
8
+ *.so
9
+
10
+ # Distribution / packaging
11
+ .Python
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ #Pipfile.lock
97
+
98
+ # poetry
99
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103
+ #poetry.lock
104
+
105
+ # pdm
106
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107
+ #pdm.lock
108
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109
+ # in version control.
110
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
111
+ .pdm.toml
112
+ .pdm-python
113
+ .pdm-build/
114
+
115
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
+ __pypackages__/
117
+
118
+ # Celery stuff
119
+ celerybeat-schedule
120
+ celerybeat.pid
121
+
122
+ # SageMath parsed files
123
+ *.sage.py
124
+
125
+ # Environments
126
+ .env
127
+ .venv
128
+ env/
129
+ venv/
130
+ ENV/
131
+ env.bak/
132
+ venv.bak/
133
+
134
+ # Spyder project settings
135
+ .spyderproject
136
+ .spyproject
137
+
138
+ # Rope project settings
139
+ .ropeproject
140
+
141
+ # mkdocs documentation
142
+ /site
143
+
144
+ # mypy
145
+ .mypy_cache/
146
+ .dmypy.json
147
+ dmypy.json
148
+
149
+ # Pyre type checker
150
+ .pyre/
151
+
152
+ # pytype static type analyzer
153
+ .pytype/
154
+
155
+ # Cython debug symbols
156
+ cython_debug/
157
+
158
+ # PyCharm
159
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
162
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163
+ #.idea/
164
+
165
+
166
+ tests/tmp
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.5
2
+ Name: simplydoc
3
+ Version: 0.1.0
4
+ Summary: Beautiful, portable documents from Python
5
+ Author-email: PinkSalmon <dev@pinksalmon.cloud>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.11
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ Classifier: Programming Language :: Python :: 3.13
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: pydantic
12
+ Provides-Extra: dev
13
+ Requires-Dist: mypy>=1.0; extra == 'dev'
14
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
15
+ Requires-Dist: pytest>=7.0; extra == 'dev'
16
+ Requires-Dist: ruff>=0.4; extra == 'dev'
17
+ Provides-Extra: docs
18
+ Requires-Dist: mkdocstrings-python; extra == 'docs'
19
+ Requires-Dist: zensical; extra == 'docs'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # SimplyDoc
23
+
24
+ Beautiful, portable documents from Python.
25
+
26
+
27
+ ```python
28
+ from simplydoc import Doc
29
+
30
+ doc = Doc(
31
+ data={
32
+ "content_1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
33
+ "content_2": "Sed non risus.",
34
+ },
35
+ layout={
36
+ "title": "This is a title",
37
+ "sections": [
38
+ {
39
+ "title": "Part 1",
40
+ "blocks": [
41
+ {"data": "content_1"},
42
+ {"data": "content_2"},
43
+ ]
44
+ }
45
+ ],
46
+ },
47
+ )
48
+
49
+ doc.to_html("report.html")
50
+
51
+ ```
@@ -0,0 +1,27 @@
1
+ # SimplyDoc
2
+
3
+ By PinkSalmon
4
+
5
+ ## Development
6
+
7
+ ### Comments Style Convention
8
+
9
+ TODEFINE
10
+
11
+
12
+ ### Install
13
+
14
+ - Clone this repo
15
+ - Install dev dependencies
16
+
17
+ ```bash
18
+ cd simplydoc
19
+ pip install -e ".[dev]"
20
+ ```
21
+
22
+ ### Tests
23
+
24
+ ```bash
25
+ pytest
26
+ ```
27
+
@@ -0,0 +1,30 @@
1
+ # SimplyDoc
2
+
3
+ Beautiful, portable documents from Python.
4
+
5
+
6
+ ```python
7
+ from simplydoc import Doc
8
+
9
+ doc = Doc(
10
+ data={
11
+ "content_1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
12
+ "content_2": "Sed non risus.",
13
+ },
14
+ layout={
15
+ "title": "This is a title",
16
+ "sections": [
17
+ {
18
+ "title": "Part 1",
19
+ "blocks": [
20
+ {"data": "content_1"},
21
+ {"data": "content_2"},
22
+ ]
23
+ }
24
+ ],
25
+ },
26
+ )
27
+
28
+ doc.to_html("report.html")
29
+
30
+ ```
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "simplydoc"
7
+ version = "0.1.0"
8
+ description = "Beautiful, portable documents from Python"
9
+ readme = "README.md"
10
+ authors = [{ name = "PinkSalmon", email = "dev@pinksalmon.cloud" }]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ ]
17
+ requires-python = ">=3.11"
18
+ dependencies = [
19
+ "pydantic",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ dev = [
24
+ "pytest>=7.0",
25
+ "pytest-cov>=4.0",
26
+ "ruff>=0.4",
27
+ "mypy>=1.0",
28
+ ]
29
+ docs = [
30
+ "zensical",
31
+ "mkdocstrings-python",
32
+ ]
33
+
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/simplydoc"]
37
+
38
+ # --- Ruff (linter + formatter) ---
39
+ [tool.ruff]
40
+ src = ["src"]
41
+ line-length = 120
42
+ # target-version = "py39"
43
+
44
+ [tool.ruff.lint]
45
+ select = ["E", "F", "I", "UP", "B", "SIM"]
46
+ ignore = []
47
+
48
+ [tool.ruff.lint.isort]
49
+ known-first-party = ["simplydoc"]
50
+
51
+ # --- Mypy (type checker) ---
52
+ [tool.mypy]
53
+ python_version = "3.12"
54
+ strict = true
55
+ files = ["src/simplydoc"]
56
+
57
+ # --- Pytest ---
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["tests"]
60
+ addopts = "--cov=simplydoc --cov-report=term-missing"
61
+
62
+ [tool.coverage.run]
63
+ source = ["src/simplydoc"]
64
+
65
+ [tool.coverage.report]
66
+ exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:"]
@@ -0,0 +1,2 @@
1
+ from.doc import Doc,DocLayout
2
+ __all__=['Doc','DocLayout']
@@ -0,0 +1,115 @@
1
+ * {
2
+ box-sizing: border-box;
3
+ }
4
+ :root {
5
+ font: 15px/1.5 system-ui,sans-serif;
6
+ color-scheme: light;
7
+ --text: #172b41;
8
+ --page: #f2f5f8;
9
+ --surface: #ffffff;
10
+ --border: #d9e2eb;
11
+ --row-border: #e4eaf0;
12
+ --row-stripe: #f4f7fa;
13
+ --row-hover: #e5eef8;
14
+ color: var(--text);
15
+ background: var(--page);
16
+ }
17
+ :root[data-theme="dark"] {
18
+ color-scheme: dark;
19
+ --text: #e4edf7;
20
+ --page: #101720;
21
+ --surface: #1b2532;
22
+ --border: #3b4c60;
23
+ --row-border: #334357;
24
+ --row-stripe: #222f3f;
25
+ --row-hover: #2d4056;
26
+ }
27
+ table {
28
+ border: 0;
29
+ border-collapse: collapse;
30
+ /* width: 100%; */
31
+ font-size: 0.9em;
32
+ color: var(--text);
33
+ background-color: var(--surface);
34
+ }
35
+ th, td {
36
+ border: 0;
37
+ padding: 2px 6px;
38
+ text-align: left;
39
+ border-bottom: 1px solid var(--row-border);
40
+ text-wrap: nowrap;
41
+
42
+ }
43
+ /* stripped */
44
+ tbody tr:nth-child(even) {
45
+ background-color: var(--row-stripe);
46
+ }
47
+ tbody tr:hover {
48
+ background-color: var(--row-hover);
49
+ }
50
+
51
+ h1 {
52
+ font-size: 32px;
53
+ letter-spacing: -.04em;
54
+ }
55
+ h2 {
56
+ margin: 0;
57
+ }
58
+ summary h2 , summary h3 , summary h4 { display: inline; margin: 0; }
59
+ main {
60
+ max-width: 1240px;
61
+ margin: auto;
62
+ padding: 36px 24px;
63
+ }
64
+ section {
65
+ background: var(--surface);
66
+ border: 1px solid var(--border);
67
+ border-radius: 12px;
68
+ padding: 22px;
69
+ margin: 18px 0;
70
+ }
71
+ header { display: flex; align-items: center; gap: 16px; }
72
+ header svg, header img { display: block; height: 40px; width: auto; flex-shrink: 0; }
73
+ header h1 { margin: 0; }
74
+
75
+ .theme-control { display: flex; align-items: center; gap: 10px; margin-top: 10px; font-size: 14px; }
76
+
77
+ .switch { position: relative; width: 26px; height: 16px; padding: 0; border: 1px solid var(--border); border-radius: 20px; background: #64748b; cursor: pointer; flex-shrink: 0; }
78
+ .switch::after { content: ""; position: absolute; top: 3px; left: 3px; width: 8px; height: 8px; border-radius: 50%; background: #fff; transition: transform .18s; }
79
+ .switch[aria-checked="true"] { background: #b64431; }
80
+ .switch[aria-checked="true"]::after { transform: translateX(10px); }
81
+ /* .switch:focus-visible { outline: 3px solid #ec624a; outline-offset: 4px; } */
82
+
83
+ @media (prefers-reduced-motion: reduce) { .switch::after { transition: none; } }
84
+
85
+ .button-link {
86
+ appearance: none;
87
+ border: 0;
88
+ padding: 0;
89
+ background: none;
90
+ color: #075fbd;
91
+ font: inherit;
92
+ text-decoration: underline;
93
+ text-underline-offset: 2px;
94
+ cursor: pointer;
95
+ }
96
+
97
+ :root[data-theme="dark"] .button-link {
98
+ color: #8bc4ff;
99
+ }
100
+
101
+ .button-link:hover {
102
+ text-decoration-thickness: 2px;
103
+ }
104
+
105
+ .button-link:focus-visible {
106
+ outline: 2px solid currentColor;
107
+ outline-offset: 3px;
108
+ border-radius: 2px;
109
+ }
110
+
111
+ .button-link:disabled {
112
+ opacity: 0.5;
113
+ cursor: default;
114
+ text-decoration: none;
115
+ }
@@ -0,0 +1,59 @@
1
+ _C='utf-8'
2
+ _B=False
3
+ _A=None
4
+ from pathlib import Path
5
+ from typing import Any
6
+ import json,re
7
+ try:import pandas as pd
8
+ except ModuleNotFoundError:pd=_A
9
+ from.models.doc_layout import DocLayout
10
+ from.utils import file_to_img_src_base64
11
+ ASSETS=Path(__file__).parent
12
+ DEFAULT_IMG_SRC='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9Ijk1IDE1MCA0NTQuMjUgMzQ0LjI1Ij4KICA8ZyBmaWxsPSIjZWM2MjRhIiA+CiAgICA8cGF0aCBkPSJNMTkzLjAxLDMzNy41OGMyLjU2LTMuNzEsMy4wNi04LjQyLDEuMzItMTIuNTktMS43NC00LjE3LTUuNDMtNy4xMy05Ljg4LTcuOTJsLTc5LjIyLTE0LjA1Yy0uMTQtLjAzLS4yOC0uMDEtLjQyLS4wMy0uMjctLjAzLS41My0uMDYtLjc5LS4wNi0uMjUsMC0uNDksMC0uNzMuMDMtLjI1LjAyLS41LjA1LS43NS4wOS0uMjUuMDUtLjQ4LjEtLjcyLjE3LS4yMy4wNy0uNDYuMTQtLjY5LjIzLS4yMy4wOS0uNDUuMTktLjY3LjMtLjIyLjExLS40My4yMy0uNjQuMzYtLjIuMTMtLjQuMjctLjU5LjQyLS4yLjE1LS4zOS4zMS0uNTcuNDktLjE3LjE2LS4zMy4zMy0uNDkuNTEtLjE3LjE5LS4zMy4zOS0uNDcuNTktLjE0LjItLjI3LjQxLS40LjYyLS4xMi4yMi0uMjQuNDMtLjM0LjY2LS4xMS4yNC0uMi40OS0uMjguNzQtLjA1LjE0LS4xMi4yNi0uMTUuNC0uMDMuMTEtLjAzLjIyLS4wN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LC4yNi4wOS4zOS4xMy4yMi4wNC4zOS4xMy42LjE3LjE3LjA5LjM0LjE3LjUyLjI2LjE3LjEzLjM0LjIyLjUyLjM0LjE3LjA5LjMuMjEuNDMuMzQuMTcuMTMuMy4yNi40Ny4zOS4xMy4xMy4yMi4yNi4zNC40My4xMy4xMy4yNi4zLjM5LjQ3LjA5LjEzLjE3LjMuMjYuNDcuMDkuMTcuMTcuMzQuMjYuNTYuMDkuMTcuMTMuMzQuMTcuNTIuMDkuMTcuMTMuMzkuMTcuNTYuMDQuMjIuMDQuMzkuMDkuNTYsMCwuMjEuMDQuNDMuMDQuNjVaIi8+CiAgICA8cGF0aCBkPSJNNDc4Ljg1LDQ3Mi40MUgxODkuMjdjLTQuMTQsMC03LjUxLDMuMzctNy41MSw3LjUxczMuMzcsNy41MSw3LjUxLDcuNTFoMjg5LjU4YzQuMTQsMCw3LjUxLTMuMzcsNy41MS03LjUxcy0zLjM3LTcuNTEtNy41MS03LjUxWiIvPgogIDwvZz4KPC9zdmc+'
13
+ IS_MINIFY=_B
14
+ class Doc:
15
+ def __init__(A,data,layout,encoding=_C,lang=_A):B=layout;A.data=data;A.layout=B if isinstance(B,DocLayout)else DocLayout(**B);A.encoding=encoding;A.lang=lang
16
+ def to_json(B,path,indent=_A):A=path;A=Path(A);B._save(A,B._get_json(indent=indent))
17
+ def to_html(B,path,is_static=_B):
18
+ A=path;A=Path(A)
19
+ if is_static:B._create_static_html(A)
20
+ else:B._create_html(A)
21
+ def _create_html(B,path):E=B.layout;C=IS_MINIFY;A=''if C else'\n';D=_A if C else 4;B._save(path,f'<!DOCTYPE html>{A}<html lang="fr">{A}'+f"<head>{A}"+f"<title>{E.title}</title>"+f"<style>{B._get_css(C)}</style>{A}"+f"<script>{B._get_head_js(C)}</script>{A}"+f'<script src="https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js"></script>'+f"</head>{A}"+f'<body>{A}<main id="main">{A}'+B._html_main(A)+f"</main>{A}"+f'<script id="report-data" type="application/json">{B._get_json(indent=D)}</script>{A}'+f'<script id="report-layout" type="application/json">{B._dynamic_html_layout(indent=D)}</script>{A}'+f"<script>{B._get_js(C)}</script>{A}"+f"</body>{A}</html>{A}")
22
+ def _create_static_html(B,path):D=B.layout;C=IS_MINIFY;A=''if C else'\n';B._save(path,f'<!DOCTYPE html>{A}<html lang="fr">{A}'+f"<head>{A}"+f"<title>{D.title}</title>"+f"<style>{B._get_css(C)}</style>{A}"+f"<script>{B._get_head_js(C)}</script>{A}"+f"</head>{A}"+f'<body>{A}<main id="main">{A}'+B._html_main(A,is_static=True)+'</main></body></html>')
23
+ def _save(A,path,s):Path(path).write_text(s,encoding=A.encoding)
24
+ def _get_json(D,indent):
25
+ A={}
26
+ for(C,B)in D.data.items():
27
+ if isinstance(B,pd.DataFrame):A[C]=json.loads(B.to_json(orient='split',force_ascii=_B,date_format='iso',indent=_A))
28
+ else:A[C]=B
29
+ return json.dumps(A,indent=indent)
30
+ def _simple_css_minify(B,css):A=css;A=re.sub('/\\*.*?\\*/','',A,flags=re.DOTALL);A=re.sub('\\s+',' ',A);A=re.sub('\\s*([{}:;,])\\s*','\\1',A);return A.strip()
31
+ def _simple_js_minify(B,js):A='("(?:\\\\[\\s\\S]|[^"\\\\])*"|\'(?:\\\\[\\s\\S]|[^\'\\\\])*\'|`(?:\\\\[\\s\\S]|[^`\\\\])*`)|//[^\\r\\n]*|/\\*[\\s\\S]*?\\*/|[\\r\\n]+';return re.sub(A,lambda m:m.group(1)if m.group(1)is not _A else' ',js).strip()
32
+ def _get_css(B,is_minify):A=(ASSETS/'doc.css').read_text(encoding=_C);return B._simple_css_minify(A)if is_minify else A
33
+ def _get_head_js(B,is_minify):A=(ASSETS/'doc_head.js').read_text(encoding=_C);return B._simple_js_minify(A)if is_minify else A
34
+ def _get_js(B,is_minify):A=(ASSETS/'doc_body.js').read_text(encoding=_C);return B._simple_js_minify(A)if is_minify else A
35
+ def _html_main(E,eol,is_static=_B):
36
+ K=' open';H=is_static;A=eol;C=E.layout;F=_A
37
+ if C.logo_path:F=file_to_img_src_base64(C.logo_path)
38
+ if C.logo_data_source:F=C.logo_data_source
39
+ B=f'<header>{A}<img src="{F or DEFAULT_IMG_SRC}">{A}<h1>{C.title}<h1>{A}</header>{A}';B+='<div class="theme-control">'+'<button id="theme-switch" class="switch" type="button" role="switch" aria-checked="false" aria-label="Theme"></button>'+'</div>'
40
+ for(L,G)in enumerate(C.sections):
41
+ B+=f"<section>{A}";B+=f"<details{K if G.open else''}>{A}";B+=f"<summary><h2>{G.title}</h2></summary>{A}"
42
+ for(M,D)in enumerate(G.blocks):
43
+ N=f"block_{L}_{M}";I=getattr(E,f"_static_html_{D.render.type}",_A)
44
+ if H and not I:continue
45
+ J=f'<div id="{N}">{I(E.data[D.data])if H else""}</div>{A}'
46
+ if D.title:B+=f"<details{K if D.open else''}>{A}";B+=f"<summary><h3>{D.title}</h3></summary>{A}";B+=J;B+=f"</details>{A}"
47
+ else:B+=J
48
+ B+=f"</details>{A}";B+=f"</section>{A}"
49
+ return B
50
+ def _dynamic_html_layout(C,indent):
51
+ A=[];D=C.layout
52
+ for(E,F)in enumerate(D.sections):
53
+ for(G,B)in enumerate(F.blocks):H=f"block_{E}_{G}";A.append({'block_id':H,'data':B.data,'render':B.render.model_dump()})
54
+ return json.dumps(A,indent=indent)
55
+ def _static_html_raw(A,data):return str(data)
56
+ def _static_html_table(C,data,eol):
57
+ B=eol;A=data
58
+ if isinstance(A,pd.DataFrame):return A.to_html(escape=True)
59
+ elif isinstance(A,dict):return'<table>'+B+B.join([f"<tr><td>{A}</td><td>{B}</td></tr>"for(A,B)in A.items()])+'</table>'+B
@@ -0,0 +1,322 @@
1
+ 'use strict';
2
+ // utils
3
+ const $=id=>document.getElementById(id);
4
+ function el(tag,cls,text){const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n}
5
+ function table2CSV(table, separator = ",") {
6
+ const escapeCell = (value) => {
7
+ const text = String(value ?? "");
8
+ return `"${text.replace(/"/g, '""')}"`;
9
+ };
10
+ // 2 table formats supported
11
+ const isTable = Array.isArray(table.columns) && Array.isArray(table.data);
12
+ const rows = isTable
13
+ ? [table.columns, ...table.data]
14
+ : [Object.keys(table), Object.values(table)];
15
+ return rows
16
+ .map(row => row.map(escapeCell).join(separator))
17
+ .join("\r\n");
18
+ }
19
+ function downloadCSV(table, filename = "export.csv", separator = ",") {
20
+ const csv = table2CSV(table, separator)
21
+ // Le BOM UTF-8 facilite la lecture des accents dans Excel.
22
+ const blob = new Blob(["\uFEFF", csv], {type: "text/csv;charset=utf-8;"});
23
+ const url = URL.createObjectURL(blob);
24
+ const link = el("a");
25
+ link.href = url;
26
+ link.download = filename;
27
+ document.body.appendChild(link);
28
+ link.click();
29
+ link.remove();
30
+ // Laisse le temps au navigateur de démarrer le téléchargement.
31
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
32
+ }
33
+
34
+
35
+ function echarts_updateTheme(chart, dark) {
36
+
37
+ // const text = dark ? '#e4edf7' : '#172b41';
38
+ // const border = dark ? '#3b4c60' : '#d9e2eb';
39
+ // const surface = dark ? '#1b2532' : '#ffffff';
40
+ // const axis = { axisLabel: { color: text }, nameTextStyle: { color: text },
41
+ // axisLine: { lineStyle: { color: border } }, splitLine: { lineStyle: { color: border } } };
42
+ // chart.setOption({ backgroundColor: surface, textStyle: { color: text },
43
+ // xAxis: axis, yAxis: axis,
44
+ // tooltip: { backgroundColor: surface, borderColor: border, textStyle: { color: text } },
45
+ // dataZoom: [
46
+ // { textStyle: { color: text }, borderColor: border, backgroundColor: surface },
47
+ // {},
48
+ // { textStyle: { color: text }, borderColor: border, backgroundColor: surface }
49
+ // ]
50
+ // });
51
+ }
52
+
53
+ class Report {
54
+ constructor(data, design) {
55
+ this.data = data;
56
+ this.design = design;
57
+ this.echarts = [];
58
+ }
59
+ // theme
60
+ theme_is_dark() {
61
+ return document.documentElement.dataset.theme === 'dark'
62
+ }
63
+ theme_toogle(theme) {
64
+ document.documentElement.dataset.theme = theme;
65
+ try { localStorage.setItem('report-theme', theme); } catch (_) {}
66
+ }
67
+ theme_sync() {
68
+ const dark = this.theme_is_dark();
69
+ $('theme-switch').setAttribute('aria-checked', String(dark));
70
+ // this.echarts.forEach(updateChartTheme);
71
+ this.echarts.forEach(c => echarts_updateTheme(c, dark));
72
+ }
73
+ // export
74
+ renderDownloadCSV(table, name){
75
+ const but = el('button', 'button-link');
76
+ but.innerHTML = "Download csv";
77
+ but.addEventListener('click', () => {
78
+ downloadCSV(table, name + ".csv")
79
+ });
80
+ return but
81
+ }
82
+ // render
83
+ renderTable(value) {
84
+ const table = el('table');
85
+ const addRow = (parent, values, tag = 'td') => {
86
+ const row = el('tr');
87
+ for (const value of values) {
88
+ const cell = el(tag);
89
+ cell.textContent = value == null ? '' :
90
+ typeof value === 'object' ? JSON.stringify(value) : String(value);
91
+ if (tag === 'th') cell.scope = 'col';
92
+ row.appendChild(cell);
93
+ }
94
+ parent.appendChild(row);
95
+ };
96
+ const head = el('thead');
97
+ const body = el('tbody');
98
+ // 2 formats managed dataframe and key-values
99
+ if (value && Array.isArray(value.columns) && Array.isArray(value.data)) {
100
+ const hasIndex = Array.isArray(value.index);
101
+ if (hasIndex && value.index.length !== value.data.length) {
102
+ throw new Error('Table index and data lengths differ');
103
+ }
104
+ addRow(head, hasIndex ? ['Index', ...value.columns] : value.columns, 'th');
105
+ value.data.forEach((row, index) => {
106
+ if (!Array.isArray(row) || row.length !== value.columns.length) {
107
+ throw new Error('Invalid table row: ' + index);
108
+ }
109
+ addRow(body, hasIndex ? [value.index[index], ...row] : row);
110
+ });
111
+ } else if (value && typeof value === 'object' && !Array.isArray(value)) {
112
+ Object.entries(value).forEach(entry => addRow(body, entry));
113
+ } else {
114
+ throw new Error('Unsupported table data');
115
+ }
116
+ table.append(head, body);
117
+ return table;
118
+ }
119
+
120
+ renderTimeline(target, value, config) {
121
+ // value is table,
122
+ const labels_index = value.columns.indexOf(config.col_label) // TODO
123
+ const start_index = value.columns.indexOf(config.col_start)
124
+ const end_index = value.columns.indexOf(config.col_end)
125
+ const data = value.data.map((x, index) => [index, Date.parse(x[start_index]), Date.parse(x[end_index])]);
126
+ const periodStart = Math.min(...data.map(([, start]) => start));
127
+ const periodEnd = Math.max(...data.map(([, , stop]) => stop));
128
+
129
+ // html
130
+ const div = el('div');
131
+ div.style.width = '100%';
132
+ div.style.height = '520px';
133
+
134
+ // Chart
135
+ // const chart = echarts.init(div, this.theme_is_dark() ? "dark": null);
136
+ const chart = echarts.init(div)
137
+
138
+ const dateFormat = new Intl.DateTimeFormat("fr-FR", {
139
+ timeZone: "UTC",
140
+ day: "2-digit",
141
+ month: "2-digit",
142
+ hour: "2-digit",
143
+ minute: "2-digit"
144
+ });
145
+
146
+ chart.setOption({
147
+ animation: false,
148
+
149
+ grid: {
150
+ left: 100,
151
+ right: 65,
152
+ top: 80,
153
+ bottom: 110
154
+ },
155
+
156
+
157
+ tooltip: {
158
+ confine: true,
159
+ formatter: ({ value: [row, start, end] }) =>
160
+ `
161
+ Start : ${dateFormat.format(start)} UTC<br>
162
+ End : ${dateFormat.format(end)} UTC<br>
163
+ ${value.columns
164
+ .map((label, index) =>
165
+ `${label} : ${value.data[row][index] ?? ''}`
166
+ )
167
+ .join('<br>')}
168
+ `
169
+ },
170
+
171
+ xAxis: {
172
+ type: "time",
173
+ min: periodStart,
174
+ max: periodEnd,
175
+ name: "(UTC)",
176
+ nameLocation: "middle",
177
+ nameGap: 45,
178
+ splitNumber: 6,
179
+ axisLabel: {
180
+ hideOverlap: true,
181
+ formatter: value => {
182
+ const date = new Date(value);
183
+ const day = String(date.getUTCDate()).padStart(2, "0");
184
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
185
+ const hour = String(date.getUTCHours()).padStart(2, "0");
186
+
187
+ return `${day}/${month}\n${hour}:00`;
188
+ }
189
+ }
190
+ },
191
+
192
+ yAxis: {
193
+ type: "category",
194
+ inverse: true,
195
+ data: data.map(x => x[0]),
196
+ axisLabel: { interval: 0 },
197
+ axisTick: { show: false },
198
+ axisLine: { show: false }
199
+ },
200
+
201
+ dataZoom: [
202
+ {
203
+ type: "slider",
204
+ yAxisIndex: 0,
205
+ right: 10,
206
+ top: 80,
207
+ bottom: 110,
208
+ width: 20,
209
+ startValue: 0,
210
+ endValue: 40,
211
+ zoomLock: true,
212
+ filterMode: "filter",
213
+ showDetail: false,
214
+ showDataShadow: false
215
+ },
216
+ {
217
+ type: "inside",
218
+ yAxisIndex: 0,
219
+ zoomOnMouseWheel: false,
220
+ moveOnMouseWheel: true,
221
+ moveOnMouseMove: true,
222
+ filterMode: "filter"
223
+ },
224
+ // Zoom horizontal sur les dates.
225
+ {
226
+ type: "slider",
227
+ xAxisIndex: 0,
228
+ bottom: 15,
229
+ height: 22,
230
+ filterMode: "weakFilter",
231
+ showDetail: false
232
+ }
233
+ ],
234
+
235
+ series: [{
236
+ type: "custom",
237
+ data,
238
+ encode: {
239
+ x: [1, 2],
240
+ y: 0
241
+ },
242
+
243
+ renderItem(params, api) {
244
+ const row = api.value(0);
245
+ const start = api.coord([api.value(1), row]);
246
+ const end = api.coord([api.value(2), row]);
247
+ const height = Math.abs(api.size([0, 1])[1]) * 0.65;
248
+
249
+ const shape = echarts.graphic.clipRectByRect(
250
+ {
251
+ x: start[0],
252
+ y: start[1] - height / 2,
253
+ width: end[0] - start[0],
254
+ height: 8
255
+ },
256
+ {
257
+ x: params.coordSys.x,
258
+ y: params.coordSys.y,
259
+ width: params.coordSys.width,
260
+ height: params.coordSys.height
261
+ }
262
+ );
263
+
264
+ return shape && {
265
+ type: "rect",
266
+ shape,
267
+ style: { fill: "#ec624a" }, // #5470c6
268
+ emphasis: {style: { fill: "#ec624a" }} // #3654a5
269
+ };
270
+ }
271
+ }]
272
+ });
273
+ target.replaceChildren(div);
274
+ chart.resize()
275
+ window.addEventListener("resize", () => chart.resize());
276
+ }
277
+
278
+ render() {
279
+ if (!Array.isArray(this.design)) throw new Error('Invalid report design');
280
+ for (const block of this.design) {
281
+ const target = $(block.block_id);
282
+ if (!target) throw new Error('Unknown block: ' + block.block_id);
283
+ if (!Object.prototype.hasOwnProperty.call(this.data, block.data)) {
284
+ throw new Error('Missing data: ' + block.data);
285
+ }
286
+ const value = this.data[block.data];
287
+ switch (block.render.type) {
288
+ case 'raw':
289
+ // Raw blocks deliberately contain trusted report HTML.
290
+ target.innerHTML = value == null ? '' : String(value);
291
+ break;
292
+ case 'table':
293
+ target.style.overflowX = 'auto';
294
+ target.appendChild(this.renderDownloadCSV(value, block.data));
295
+ target.appendChild(this.renderTable(value));
296
+ // target.replaceChildren(this.renderTable(value));
297
+ break;
298
+ case 'timeline':
299
+ this.renderTimeline(target, value, block.render);
300
+ break;
301
+ default:
302
+ throw new Error('Unknown renderer: ' + block.render);
303
+ }
304
+ }
305
+ return this;
306
+ }
307
+ }
308
+
309
+
310
+ try{
311
+ const data=JSON.parse($('report-data').textContent),design=JSON.parse($('report-layout').textContent);
312
+ const report = new Report(data, design);
313
+ report.render();
314
+ report.theme_sync();
315
+
316
+ $('theme-switch').addEventListener('click', () => {
317
+ const theme = report.theme_is_dark() ? 'light' : 'dark';
318
+ document.documentElement.dataset.theme = theme;
319
+ try { localStorage.setItem('report-theme', theme); } catch (_) {}
320
+ report.theme_sync();
321
+ });
322
+ }catch(error){$('main').setAttribute('role','alert');$('main').textContent='Issue in loading data : '+error.message;}
@@ -0,0 +1,8 @@
1
+ (() => {
2
+ // manage in head before diplay anything
3
+
4
+ let theme;
5
+ try { theme = localStorage.getItem('report-theme'); } catch (_) {}
6
+ document.documentElement.dataset.theme = theme === 'light' || theme === 'dark'
7
+ ? theme : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
8
+ })();
@@ -0,0 +1,10 @@
1
+ _B='timeline'
2
+ _A=None
3
+ from typing import Literal
4
+ from pydantic import BaseModel,Field
5
+ class AutoRender(BaseModel):type:Literal['auto']='auto'
6
+ class RawRender(BaseModel):type:Literal['raw']='raw'
7
+ class TableRender(BaseModel):type:Literal['table']='table'
8
+ class GraphRender(BaseModel):type:Literal['graph']='graph'
9
+ class TimelineRender(BaseModel):type:Literal[_B]=_B;col_start:str;col_end:str;col_label:str|_A=_A
10
+ class BlockDesign(BaseModel):title:str|_A=_A;data:str;open:bool=True;render:RawRender|TableRender|GraphRender|TimelineRender=Field(discriminator='type',default_factory=RawRender)
@@ -0,0 +1,5 @@
1
+ _A=None
2
+ from pydantic import BaseModel,Field
3
+ from.block import BlockDesign
4
+ class SectionDesign(BaseModel):title:str;blocks:list[BlockDesign];open:bool=True
5
+ class DocLayout(BaseModel):title:str;logo_path:str|_A=_A;logo_data_source:str|_A=_A;sections:list[SectionDesign]=Field(default_factory=list)
@@ -0,0 +1,6 @@
1
+ import base64
2
+ from pathlib import Path
3
+ def file_to_img_src_base64(path):
4
+ C='image/jpeg';A=path;A=Path(A);D={'.svg':'image/svg+xml','.png':'image/png','.jpg':C,'.jpeg':C};B=D.get(A.suffix.lower())
5
+ if B is None:raise ValueError(f"Format d'image non supporté : {A.suffix}")
6
+ E=base64.b64encode(A.read_bytes()).decode('ascii');return f"data:{B};base64,{E}"
@@ -0,0 +1,16 @@
1
+ import shutil
2
+ from pathlib import Path
3
+
4
+ CURRENT_DIR = Path(__file__).parent.resolve()
5
+
6
+
7
+ def tmp_persistent_folder(name: str) -> Path:
8
+ """
9
+ tests/tmp is in .gitignore
10
+ """
11
+ output_folder = CURRENT_DIR / "tmp" / name
12
+ if output_folder.exists():
13
+ shutil.rmtree(output_folder)
14
+ output_folder.mkdir(parents=True)
15
+ return output_folder
16
+
@@ -0,0 +1,32 @@
1
+
2
+ from simplydoc import Doc
3
+
4
+ from dev import tmp_persistent_folder
5
+
6
+ def test_1(tmp_path):
7
+
8
+ tmp_path = tmp_persistent_folder("tmp") # for dev
9
+
10
+ doc = Doc(
11
+ data={
12
+ "content_1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
13
+ "content_2": "Sed non risus.",
14
+ },
15
+ layout={
16
+ "title": "This is a title",
17
+ "sections": [
18
+ {
19
+ "title": "Part 1",
20
+ "blocks": [
21
+ {"data": "content_1"},
22
+ {"data": "content_2"},
23
+ ]
24
+ }
25
+ ],
26
+ },
27
+ )
28
+
29
+ doc.to_html(tmp_path / "report.html")
30
+
31
+
32
+ assert True