margin-notes 0.1.0__py3-none-any.whl
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.
- margin_notes/__init__.py +3 -0
- margin_notes/__main__.py +3 -0
- margin_notes/cli.py +103 -0
- margin_notes/notes.py +112 -0
- margin_notes/py.typed +0 -0
- margin_notes/render.py +142 -0
- margin_notes/server.py +145 -0
- margin_notes/static/page.css +88 -0
- margin_notes/static/review.js +435 -0
- margin_notes-0.1.0.dist-info/METADATA +172 -0
- margin_notes-0.1.0.dist-info/RECORD +14 -0
- margin_notes-0.1.0.dist-info/WHEEL +4 -0
- margin_notes-0.1.0.dist-info/entry_points.txt +2 -0
- margin_notes-0.1.0.dist-info/licenses/LICENSE +21 -0
margin_notes/__init__.py
ADDED
margin_notes/__main__.py
ADDED
margin_notes/cli.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Command line: `margin-notes [PATH] [--host HOST] [--port PORT]`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import ipaddress
|
|
8
|
+
import socket
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import webbrowser
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .server import create_app, is_reviewable
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def free_port(host: str, start: int) -> int:
|
|
20
|
+
family = socket.AF_INET6 if ":" in host else socket.AF_INET
|
|
21
|
+
for port in range(start, start + 50):
|
|
22
|
+
with socket.socket(family) as s:
|
|
23
|
+
try:
|
|
24
|
+
s.bind((host, port))
|
|
25
|
+
return port
|
|
26
|
+
except OSError:
|
|
27
|
+
continue
|
|
28
|
+
raise SystemExit(f"margin-notes: no free port in {start}-{start + 49} on {host}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def lan_address() -> str | None:
|
|
32
|
+
# A UDP "connect" picks the outbound interface without sending anything.
|
|
33
|
+
try:
|
|
34
|
+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
|
35
|
+
s.connect(("192.0.2.1", 9))
|
|
36
|
+
return s.getsockname()[0]
|
|
37
|
+
except OSError:
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_loopback(host: str) -> bool:
|
|
42
|
+
if host == "localhost":
|
|
43
|
+
return True
|
|
44
|
+
try:
|
|
45
|
+
return ipaddress.ip_address(host).is_loopback
|
|
46
|
+
except ValueError:
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def main(argv: list[str] | None = None) -> None:
|
|
51
|
+
ap = argparse.ArgumentParser(
|
|
52
|
+
prog="margin-notes",
|
|
53
|
+
description="Serve a folder or a document, highlight and comment on HTML and Markdown, "
|
|
54
|
+
"and save the notes as <document>.notes.json beside each one.",
|
|
55
|
+
)
|
|
56
|
+
ap.add_argument(
|
|
57
|
+
"path", nargs="?", default=".", type=Path, help="a folder to browse or a document to open (default: .)"
|
|
58
|
+
)
|
|
59
|
+
ap.add_argument(
|
|
60
|
+
"--host", default="127.0.0.1", help="interface to bind; 0.0.0.0 exposes it to your network (default: 127.0.0.1)"
|
|
61
|
+
)
|
|
62
|
+
ap.add_argument("-p", "--port", type=int, default=8765, help="first port to try (default: 8765)")
|
|
63
|
+
ap.add_argument("--no-open", action="store_true", help="don't open a browser")
|
|
64
|
+
ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
65
|
+
args = ap.parse_args(argv)
|
|
66
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
67
|
+
sys.stdout.reconfigure(line_buffering=True) # show the banner even when piped
|
|
68
|
+
|
|
69
|
+
import uvicorn # deferred so --help and --version stay fast
|
|
70
|
+
|
|
71
|
+
target = args.path.expanduser().resolve()
|
|
72
|
+
if not target.exists():
|
|
73
|
+
raise SystemExit(f"margin-notes: no such file or folder: {target}")
|
|
74
|
+
if target.is_dir():
|
|
75
|
+
root, start_path = target, "/"
|
|
76
|
+
else:
|
|
77
|
+
root, start_path = target.parent, "/" + quote(target.name)
|
|
78
|
+
if not is_reviewable(target):
|
|
79
|
+
print(f"margin-notes: {target.name} isn't Markdown or HTML; it will be served as-is.", file=sys.stderr)
|
|
80
|
+
|
|
81
|
+
port = free_port(args.host, args.port)
|
|
82
|
+
browse_host = "127.0.0.1" if args.host in ("0.0.0.0", "::", "") else args.host
|
|
83
|
+
url = f"http://{f'[{browse_host}]' if ':' in browse_host else browse_host}:{port}{start_path}"
|
|
84
|
+
|
|
85
|
+
print(f"margin-notes {__version__}")
|
|
86
|
+
print(f" serving {root}")
|
|
87
|
+
print(f" open {url}")
|
|
88
|
+
if args.host in ("0.0.0.0", "::"):
|
|
89
|
+
lan = lan_address()
|
|
90
|
+
if lan:
|
|
91
|
+
print(f" network http://{lan}:{port}{start_path}")
|
|
92
|
+
if not is_loopback(args.host):
|
|
93
|
+
print(
|
|
94
|
+
" warning anyone who can reach this address can read every file under the folder "
|
|
95
|
+
"and add notes. There is no authentication.",
|
|
96
|
+
file=sys.stderr,
|
|
97
|
+
)
|
|
98
|
+
print(" Ctrl-C to stop")
|
|
99
|
+
|
|
100
|
+
if not args.no_open:
|
|
101
|
+
threading.Timer(1.0, webbrowser.open, args=(url,)).start()
|
|
102
|
+
with contextlib.suppress(KeyboardInterrupt):
|
|
103
|
+
uvicorn.run(create_app(root), host=args.host, port=port, log_level="warning")
|
margin_notes/notes.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""The `<document>.notes.json` file that sits beside each reviewed document."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
import threading
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
ABOUT = (
|
|
16
|
+
"Review notes on {doc}. Notes are in document order. Each note has `quote` (the "
|
|
17
|
+
"highlighted text, whitespace collapsed), `section` (the nearest heading before it), "
|
|
18
|
+
"and `comment` (the reviewer's remark; may be empty for a bare highlight). A note "
|
|
19
|
+
"with a null `quote` is a general comment on the whole document. `anchor` holds the "
|
|
20
|
+
"exact text and surrounding context used to re-find the highlight. If "
|
|
21
|
+
"`document_sha256` no longer matches the file, the document changed after review."
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _file_mode() -> int:
|
|
26
|
+
mask = os.umask(0) # reading the umask means setting it; do it once, at import
|
|
27
|
+
os.umask(mask)
|
|
28
|
+
return 0o666 & ~mask
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
FILE_MODE = _file_mode()
|
|
32
|
+
NOTE_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def notes_path(doc: Path) -> Path:
|
|
36
|
+
return doc.with_name(f"{doc.name}.notes.json")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def now() -> str:
|
|
40
|
+
return datetime.now().astimezone().isoformat(timespec="seconds")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _order(note: dict[str, Any]) -> tuple:
|
|
44
|
+
anchor = note.get("anchor")
|
|
45
|
+
if isinstance(anchor, dict):
|
|
46
|
+
return (1, anchor.get("start") or 0, "")
|
|
47
|
+
return (0, 0, str(note.get("created_at", "")))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def validate(note: Any) -> dict[str, Any]:
|
|
51
|
+
if not isinstance(note, dict) or not isinstance(note.get("id"), str) or not NOTE_ID.match(note["id"]):
|
|
52
|
+
raise ValueError("a note is an object with an `id` of letters, digits, _ or -")
|
|
53
|
+
return {k: v for k, v in note.items() if not k.startswith("_")}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class NoteStore:
|
|
57
|
+
"""Read-modify-write under one lock, so concurrent reviewers never clobber each other."""
|
|
58
|
+
|
|
59
|
+
def __init__(self) -> None:
|
|
60
|
+
self._lock = threading.Lock()
|
|
61
|
+
|
|
62
|
+
def read(self, doc: Path) -> list[dict[str, Any]]:
|
|
63
|
+
path = notes_path(doc)
|
|
64
|
+
if not path.exists():
|
|
65
|
+
return []
|
|
66
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
67
|
+
return list(data.get("notes", []))
|
|
68
|
+
|
|
69
|
+
def count(self, doc: Path) -> int:
|
|
70
|
+
try:
|
|
71
|
+
return len(self.read(doc))
|
|
72
|
+
except (OSError, ValueError):
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
def upsert(self, doc: Path, note: dict[str, Any]) -> list[dict[str, Any]]:
|
|
76
|
+
note = validate(note)
|
|
77
|
+
with self._lock:
|
|
78
|
+
notes = [n for n in self.read(doc) if n.get("id") != note["id"]]
|
|
79
|
+
notes.append(note)
|
|
80
|
+
return self._write(doc, notes)
|
|
81
|
+
|
|
82
|
+
def delete(self, doc: Path, note_id: str) -> list[dict[str, Any]]:
|
|
83
|
+
with self._lock:
|
|
84
|
+
notes = self.read(doc)
|
|
85
|
+
kept = [n for n in notes if n.get("id") != note_id]
|
|
86
|
+
return self._write(doc, kept) if len(kept) != len(notes) else notes
|
|
87
|
+
|
|
88
|
+
def _write(self, doc: Path, notes: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
89
|
+
notes.sort(key=_order)
|
|
90
|
+
path = notes_path(doc)
|
|
91
|
+
if not notes and path.exists():
|
|
92
|
+
path.unlink()
|
|
93
|
+
return notes
|
|
94
|
+
data = {
|
|
95
|
+
"about": ABOUT.format(doc=doc.name),
|
|
96
|
+
"document": doc.name,
|
|
97
|
+
"document_path": str(doc),
|
|
98
|
+
"document_sha256": hashlib.sha256(doc.read_bytes()).hexdigest(),
|
|
99
|
+
"updated_at": now(),
|
|
100
|
+
"notes": notes,
|
|
101
|
+
}
|
|
102
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".notes-", suffix=".tmp")
|
|
103
|
+
try:
|
|
104
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
105
|
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
106
|
+
f.write("\n")
|
|
107
|
+
os.chmod(tmp, FILE_MODE) # mkstemp creates 0600; use ordinary permissions
|
|
108
|
+
os.replace(tmp, path)
|
|
109
|
+
except BaseException:
|
|
110
|
+
Path(tmp).unlink(missing_ok=True)
|
|
111
|
+
raise
|
|
112
|
+
return notes
|
margin_notes/py.typed
ADDED
|
File without changes
|
margin_notes/render.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Markdown -> a standalone, styled HTML page (GFM, code highlighting, math, mermaid)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
from functools import lru_cache
|
|
8
|
+
|
|
9
|
+
from markdown_it import MarkdownIt
|
|
10
|
+
from mdit_py_plugins.anchors import anchors_plugin
|
|
11
|
+
from mdit_py_plugins.deflist import deflist_plugin
|
|
12
|
+
from mdit_py_plugins.dollarmath import dollarmath_plugin
|
|
13
|
+
from mdit_py_plugins.footnote import footnote_plugin
|
|
14
|
+
from mdit_py_plugins.front_matter import front_matter_plugin
|
|
15
|
+
from mdit_py_plugins.tasklists import tasklists_plugin
|
|
16
|
+
from pygments import highlight
|
|
17
|
+
from pygments.formatters import HtmlFormatter
|
|
18
|
+
from pygments.lexers import get_lexer_by_name
|
|
19
|
+
from pygments.util import ClassNotFound
|
|
20
|
+
|
|
21
|
+
MATHJAX_URL = "https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js"
|
|
22
|
+
MERMAID_URL = "https://cdn.jsdelivr.net/npm/mermaid@11.4.1/dist/mermaid.esm.min.mjs"
|
|
23
|
+
|
|
24
|
+
ALERTS = {"NOTE": "Note", "TIP": "Tip", "IMPORTANT": "Important", "WARNING": "Warning", "CAUTION": "Caution"}
|
|
25
|
+
_ALERT_RE = re.compile(r"<blockquote>\s*<p>\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(?:<br\s*/?>)?\s*")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _highlight(code: str, lang: str, _attrs: str) -> str:
|
|
29
|
+
if not lang:
|
|
30
|
+
return "" # markdown-it escapes it as plain code
|
|
31
|
+
try:
|
|
32
|
+
lexer = get_lexer_by_name(lang)
|
|
33
|
+
except ClassNotFound:
|
|
34
|
+
return ""
|
|
35
|
+
return highlight(code, lexer, HtmlFormatter(nowrap=True))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _math(content: str, opts: dict) -> str:
|
|
39
|
+
# Emit TeX with MathJax delimiters; MathJax typesets it in the browser.
|
|
40
|
+
tex = html.escape(content)
|
|
41
|
+
return f"\\[{tex}\\]" if opts.get("display_mode") else f"\\({tex}\\)"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@lru_cache(maxsize=1)
|
|
45
|
+
def _parser() -> MarkdownIt:
|
|
46
|
+
md = MarkdownIt("gfm-like", {"highlight": _highlight, "typographer": False})
|
|
47
|
+
md.use(front_matter_plugin)
|
|
48
|
+
md.use(footnote_plugin)
|
|
49
|
+
md.use(deflist_plugin)
|
|
50
|
+
md.use(tasklists_plugin)
|
|
51
|
+
md.use(anchors_plugin, min_level=1, max_level=6)
|
|
52
|
+
md.use(dollarmath_plugin, renderer=_math, double_inline=True, allow_digits=False)
|
|
53
|
+
|
|
54
|
+
default_fence = md.renderer.rules["fence"]
|
|
55
|
+
|
|
56
|
+
def fence(self, tokens, idx, options, env):
|
|
57
|
+
info = tokens[idx].info.strip()
|
|
58
|
+
lang = info.split(maxsplit=1)[0].lower() if info else ""
|
|
59
|
+
if lang == "mermaid":
|
|
60
|
+
return f'<pre class="mermaid">{html.escape(tokens[idx].content)}</pre>\n'
|
|
61
|
+
if lang == "math":
|
|
62
|
+
return f'<div class="math block">\\[{html.escape(tokens[idx].content.strip())}\\]</div>\n'
|
|
63
|
+
return default_fence(tokens, idx, options, env)
|
|
64
|
+
|
|
65
|
+
md.add_render_rule("fence", fence)
|
|
66
|
+
return md
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@lru_cache(maxsize=1)
|
|
70
|
+
def pygments_css() -> str:
|
|
71
|
+
def defs(style: str) -> str:
|
|
72
|
+
lines = HtmlFormatter(style=style).get_style_defs(".markdown-body pre").splitlines()
|
|
73
|
+
# Drop the base rule (background/colour) and unscoped rules; page.css owns those.
|
|
74
|
+
return "\n".join(line for line in lines if line.startswith(".markdown-body pre ."))
|
|
75
|
+
|
|
76
|
+
return f"{defs('default')}\n@media (prefers-color-scheme: dark) {{\n{defs('github-dark')}\n}}\n"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _title(tokens, fallback: str) -> str:
|
|
80
|
+
for i, tok in enumerate(tokens):
|
|
81
|
+
if tok.type == "front_matter":
|
|
82
|
+
m = re.search(r"^title:\s*[\"']?(.+?)[\"']?\s*$", tok.content, re.M)
|
|
83
|
+
if m:
|
|
84
|
+
return m.group(1)
|
|
85
|
+
if tok.type == "heading_open" and tok.tag == "h1" and i + 1 < len(tokens):
|
|
86
|
+
return tokens[i + 1].content
|
|
87
|
+
return fallback
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def render_markdown(text: str, name: str) -> str:
|
|
91
|
+
md = _parser()
|
|
92
|
+
tokens = md.parse(text, {})
|
|
93
|
+
body = md.renderer.render(tokens, md.options, {})
|
|
94
|
+
body = _ALERT_RE.sub(
|
|
95
|
+
lambda m: (
|
|
96
|
+
f'<blockquote class="alert alert-{m.group(1).lower()}"><p class="alert-title">{ALERTS[m.group(1)]}</p><p>'
|
|
97
|
+
),
|
|
98
|
+
body,
|
|
99
|
+
)
|
|
100
|
+
title = html.escape(_title(tokens, name))
|
|
101
|
+
has_math = 'class="math' in body
|
|
102
|
+
has_mermaid = 'class="mermaid"' in body
|
|
103
|
+
|
|
104
|
+
head = [
|
|
105
|
+
'<meta charset="utf-8">',
|
|
106
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
|
107
|
+
f"<title>{title}</title>",
|
|
108
|
+
'<link rel="stylesheet" href="/__review/static/page.css">',
|
|
109
|
+
f"<style>{pygments_css()}</style>",
|
|
110
|
+
"<script>window.__reviewWait = [];</script>",
|
|
111
|
+
]
|
|
112
|
+
if has_math:
|
|
113
|
+
head.append(
|
|
114
|
+
"""<script>
|
|
115
|
+
window.__reviewWait.push(new Promise((done) => {
|
|
116
|
+
window.MathJax = {
|
|
117
|
+
tex: { inlineMath: [["\\\\(", "\\\\)"]], displayMath: [["\\\\[", "\\\\]"]], tags: "ams" },
|
|
118
|
+
options: { ignoreHtmlClass: "tex2jax_ignore", processHtmlClass: "math" },
|
|
119
|
+
startup: { pageReady: () => MathJax.startup.defaultPageReady().then(done, done) },
|
|
120
|
+
};
|
|
121
|
+
}));
|
|
122
|
+
</script>"""
|
|
123
|
+
)
|
|
124
|
+
head.append(f'<script defer src="{MATHJAX_URL}"></script>')
|
|
125
|
+
tail = []
|
|
126
|
+
if has_mermaid:
|
|
127
|
+
tail.append(
|
|
128
|
+
f"""<script type="module">
|
|
129
|
+
import mermaid from "{MERMAID_URL}";
|
|
130
|
+
const dark = matchMedia("(prefers-color-scheme: dark)").matches;
|
|
131
|
+
mermaid.initialize({{ startOnLoad: false, theme: dark ? "dark" : "default" }});
|
|
132
|
+
window.__reviewWait.push(mermaid.run({{ querySelector: "pre.mermaid" }}).catch(console.error));
|
|
133
|
+
</script>"""
|
|
134
|
+
)
|
|
135
|
+
tail.append('<script src="/__review/static/review.js" defer></script>')
|
|
136
|
+
return (
|
|
137
|
+
'<!doctype html>\n<html lang="en">\n<head>\n'
|
|
138
|
+
+ "\n".join(head)
|
|
139
|
+
+ f'\n</head>\n<body class="mn-page">\n<main class="markdown-body">\n{body}</main>\n'
|
|
140
|
+
+ "\n".join(tail)
|
|
141
|
+
+ "\n</body>\n</html>\n"
|
|
142
|
+
)
|
margin_notes/server.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""FastAPI app: browse a folder, render documents with the review overlay, store notes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
from importlib.resources import files
|
|
7
|
+
from pathlib import Path, PurePosixPath
|
|
8
|
+
from urllib.parse import quote, unquote
|
|
9
|
+
|
|
10
|
+
from fastapi import FastAPI, HTTPException, Query, Request
|
|
11
|
+
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse, Response
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .notes import NoteStore, notes_path
|
|
15
|
+
from .render import render_markdown
|
|
16
|
+
|
|
17
|
+
MARKDOWN = {".md", ".markdown", ".mdown", ".mkd"}
|
|
18
|
+
HTML = {".html", ".htm"}
|
|
19
|
+
REVIEWABLE = MARKDOWN | HTML
|
|
20
|
+
STATIC = {"review.js": "application/javascript", "page.css": "text/css"}
|
|
21
|
+
NO_STORE = {"Cache-Control": "no-store"}
|
|
22
|
+
OVERLAY_TAG = '<script src="/__review/static/review.js" defer></script>'
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_reviewable(path: Path) -> bool:
|
|
26
|
+
return path.suffix.lower() in REVIEWABLE
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def inject_overlay(page: str) -> str:
|
|
30
|
+
i = page.lower().rfind("</body>")
|
|
31
|
+
return page[:i] + OVERLAY_TAG + page[i:] if i != -1 else page + OVERLAY_TAG
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def create_app(root: Path) -> FastAPI:
|
|
35
|
+
root = root.resolve()
|
|
36
|
+
store = NoteStore()
|
|
37
|
+
app = FastAPI(title="margin-notes", version=__version__, docs_url=None, redoc_url=None, openapi_url=None)
|
|
38
|
+
|
|
39
|
+
def resolve(rel: str) -> Path:
|
|
40
|
+
"""Map a URL path to a file under root. Dotfiles and anything outside root are 404."""
|
|
41
|
+
parts = PurePosixPath(rel.strip("/")).parts
|
|
42
|
+
if any(p.startswith(".") for p in parts):
|
|
43
|
+
raise HTTPException(404)
|
|
44
|
+
target = root.joinpath(*parts).resolve()
|
|
45
|
+
if not target.is_relative_to(root) or not target.exists():
|
|
46
|
+
raise HTTPException(404)
|
|
47
|
+
return target
|
|
48
|
+
|
|
49
|
+
def doc_for(doc: str) -> Path:
|
|
50
|
+
target = resolve(unquote(doc))
|
|
51
|
+
if not target.is_file() or not is_reviewable(target):
|
|
52
|
+
raise HTTPException(404, "not a reviewable document")
|
|
53
|
+
return target
|
|
54
|
+
|
|
55
|
+
def notes_payload(doc: Path, notes: list) -> dict:
|
|
56
|
+
return {"notes": notes, "notes_file": notes_path(doc).name}
|
|
57
|
+
|
|
58
|
+
@app.get("/__review/static/{name}")
|
|
59
|
+
def static(name: str) -> Response:
|
|
60
|
+
if name not in STATIC:
|
|
61
|
+
raise HTTPException(404)
|
|
62
|
+
body = files("margin_notes").joinpath("static", name).read_text(encoding="utf-8")
|
|
63
|
+
return Response(body, media_type=STATIC[name], headers=NO_STORE)
|
|
64
|
+
|
|
65
|
+
@app.get("/__review/api/notes")
|
|
66
|
+
def get_notes(doc: str = Query(...)) -> dict:
|
|
67
|
+
path = doc_for(doc)
|
|
68
|
+
try:
|
|
69
|
+
return notes_payload(path, store.read(path))
|
|
70
|
+
except ValueError as e:
|
|
71
|
+
raise HTTPException(500, f"{notes_path(path).name} is not valid JSON: {e}") from e
|
|
72
|
+
|
|
73
|
+
@app.put("/__review/api/notes")
|
|
74
|
+
async def put_note(request: Request, doc: str = Query(...)) -> dict:
|
|
75
|
+
path = doc_for(doc)
|
|
76
|
+
try:
|
|
77
|
+
return notes_payload(path, store.upsert(path, await request.json()))
|
|
78
|
+
except ValueError as e:
|
|
79
|
+
raise HTTPException(400, str(e)) from e
|
|
80
|
+
|
|
81
|
+
@app.delete("/__review/api/notes/{note_id}")
|
|
82
|
+
def delete_note(note_id: str, doc: str = Query(...)) -> dict:
|
|
83
|
+
path = doc_for(doc)
|
|
84
|
+
return notes_payload(path, store.delete(path, note_id))
|
|
85
|
+
|
|
86
|
+
@app.get("/{rel:path}")
|
|
87
|
+
def serve(rel: str, raw: bool = False) -> Response:
|
|
88
|
+
if rel == "favicon.ico" and not (root / rel).is_file():
|
|
89
|
+
return Response(status_code=204)
|
|
90
|
+
target = resolve(rel)
|
|
91
|
+
if target.is_dir():
|
|
92
|
+
if rel and not rel.endswith("/"):
|
|
93
|
+
return RedirectResponse(f"/{quote(rel)}/")
|
|
94
|
+
return HTMLResponse(listing(root, target, store), headers=NO_STORE)
|
|
95
|
+
suffix = target.suffix.lower()
|
|
96
|
+
if not raw and suffix in MARKDOWN:
|
|
97
|
+
text = target.read_text(encoding="utf-8", errors="replace")
|
|
98
|
+
return HTMLResponse(render_markdown(text, target.name), headers=NO_STORE)
|
|
99
|
+
if not raw and suffix in HTML:
|
|
100
|
+
page = target.read_text(encoding="utf-8", errors="replace")
|
|
101
|
+
return HTMLResponse(inject_overlay(page), headers=NO_STORE)
|
|
102
|
+
return FileResponse(target, headers=NO_STORE)
|
|
103
|
+
|
|
104
|
+
return app
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def listing(root: Path, folder: Path, store: NoteStore) -> str:
|
|
108
|
+
rel = folder.relative_to(root)
|
|
109
|
+
crumbs = [f'<a href="/">{html.escape(root.name or "/")}</a>']
|
|
110
|
+
acc = ""
|
|
111
|
+
for part in rel.parts:
|
|
112
|
+
acc += quote(part) + "/"
|
|
113
|
+
crumbs.append(f'<a href="/{acc}">{html.escape(part)}</a>')
|
|
114
|
+
|
|
115
|
+
entries = [p for p in folder.iterdir() if not p.name.startswith(".") and not p.name.endswith(".notes.json")]
|
|
116
|
+
entries.sort(key=lambda p: (not p.is_dir(), not is_reviewable(p), p.name.lower()))
|
|
117
|
+
rows = []
|
|
118
|
+
if rel.parts:
|
|
119
|
+
rows.append('<li class="dir"><a href="../">../</a></li>')
|
|
120
|
+
for p in entries:
|
|
121
|
+
name = html.escape(p.name)
|
|
122
|
+
href = quote(p.name)
|
|
123
|
+
if p.is_dir():
|
|
124
|
+
rows.append(f'<li class="dir"><a href="{href}/">{name}/</a></li>')
|
|
125
|
+
elif is_reviewable(p):
|
|
126
|
+
n = store.count(p)
|
|
127
|
+
badge = f'<span class="badge">{n} note{"s" if n != 1 else ""}</span>' if n else ""
|
|
128
|
+
kind = "md" if p.suffix.lower() in MARKDOWN else "html"
|
|
129
|
+
rows.append(
|
|
130
|
+
f'<li class="doc {kind}"><a href="{href}">{name}</a>{badge}'
|
|
131
|
+
f'<a class="raw" href="{href}?raw=1">raw</a></li>'
|
|
132
|
+
)
|
|
133
|
+
else:
|
|
134
|
+
rows.append(f'<li class="file"><a href="{href}">{name}</a></li>')
|
|
135
|
+
body = "\n".join(rows) or '<li class="empty">Nothing here.</li>'
|
|
136
|
+
return f"""<!doctype html>
|
|
137
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
138
|
+
<title>{html.escape(rel.as_posix() if rel.parts else (root.name or "/"))} · margin-notes</title>
|
|
139
|
+
<link rel="stylesheet" href="/__review/static/page.css"></head>
|
|
140
|
+
<body class="mn-page"><main class="listing">
|
|
141
|
+
<nav class="crumbs">{" / ".join(crumbs)}</nav>
|
|
142
|
+
<p class="hint">Open a Markdown or HTML document to highlight and comment on it.
|
|
143
|
+
Notes save beside each document as <code><name>.notes.json</code>.</p>
|
|
144
|
+
<ul>{body}</ul>
|
|
145
|
+
</main></body></html>"""
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/* margin-notes: rendered Markdown and folder listings. */
|
|
2
|
+
:root {
|
|
3
|
+
--bg: #ffffff; --fg: #1f2328; --muted: #59636e; --line: #d1d9e0; --soft: #f6f8fa;
|
|
4
|
+
--accent: #0969da; --code-bg: #f6f8fa; --mark: #fff8c5;
|
|
5
|
+
--note: #0969da; --tip: #1a7f37; --important: #8250df; --warning: #9a6700; --caution: #d1242f;
|
|
6
|
+
color-scheme: light dark;
|
|
7
|
+
}
|
|
8
|
+
@media (prefers-color-scheme: dark) {
|
|
9
|
+
:root {
|
|
10
|
+
--bg: #0d1117; --fg: #e6edf3; --muted: #9198a1; --line: #3d444d; --soft: #151b23;
|
|
11
|
+
--accent: #4493f8; --code-bg: #151b23; --mark: #bb800926;
|
|
12
|
+
--note: #4493f8; --tip: #3fb950; --important: #ab7df8; --warning: #d29922; --caution: #f85149;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
* { box-sizing: border-box; }
|
|
16
|
+
body.mn-page { margin: 0; background: var(--bg); color: var(--fg);
|
|
17
|
+
font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif; }
|
|
18
|
+
a { color: var(--accent); text-decoration: none; }
|
|
19
|
+
a:hover { text-decoration: underline; }
|
|
20
|
+
code, pre, kbd, samp { font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; }
|
|
21
|
+
|
|
22
|
+
/* ---------- Markdown ---------- */
|
|
23
|
+
.markdown-body { max-width: 860px; margin: 0 auto; padding: 48px 16px 120px; word-wrap: break-word; }
|
|
24
|
+
.markdown-body > :first-child { margin-top: 0; }
|
|
25
|
+
.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 {
|
|
26
|
+
margin: 1.6em 0 .6em; font-weight: 600; line-height: 1.25; scroll-margin-top: 16px; }
|
|
27
|
+
.markdown-body h1 { font-size: 2em; padding-bottom: .3em; border-bottom: 1px solid var(--line); }
|
|
28
|
+
.markdown-body h2 { font-size: 1.5em; padding-bottom: .3em; border-bottom: 1px solid var(--line); }
|
|
29
|
+
.markdown-body h3 { font-size: 1.25em; }
|
|
30
|
+
.markdown-body h4 { font-size: 1em; }
|
|
31
|
+
.markdown-body h5 { font-size: .875em; }
|
|
32
|
+
.markdown-body h6 { font-size: .85em; color: var(--muted); }
|
|
33
|
+
.markdown-body p, .markdown-body ul, .markdown-body ol, .markdown-body dl, .markdown-body table,
|
|
34
|
+
.markdown-body blockquote, .markdown-body pre, .markdown-body details { margin: 0 0 16px; }
|
|
35
|
+
.markdown-body ul, .markdown-body ol { padding-left: 2em; }
|
|
36
|
+
.markdown-body li + li { margin-top: .25em; }
|
|
37
|
+
.markdown-body li > p { margin: .5em 0; }
|
|
38
|
+
.markdown-body .contains-task-list { list-style: none; padding-left: 1.2em; }
|
|
39
|
+
.markdown-body .task-list-item-checkbox { margin: 0 .4em 0 -1.2em; vertical-align: middle; }
|
|
40
|
+
.markdown-body dt { font-weight: 600; margin-top: 12px; }
|
|
41
|
+
.markdown-body dd { margin: 0 0 8px 1.5em; }
|
|
42
|
+
.markdown-body hr { height: 2px; border: 0; background: var(--line); margin: 24px 0; }
|
|
43
|
+
.markdown-body img, .markdown-body video { max-width: 100%; height: auto; background: var(--bg); }
|
|
44
|
+
.markdown-body blockquote { padding: 0 1em; color: var(--muted); border-left: .25em solid var(--line); }
|
|
45
|
+
.markdown-body blockquote > :last-child { margin-bottom: 0; }
|
|
46
|
+
.markdown-body mark { background: var(--mark); color: inherit; }
|
|
47
|
+
.markdown-body kbd { padding: 2px 5px; font-size: .85em; border: 1px solid var(--line); border-bottom-width: 2px;
|
|
48
|
+
border-radius: 6px; background: var(--soft); }
|
|
49
|
+
.markdown-body :not(pre) > code { padding: .2em .4em; font-size: 85%; background: var(--code-bg); border-radius: 6px; }
|
|
50
|
+
.markdown-body pre { padding: 16px; overflow: auto; font-size: 85%; line-height: 1.45; background: var(--code-bg);
|
|
51
|
+
border-radius: 6px; color: var(--fg); }
|
|
52
|
+
.markdown-body pre code { background: none; padding: 0; font-size: 100%; }
|
|
53
|
+
.markdown-body pre.mermaid { background: none; text-align: center; }
|
|
54
|
+
.markdown-body table { display: block; width: max-content; max-width: 100%; overflow: auto; border-collapse: collapse; }
|
|
55
|
+
.markdown-body th, .markdown-body td { padding: 6px 13px; border: 1px solid var(--line); }
|
|
56
|
+
.markdown-body th { font-weight: 600; background: var(--soft); }
|
|
57
|
+
.markdown-body tr:nth-child(2n) td { background: var(--soft); }
|
|
58
|
+
.markdown-body .math.block { overflow-x: auto; overflow-y: hidden; margin: 0 0 16px; }
|
|
59
|
+
.markdown-body .footnotes { font-size: .875em; color: var(--muted); }
|
|
60
|
+
.markdown-body .footnotes-sep { margin-top: 40px; }
|
|
61
|
+
.markdown-body details summary { cursor: pointer; }
|
|
62
|
+
|
|
63
|
+
/* GitHub-style alerts: > [!NOTE], [!TIP], [!IMPORTANT], [!WARNING], [!CAUTION] */
|
|
64
|
+
.markdown-body .alert { color: inherit; border-left-color: var(--alert); }
|
|
65
|
+
.markdown-body .alert-title { color: var(--alert); font-weight: 600; margin-bottom: 4px; }
|
|
66
|
+
.markdown-body .alert-note { --alert: var(--note); }
|
|
67
|
+
.markdown-body .alert-tip { --alert: var(--tip); }
|
|
68
|
+
.markdown-body .alert-important { --alert: var(--important); }
|
|
69
|
+
.markdown-body .alert-warning { --alert: var(--warning); }
|
|
70
|
+
.markdown-body .alert-caution { --alert: var(--caution); }
|
|
71
|
+
|
|
72
|
+
/* ---------- Folder listing ---------- */
|
|
73
|
+
.listing { max-width: 860px; margin: 0 auto; padding: 40px 16px 80px; }
|
|
74
|
+
.listing .crumbs { font-size: 1.25em; font-weight: 600; margin-bottom: 4px; overflow-wrap: anywhere; }
|
|
75
|
+
.listing .hint { color: var(--muted); font-size: .9em; margin: 0 0 20px; }
|
|
76
|
+
.listing .hint code { font-size: .9em; background: var(--soft); padding: 1px 4px; border-radius: 4px; }
|
|
77
|
+
.listing ul { list-style: none; margin: 0; padding: 0; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
|
|
78
|
+
.listing li { display: flex; align-items: center; gap: 10px; padding: 8px 14px; border-top: 1px solid var(--line); }
|
|
79
|
+
.listing li:first-child { border-top: 0; }
|
|
80
|
+
.listing li > a:first-child { flex: 1; overflow-wrap: anywhere; }
|
|
81
|
+
.listing li::before { width: 3.2em; flex: none; font-size: .75em; font-weight: 600; color: var(--muted); }
|
|
82
|
+
.listing li.dir::before { content: "DIR"; }
|
|
83
|
+
.listing li.md::before { content: "MD"; color: var(--accent); }
|
|
84
|
+
.listing li.html::before { content: "HTML"; color: var(--accent); }
|
|
85
|
+
.listing li.file > a { color: var(--muted); }
|
|
86
|
+
.listing li.empty { color: var(--muted); }
|
|
87
|
+
.listing .badge { font-size: .75em; padding: 1px 8px; border-radius: 10px; background: var(--mark); white-space: nowrap; }
|
|
88
|
+
.listing .raw { font-size: .8em; color: var(--muted); }
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// margin-notes review overlay: select text -> comment; notes save beside the document.
|
|
2
|
+
(() => {
|
|
3
|
+
if (window.__marginNotes) return;
|
|
4
|
+
window.__marginNotes = true;
|
|
5
|
+
|
|
6
|
+
const DOC = encodeURIComponent(location.pathname);
|
|
7
|
+
const API = "/__review/api/notes";
|
|
8
|
+
const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "TEXTAREA", "SELECT", "MJX-CONTAINER"]);
|
|
9
|
+
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
10
|
+
const CTX = 48;
|
|
11
|
+
let notes = [];
|
|
12
|
+
let notesFile = "";
|
|
13
|
+
let pending = null; // selection waiting for the Comment button
|
|
14
|
+
let editing = null; // {note, isNew}
|
|
15
|
+
|
|
16
|
+
// ---------- highlight styles live in the page; all UI lives in a shadow root ----------
|
|
17
|
+
const pageStyle = document.createElement("style");
|
|
18
|
+
pageStyle.textContent = `
|
|
19
|
+
mark.__rv { background: rgba(255, 210, 70, .5) !important; color: inherit !important;
|
|
20
|
+
padding: 0 !important; margin: 0 !important; border-radius: 2px; cursor: pointer;
|
|
21
|
+
box-decoration-break: clone; -webkit-box-decoration-break: clone; }
|
|
22
|
+
mark.__rv.__rv-on { background: rgba(255, 150, 20, .7) !important;
|
|
23
|
+
box-shadow: 0 0 0 2px rgba(240, 120, 0, .9); }`;
|
|
24
|
+
(document.head || document.documentElement).appendChild(pageStyle);
|
|
25
|
+
|
|
26
|
+
const host = document.createElement("div");
|
|
27
|
+
host.id = "__review-host";
|
|
28
|
+
host.style.cssText = "all: initial; position: fixed; inset: 0 auto auto 0; width: 0; height: 0; z-index: 2147483647;";
|
|
29
|
+
document.documentElement.appendChild(host);
|
|
30
|
+
const root = host.attachShadow({ mode: "open" });
|
|
31
|
+
root.innerHTML = `
|
|
32
|
+
<style>
|
|
33
|
+
:host { --bg:#fff; --fg:#1d1d1f; --muted:#6e6e73; --line:#d9d9de; --accent:#2f6fde; --hl:#ffe08a; --danger:#c62828; }
|
|
34
|
+
@media (prefers-color-scheme: dark) {
|
|
35
|
+
:host { --bg:#1f1f22; --fg:#f2f2f4; --muted:#a1a1a8; --line:#3a3a40; --accent:#6ea0ff; --hl:#6b5a1e; --danger:#ff6b6b; }
|
|
36
|
+
}
|
|
37
|
+
* { box-sizing: border-box; font: 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; }
|
|
38
|
+
a { color: var(--accent); text-decoration: none; }
|
|
39
|
+
a:hover { text-decoration: underline; }
|
|
40
|
+
button { cursor: pointer; border: 1px solid var(--line); background: var(--bg); color: var(--fg);
|
|
41
|
+
border-radius: 6px; padding: 5px 10px; }
|
|
42
|
+
button:hover { border-color: var(--accent); }
|
|
43
|
+
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
|
44
|
+
button.danger { color: var(--danger); }
|
|
45
|
+
[hidden] { display: none !important; }
|
|
46
|
+
#add { position: fixed; padding: 4px 10px; font-weight: 600; box-shadow: 0 2px 10px rgba(0,0,0,.25); }
|
|
47
|
+
#editor { position: fixed; width: min(340px, calc(100vw - 16px)); background: var(--bg); color: var(--fg);
|
|
48
|
+
border: 1px solid var(--line); border-radius: 10px; padding: 12px; box-shadow: 0 8px 30px rgba(0,0,0,.3); z-index: 2; }
|
|
49
|
+
.quote { border-left: 3px solid var(--hl); padding: 2px 8px; color: var(--muted); max-height: 7.5em;
|
|
50
|
+
overflow: auto; white-space: pre-wrap; margin-bottom: 6px; }
|
|
51
|
+
.section { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .04em; margin-bottom: 6px; }
|
|
52
|
+
textarea { width: 100%; min-height: 90px; resize: vertical; background: var(--bg); color: var(--fg);
|
|
53
|
+
border: 1px solid var(--line); border-radius: 6px; padding: 6px 8px; }
|
|
54
|
+
textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
|
55
|
+
.row { display: flex; gap: 6px; margin-top: 8px; align-items: center; flex-wrap: wrap; }
|
|
56
|
+
.sp { flex: 1; }
|
|
57
|
+
.hint { color: var(--muted); font-size: 11px; }
|
|
58
|
+
#toggle { position: fixed; right: 16px; bottom: 16px; font-weight: 600; box-shadow: 0 2px 12px rgba(0,0,0,.25); }
|
|
59
|
+
#panel { position: fixed; top: 0; right: 0; bottom: 0; width: min(360px, 100vw); background: var(--bg); color: var(--fg);
|
|
60
|
+
border-left: 1px solid var(--line); box-shadow: -6px 0 24px rgba(0,0,0,.18); display: flex; flex-direction: column; z-index: 1; }
|
|
61
|
+
#panel header { display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid var(--line); }
|
|
62
|
+
#panel header b { font-size: 14px; flex: 1; }
|
|
63
|
+
.meta { padding: 8px 14px; color: var(--muted); font-size: 12px; border-bottom: 1px solid var(--line); display: flex; gap: 8px; }
|
|
64
|
+
.meta .status { flex: 1; }
|
|
65
|
+
.meta .err { color: var(--danger); }
|
|
66
|
+
ol { list-style: none; margin: 0; padding: 6px; overflow: auto; flex: 1; }
|
|
67
|
+
li { padding: 8px 10px; border-radius: 8px; cursor: pointer; border: 1px solid transparent; }
|
|
68
|
+
li:hover { border-color: var(--line); }
|
|
69
|
+
li.on { border-color: var(--accent); }
|
|
70
|
+
li .q { color: var(--muted); border-left: 3px solid var(--hl); padding-left: 6px; margin: 2px 0 4px;
|
|
71
|
+
display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
|
|
72
|
+
li .c { white-space: pre-wrap; }
|
|
73
|
+
li .c.empty { color: var(--muted); font-style: italic; }
|
|
74
|
+
.badge { font-size: 10px; color: var(--danger); border: 1px solid var(--danger); border-radius: 4px; padding: 0 4px; margin-left: 4px; }
|
|
75
|
+
.empty-list { color: var(--muted); padding: 14px; cursor: default; }
|
|
76
|
+
</style>
|
|
77
|
+
<button id="add" hidden>💬 Comment</button>
|
|
78
|
+
<div id="editor" hidden>
|
|
79
|
+
<div class="section"></div>
|
|
80
|
+
<div class="quote"></div>
|
|
81
|
+
<textarea placeholder="Comment (optional; a bare highlight is fine)"></textarea>
|
|
82
|
+
<div class="row">
|
|
83
|
+
<button class="danger del">Delete</button><span class="sp"></span>
|
|
84
|
+
<span class="hint">⌘↵ save · Esc cancel</span>
|
|
85
|
+
<button class="cancel">Cancel</button><button class="primary save">Save</button>
|
|
86
|
+
</div>
|
|
87
|
+
</div>
|
|
88
|
+
<button id="toggle">Notes · 0</button>
|
|
89
|
+
<aside id="panel" hidden>
|
|
90
|
+
<header><b>Review notes</b><button class="general">+ General note</button><button class="close" title="Close">✕</button></header>
|
|
91
|
+
<div class="meta"><span class="status"></span><a class="folder" href="./">Folder</a></div>
|
|
92
|
+
<ol></ol>
|
|
93
|
+
</aside>`;
|
|
94
|
+
|
|
95
|
+
const $ = (s) => root.querySelector(s);
|
|
96
|
+
const addBtn = $("#add"), ed = $("#editor"), ta = $("#editor textarea"), panel = $("#panel"), list = $("#panel ol");
|
|
97
|
+
|
|
98
|
+
// Keep the page's own keyboard shortcuts from firing while typing in our UI.
|
|
99
|
+
for (const t of ["keydown", "keyup", "keypress"]) host.addEventListener(t, (e) => e.stopPropagation());
|
|
100
|
+
const inHost = (e) => e.composedPath().includes(host);
|
|
101
|
+
|
|
102
|
+
// ---------- helpers ----------
|
|
103
|
+
const norm = (s) => s.replace(/\s+/g, " ").trim();
|
|
104
|
+
const newId = () => "n" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
|
105
|
+
const clean = (n) => Object.fromEntries(Object.entries(n).filter(([k]) => !k.startsWith("_")));
|
|
106
|
+
function nowIso() {
|
|
107
|
+
const d = new Date(), off = -d.getTimezoneOffset();
|
|
108
|
+
const p = (n) => String(Math.floor(Math.abs(n))).padStart(2, "0");
|
|
109
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}` +
|
|
110
|
+
`${off >= 0 ? "+" : "-"}${p(off / 60)}:${p(off % 60)}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Concatenated text of the document body plus where each text node starts in it.
|
|
114
|
+
function textMap() {
|
|
115
|
+
const nodes = [];
|
|
116
|
+
let text = "";
|
|
117
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
|
|
118
|
+
acceptNode(n) {
|
|
119
|
+
for (let p = n.parentNode; p && p !== document.body; p = p.parentNode)
|
|
120
|
+
if (SKIP.has(p.nodeName) || p.namespaceURI === SVG_NS) return NodeFilter.FILTER_REJECT;
|
|
121
|
+
return NodeFilter.FILTER_ACCEPT;
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
for (let n; (n = walker.nextNode()); ) { nodes.push({ node: n, start: text.length }); text += n.data; }
|
|
125
|
+
return { nodes, text };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function rangeToOffsets(range, map) {
|
|
129
|
+
let start = null, end = null;
|
|
130
|
+
for (const { node, start: s } of map.nodes) {
|
|
131
|
+
if (!range.intersectsNode(node)) continue;
|
|
132
|
+
const a = node === range.startContainer ? range.startOffset : 0;
|
|
133
|
+
const b = node === range.endContainer ? range.endOffset : node.data.length;
|
|
134
|
+
if (start === null) start = s + a;
|
|
135
|
+
end = s + b;
|
|
136
|
+
}
|
|
137
|
+
return start === null || end <= start ? null : { start, end };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function sectionFor(node) {
|
|
141
|
+
let best = null;
|
|
142
|
+
for (const h of document.body.querySelectorAll("h1,h2,h3,h4,h5,h6")) {
|
|
143
|
+
if (h.contains(node) || (h.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)) best = h;
|
|
144
|
+
else break;
|
|
145
|
+
}
|
|
146
|
+
return best ? norm(best.textContent).slice(0, 200) || null : null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const commonPrefix = (a, b) => { let i = 0; while (i < a.length && i < b.length && a[i] === b[i]) i++; return i; };
|
|
150
|
+
const commonSuffix = (a, b) => { let i = 0; while (i < a.length && i < b.length && a[a.length - 1 - i] === b[b.length - 1 - i]) i++; return i; };
|
|
151
|
+
|
|
152
|
+
// Find the occurrence of the quote whose surrounding text best matches what was saved.
|
|
153
|
+
function locate(anchor, map) {
|
|
154
|
+
const t = map.text, q = anchor.exact;
|
|
155
|
+
if (!q) return null;
|
|
156
|
+
let best = null, bestScore = -Infinity;
|
|
157
|
+
for (let i = t.indexOf(q); i !== -1; i = t.indexOf(q, i + 1)) {
|
|
158
|
+
const pre = t.slice(Math.max(0, i - (anchor.prefix || "").length), i);
|
|
159
|
+
const suf = t.slice(i + q.length, i + q.length + (anchor.suffix || "").length);
|
|
160
|
+
const score = commonSuffix(pre, anchor.prefix || "") + commonPrefix(suf, anchor.suffix || "") - Math.abs(i - (anchor.start ?? i)) / 1e7;
|
|
161
|
+
if (score > bestScore) { bestScore = score; best = i; }
|
|
162
|
+
}
|
|
163
|
+
return best === null ? null : { start: best, end: best + q.length };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function wrap(start, end, id, map) {
|
|
167
|
+
const marks = [];
|
|
168
|
+
for (const { node, start: s } of map.nodes) {
|
|
169
|
+
const e = s + node.data.length;
|
|
170
|
+
if (e <= start || s >= end) continue;
|
|
171
|
+
const a = Math.max(start, s) - s, b = Math.min(end, e) - s;
|
|
172
|
+
if (!node.data.slice(a, b).trim()) continue; // whitespace between block elements
|
|
173
|
+
let n = node;
|
|
174
|
+
if (b < n.data.length) n.splitText(b);
|
|
175
|
+
if (a > 0) n = n.splitText(a);
|
|
176
|
+
const m = document.createElement("mark");
|
|
177
|
+
m.className = "__rv";
|
|
178
|
+
m.dataset.rv = id;
|
|
179
|
+
n.parentNode.insertBefore(m, n);
|
|
180
|
+
m.appendChild(n);
|
|
181
|
+
marks.push(m);
|
|
182
|
+
}
|
|
183
|
+
return marks;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function clearMarks() {
|
|
187
|
+
const parents = new Set();
|
|
188
|
+
for (const m of document.querySelectorAll("mark.__rv")) {
|
|
189
|
+
const p = m.parentNode;
|
|
190
|
+
while (m.firstChild) p.insertBefore(m.firstChild, m);
|
|
191
|
+
p.removeChild(m);
|
|
192
|
+
parents.add(p);
|
|
193
|
+
}
|
|
194
|
+
for (const p of parents) if (p.isConnected) p.normalize();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function sortNotes() {
|
|
198
|
+
notes.sort((a, b) => {
|
|
199
|
+
if (!a.anchor !== !b.anchor) return a.anchor ? 1 : -1;
|
|
200
|
+
if (!a.anchor) return String(a.created_at).localeCompare(String(b.created_at));
|
|
201
|
+
return (a.anchor.start || 0) - (b.anchor.start || 0);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---------- rendering ----------
|
|
206
|
+
function render() {
|
|
207
|
+
clearMarks();
|
|
208
|
+
for (const n of notes) {
|
|
209
|
+
n._orphan = false;
|
|
210
|
+
if (!n.anchor) continue;
|
|
211
|
+
const map = textMap();
|
|
212
|
+
const loc = locate(n.anchor, map);
|
|
213
|
+
if (!loc || !wrap(loc.start, loc.end, n.id, map).length) n._orphan = true;
|
|
214
|
+
}
|
|
215
|
+
renderList();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function markActive() {
|
|
219
|
+
const id = editing && editing.note.id;
|
|
220
|
+
for (const m of document.querySelectorAll("mark.__rv")) m.classList.toggle("__rv-on", m.dataset.rv === id);
|
|
221
|
+
for (const li of list.children) li.classList.toggle("on", li.dataset.id === id);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function renderList() {
|
|
225
|
+
$("#toggle").textContent = `Notes · ${notes.length}`;
|
|
226
|
+
list.replaceChildren();
|
|
227
|
+
if (!notes.length) {
|
|
228
|
+
const li = document.createElement("li");
|
|
229
|
+
li.className = "empty-list";
|
|
230
|
+
li.textContent = "Select text in the document, then click “Comment”.";
|
|
231
|
+
list.append(li);
|
|
232
|
+
}
|
|
233
|
+
for (const n of notes) {
|
|
234
|
+
const li = document.createElement("li");
|
|
235
|
+
li.dataset.id = n.id;
|
|
236
|
+
const sec = document.createElement("div");
|
|
237
|
+
sec.className = "section";
|
|
238
|
+
sec.textContent = n.anchor ? (n.section || "—") : "General";
|
|
239
|
+
if (n._orphan) { const b = document.createElement("span"); b.className = "badge"; b.textContent = "not found"; sec.append(b); }
|
|
240
|
+
li.append(sec);
|
|
241
|
+
if (n.quote) { const q = document.createElement("div"); q.className = "q"; q.textContent = n.quote; li.append(q); }
|
|
242
|
+
const c = document.createElement("div");
|
|
243
|
+
c.className = "c" + (n.comment ? "" : " empty");
|
|
244
|
+
c.textContent = n.comment || "highlight only";
|
|
245
|
+
li.append(c);
|
|
246
|
+
li.addEventListener("click", () => focusNote(n));
|
|
247
|
+
list.append(li);
|
|
248
|
+
}
|
|
249
|
+
markActive();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function setStatus(msg, err = false) {
|
|
253
|
+
const s = $(".meta .status");
|
|
254
|
+
s.className = "status" + (err ? " err" : "");
|
|
255
|
+
s.textContent = msg;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ---------- persistence: one request per note, applied server-side under a lock ----------
|
|
259
|
+
let chain = Promise.resolve();
|
|
260
|
+
function send(method, path, body) {
|
|
261
|
+
setStatus("Saving…");
|
|
262
|
+
chain = chain
|
|
263
|
+
.then(() => fetch(`${API}${path}?doc=${DOC}`, {
|
|
264
|
+
method, headers: body ? { "Content-Type": "application/json" } : {}, body: body && JSON.stringify(body),
|
|
265
|
+
}))
|
|
266
|
+
.then(async (r) => {
|
|
267
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
268
|
+
const data = await r.json();
|
|
269
|
+
setStatus(`Saved to ${data.notes_file} at ${new Date().toLocaleTimeString()}`);
|
|
270
|
+
// Pick up notes other reviewers added, unless we're mid-edit.
|
|
271
|
+
if (!editing && Array.isArray(data.notes)) { notes = data.notes; sortNotes(); render(); }
|
|
272
|
+
})
|
|
273
|
+
.catch((e) => setStatus(`Save failed (${e.message}). Is the server still running?`, true));
|
|
274
|
+
}
|
|
275
|
+
const saveNote = (n) => send("PUT", "", clean(n));
|
|
276
|
+
const deleteNote = (n) => send("DELETE", `/${encodeURIComponent(n.id)}`);
|
|
277
|
+
|
|
278
|
+
// ---------- editor ----------
|
|
279
|
+
function place(rect) {
|
|
280
|
+
const W = ed.offsetWidth || 340, H = ed.offsetHeight || 230;
|
|
281
|
+
if (!rect) { ed.style.left = `${(innerWidth - W) / 2}px`; ed.style.top = `${Math.max(8, (innerHeight - H) / 3)}px`; return; }
|
|
282
|
+
const left = Math.min(Math.max(8, rect.left), innerWidth - W - 8);
|
|
283
|
+
let top = rect.bottom + 8;
|
|
284
|
+
if (top + H > innerHeight - 8) top = Math.max(8, rect.top - H - 8);
|
|
285
|
+
ed.style.left = `${left}px`;
|
|
286
|
+
ed.style.top = `${top}px`;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function openEditor(note, isNew, rect) {
|
|
290
|
+
editing = { note, isNew };
|
|
291
|
+
$("#editor .section").textContent = note.anchor ? (note.section || "") : "General note";
|
|
292
|
+
const q = $("#editor .quote");
|
|
293
|
+
q.textContent = note.quote || "";
|
|
294
|
+
q.hidden = !note.quote;
|
|
295
|
+
ta.value = note.comment || "";
|
|
296
|
+
$("#editor .del").hidden = isNew;
|
|
297
|
+
ed.hidden = false;
|
|
298
|
+
place(rect);
|
|
299
|
+
markActive();
|
|
300
|
+
ta.focus();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function closeEditor() { editing = null; ed.hidden = true; markActive(); }
|
|
304
|
+
|
|
305
|
+
function save() {
|
|
306
|
+
const { note, isNew } = editing;
|
|
307
|
+
const comment = ta.value.trim();
|
|
308
|
+
closeEditor();
|
|
309
|
+
if (!isNew && comment === (note.comment || "")) return;
|
|
310
|
+
note.comment = comment;
|
|
311
|
+
note.updated_at = nowIso();
|
|
312
|
+
renderList();
|
|
313
|
+
saveNote(note);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function cancel() {
|
|
317
|
+
if (!editing) return;
|
|
318
|
+
const { note, isNew } = editing;
|
|
319
|
+
closeEditor();
|
|
320
|
+
if (isNew) { notes = notes.filter((n) => n !== note); render(); }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function remove() {
|
|
324
|
+
const { note } = editing;
|
|
325
|
+
if (!confirm("Delete this note?")) return;
|
|
326
|
+
notes = notes.filter((n) => n !== note);
|
|
327
|
+
closeEditor();
|
|
328
|
+
render();
|
|
329
|
+
deleteNote(note);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function focusNote(n) {
|
|
333
|
+
const m = document.querySelector(`mark.__rv[data-rv="${CSS.escape(n.id)}"]`);
|
|
334
|
+
if (m) { m.scrollIntoView({ block: "center" }); openEditor(n, false, m.getBoundingClientRect()); }
|
|
335
|
+
else openEditor(n, false, null);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
$("#editor .save").addEventListener("click", save);
|
|
339
|
+
$("#editor .cancel").addEventListener("click", cancel);
|
|
340
|
+
$("#editor .del").addEventListener("click", remove);
|
|
341
|
+
ta.addEventListener("keydown", (e) => {
|
|
342
|
+
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); save(); }
|
|
343
|
+
else if (e.key === "Escape") { e.preventDefault(); cancel(); }
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
// ---------- selection -> Comment button ----------
|
|
347
|
+
function hideAdd() { addBtn.hidden = true; pending = null; }
|
|
348
|
+
|
|
349
|
+
function checkSelection() {
|
|
350
|
+
const sel = document.getSelection();
|
|
351
|
+
if (!sel || !sel.rangeCount || sel.isCollapsed) return hideAdd();
|
|
352
|
+
const range = sel.getRangeAt(0);
|
|
353
|
+
if (!document.body.contains(range.commonAncestorContainer)) return hideAdd();
|
|
354
|
+
const map = textMap();
|
|
355
|
+
const off = rangeToOffsets(range, map);
|
|
356
|
+
if (!off) return hideAdd();
|
|
357
|
+
while (off.start < off.end && /\s/.test(map.text[off.start])) off.start++;
|
|
358
|
+
while (off.end > off.start && /\s/.test(map.text[off.end - 1])) off.end--;
|
|
359
|
+
if (off.end <= off.start) return hideAdd();
|
|
360
|
+
const rects = range.getClientRects();
|
|
361
|
+
const last = rects.length ? rects[rects.length - 1] : range.getBoundingClientRect();
|
|
362
|
+
pending = { ...off, text: map.text, node: range.startContainer, rect: range.getBoundingClientRect() };
|
|
363
|
+
addBtn.hidden = false;
|
|
364
|
+
addBtn.style.left = `${Math.min(Math.max(8, last.right - 40), innerWidth - 120)}px`;
|
|
365
|
+
addBtn.style.top = `${Math.min(last.bottom + 6, innerHeight - 40)}px`;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
document.addEventListener("mouseup", (e) => { if (!inHost(e)) setTimeout(checkSelection, 0); });
|
|
369
|
+
document.addEventListener("keyup", (e) => { if (!inHost(e) && (e.shiftKey || e.key === "Shift")) setTimeout(checkSelection, 0); });
|
|
370
|
+
document.addEventListener("scroll", () => { if (!addBtn.hidden) checkSelection(); }, { passive: true, capture: true });
|
|
371
|
+
|
|
372
|
+
addBtn.addEventListener("mousedown", (e) => e.preventDefault());
|
|
373
|
+
addBtn.addEventListener("click", () => {
|
|
374
|
+
const p = pending;
|
|
375
|
+
if (!p) return;
|
|
376
|
+
const exact = p.text.slice(p.start, p.end);
|
|
377
|
+
const t = nowIso();
|
|
378
|
+
const note = {
|
|
379
|
+
id: newId(), quote: norm(exact), section: sectionFor(p.node), comment: "", created_at: t, updated_at: t,
|
|
380
|
+
anchor: { exact, prefix: p.text.slice(Math.max(0, p.start - CTX), p.start), suffix: p.text.slice(p.end, p.end + CTX), start: p.start },
|
|
381
|
+
};
|
|
382
|
+
hideAdd();
|
|
383
|
+
document.getSelection().removeAllRanges();
|
|
384
|
+
notes.push(note);
|
|
385
|
+
sortNotes();
|
|
386
|
+
render();
|
|
387
|
+
openEditor(note, true, p.rect);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
// Click a highlight to open its note.
|
|
391
|
+
document.addEventListener("click", (e) => {
|
|
392
|
+
if (inHost(e)) return;
|
|
393
|
+
const m = e.target.closest && e.target.closest("mark.__rv");
|
|
394
|
+
const sel = document.getSelection();
|
|
395
|
+
if (!m || (sel && !sel.isCollapsed)) return;
|
|
396
|
+
const n = notes.find((x) => x.id === m.dataset.rv);
|
|
397
|
+
if (n) { e.preventDefault(); openEditor(n, false, m.getBoundingClientRect()); }
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
document.addEventListener("keydown", (e) => {
|
|
401
|
+
if (e.key !== "Escape") return;
|
|
402
|
+
if (editing) cancel(); else hideAdd();
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// ---------- panel ----------
|
|
406
|
+
$("#toggle").addEventListener("click", () => { panel.hidden = !panel.hidden; });
|
|
407
|
+
$("#panel .close").addEventListener("click", () => { panel.hidden = true; });
|
|
408
|
+
$("#panel .general").addEventListener("click", () => {
|
|
409
|
+
const t = nowIso();
|
|
410
|
+
const note = { id: newId(), quote: null, section: null, comment: "", created_at: t, updated_at: t, anchor: null };
|
|
411
|
+
notes.push(note);
|
|
412
|
+
sortNotes();
|
|
413
|
+
renderList();
|
|
414
|
+
openEditor(note, true, null);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
// ---------- boot: wait for math and diagrams to render so highlights anchor on final text ----------
|
|
418
|
+
async function boot() {
|
|
419
|
+
const waits = Array.isArray(window.__reviewWait) ? window.__reviewWait : [];
|
|
420
|
+
await Promise.race([Promise.allSettled(waits), new Promise((r) => setTimeout(r, 10000))]);
|
|
421
|
+
try {
|
|
422
|
+
const r = await fetch(`${API}?doc=${DOC}`, { cache: "no-store" });
|
|
423
|
+
const data = await r.json();
|
|
424
|
+
if (!r.ok) throw new Error(data.detail || `HTTP ${r.status}`);
|
|
425
|
+
notes = Array.isArray(data.notes) ? data.notes : [];
|
|
426
|
+
notesFile = data.notes_file;
|
|
427
|
+
setStatus(notes.length ? `Loaded ${notes.length} note(s) from ${notesFile}` : `Notes save to ${notesFile}`);
|
|
428
|
+
} catch (e) {
|
|
429
|
+
setStatus(`Couldn't load notes (${e.message})`, true);
|
|
430
|
+
}
|
|
431
|
+
sortNotes();
|
|
432
|
+
render();
|
|
433
|
+
}
|
|
434
|
+
if (document.readyState === "complete") boot(); else window.addEventListener("load", boot);
|
|
435
|
+
})();
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: margin-notes
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Review HTML and Markdown in your browser: highlight passages, comment, and save the notes as JSON beside each document.
|
|
5
|
+
Project-URL: Homepage, https://github.com/jbn/margin-notes
|
|
6
|
+
Project-URL: Repository, https://github.com/jbn/margin-notes
|
|
7
|
+
Project-URL: Issues, https://github.com/jbn/margin-notes/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/jbn/margin-notes/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: John B Nelson <jbn@abreka.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: annotation,comments,highlight,html,markdown,mathjax,mermaid,review
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Environment :: Web Environment
|
|
15
|
+
Classifier: Framework :: FastAPI
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Intended Audience :: Science/Research
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
26
|
+
Classifier: Topic :: Documentation
|
|
27
|
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
|
28
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
29
|
+
Classifier: Typing :: Typed
|
|
30
|
+
Requires-Python: >=3.10
|
|
31
|
+
Requires-Dist: fastapi>=0.110
|
|
32
|
+
Requires-Dist: linkify-it-py>=2.0
|
|
33
|
+
Requires-Dist: markdown-it-py>=3.0
|
|
34
|
+
Requires-Dist: mdit-py-plugins>=0.4
|
|
35
|
+
Requires-Dist: pygments>=2.14
|
|
36
|
+
Requires-Dist: uvicorn>=0.29
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# margin-notes
|
|
40
|
+
|
|
41
|
+
[](https://github.com/jbn/margin-notes/actions/workflows/ci.yml)
|
|
42
|
+
[](https://pypi.org/project/margin-notes/)
|
|
43
|
+
[](https://pypi.org/project/margin-notes/)
|
|
44
|
+
[](https://github.com/jbn/margin-notes/blob/main/LICENSE)
|
|
45
|
+
|
|
46
|
+
Review HTML and Markdown documents in your browser. Select a passage, leave a comment, and the
|
|
47
|
+
notes save as JSON next to the document, ready for a person or an LLM agent to act on.
|
|
48
|
+
|
|
49
|
+

|
|
50
|
+
|
|
51
|
+
It replaces `python -m http.server` when the reason you're serving a folder is to read and
|
|
52
|
+
critique what's in it.
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
uvx margin-notes # browse the current folder
|
|
56
|
+
uvx margin-notes docs/design.md # open one document
|
|
57
|
+
uvx margin-notes ~/reports --host 0.0.0.0 --port 9000
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## What it does
|
|
61
|
+
|
|
62
|
+
- **Any folder.** A listing shows Markdown and HTML documents first, with a count of the notes on each.
|
|
63
|
+
Other files (images, PDFs, data) are served as-is, so relative links and images work.
|
|
64
|
+
- **HTML** is served unchanged with a small review overlay added. Its own scripts and styles still run.
|
|
65
|
+
- **Markdown** is rendered GitHub-style: tables, task lists, footnotes, definition lists, heading
|
|
66
|
+
anchors, front matter (`title:` becomes the page title), alerts (`> [!NOTE]`, `[!TIP]`,
|
|
67
|
+
`[!IMPORTANT]`, `[!WARNING]`, `[!CAUTION]`), Pygments syntax highlighting, light and dark themes.
|
|
68
|
+
- **Math** with MathJax: `$inline$`, `$$display$$` and ```` ```math ```` fences. MathJax only
|
|
69
|
+
loads on pages that contain math, so prices like `$5 and $10` are left alone.
|
|
70
|
+
- **Diagrams** in ```` ```mermaid ```` fences.
|
|
71
|
+
- Add `?raw=1` to any document URL to get the source.
|
|
72
|
+
- **Reviewing:** select text and click **💬 Comment**. ⌘↵ saves and Esc cancels. Click a highlight to
|
|
73
|
+
edit or delete it. **Notes** (bottom right) lists every note in document order and has
|
|
74
|
+
**+ General note** for comments about the whole document. Every change saves immediately.
|
|
75
|
+
|
|
76
|
+
MathJax and mermaid load from jsDelivr, so math and diagrams need internet access. Everything
|
|
77
|
+
else works offline.
|
|
78
|
+
|
|
79
|
+
## The notes file
|
|
80
|
+
|
|
81
|
+
`report.md` gets `report.md.notes.json` beside it. Using the full filename keeps `report.md` and
|
|
82
|
+
`report.html` in one folder from sharing a file.
|
|
83
|
+
|
|
84
|
+
```json
|
|
85
|
+
{
|
|
86
|
+
"about": "Review notes on report.md. Notes are in document order. ...",
|
|
87
|
+
"document": "report.md",
|
|
88
|
+
"document_path": "/abs/path/report.md",
|
|
89
|
+
"document_sha256": "…",
|
|
90
|
+
"updated_at": "2026-11-17T13:43:20-08:00",
|
|
91
|
+
"notes": [
|
|
92
|
+
{
|
|
93
|
+
"id": "nmwl7ygt5zh7r",
|
|
94
|
+
"quote": "links five constants",
|
|
95
|
+
"section": "Euler and friends",
|
|
96
|
+
"comment": "which five?",
|
|
97
|
+
"created_at": "2026-11-17T13:43:19-08:00",
|
|
98
|
+
"updated_at": "2026-11-17T13:43:20-08:00",
|
|
99
|
+
"anchor": { "exact": "links five constants", "prefix": "…", "suffix": "…", "start": 35 }
|
|
100
|
+
}
|
|
101
|
+
]
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
- `quote` is the highlighted text and `section` is the nearest heading above it. A note with a
|
|
106
|
+
null `quote` is a general comment.
|
|
107
|
+
- `anchor` re-finds the highlight using the exact text and its surroundings. A highlight whose
|
|
108
|
+
text has since been edited out shows as **not found** in the notes panel.
|
|
109
|
+
- `about` describes the format in plain words, so an agent handed the file needs no other
|
|
110
|
+
instructions.
|
|
111
|
+
- If `document_sha256` no longer matches the file, the document changed after the review.
|
|
112
|
+
- Deleting the last note removes the file.
|
|
113
|
+
|
|
114
|
+
Several people can review the same document at once. Each save changes one note on the server,
|
|
115
|
+
so reviewers don't overwrite each other.
|
|
116
|
+
|
|
117
|
+
## Options
|
|
118
|
+
|
|
119
|
+
```
|
|
120
|
+
margin-notes [PATH] [--host HOST] [-p PORT] [--no-open] [--version]
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
| Option | Default | |
|
|
124
|
+
|---|---|---|
|
|
125
|
+
| `PATH` | `.` | A folder to browse, or a document to open |
|
|
126
|
+
| `--host` | `127.0.0.1` | `0.0.0.0` makes it reachable from your network |
|
|
127
|
+
| `-p`, `--port` | `8765` | The first port to try; it moves up if that one is busy |
|
|
128
|
+
| `--no-open` | | Don't open a browser |
|
|
129
|
+
|
|
130
|
+
**Security:** there is no authentication. Bound to anything other than localhost, anyone who can
|
|
131
|
+
reach the port can read every file under the folder and add notes. Dotfiles and dot-directories
|
|
132
|
+
(`.git`, `.env`) are never served, and nothing outside the folder is reachable, including
|
|
133
|
+
through symlinks.
|
|
134
|
+
|
|
135
|
+
## Development
|
|
136
|
+
|
|
137
|
+
```sh
|
|
138
|
+
uv sync --all-groups
|
|
139
|
+
uv run pytest # unit tests, plus browser tests when Playwright has a browser
|
|
140
|
+
uv run playwright install chromium # once, if you have no Chrome or Chromium
|
|
141
|
+
uv run pytest -m "not browser" # skip the browser tests
|
|
142
|
+
uv run ruff check && uv run ruff format --check
|
|
143
|
+
uv run margin-notes . # try it on this repository
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The browser tests (`tests/test_browser.py`) drive the overlay in Chromium through Playwright:
|
|
147
|
+
selecting text, anchoring repeated phrases, editing, deleting, general notes, and highlights
|
|
148
|
+
that no longer match. They need no network.
|
|
149
|
+
|
|
150
|
+
### Releasing
|
|
151
|
+
|
|
152
|
+
0. Optional dry run: run the **Release** workflow by hand from the Actions tab. It builds and
|
|
153
|
+
publishes to [TestPyPI](https://test.pypi.org/project/margin-notes/). Check the page, then
|
|
154
|
+
run the uploaded wheel. Only the wheel comes from TestPyPI; its dependencies come from PyPI,
|
|
155
|
+
because TestPyPI holds unrelated packages under real names (such as a broken `fastapi 1.0`):
|
|
156
|
+
|
|
157
|
+
```sh
|
|
158
|
+
uvx --refresh --from "margin-notes @ $(curl -s https://test.pypi.org/pypi/margin-notes/json \
|
|
159
|
+
| python3 -c 'import json,sys; print(next(u["url"] for u in json.load(sys.stdin)["urls"] if u["filename"].endswith(".whl")))')" \
|
|
160
|
+
margin-notes --version
|
|
161
|
+
```
|
|
162
|
+
1. Bump `__version__` in `src/margin_notes/__init__.py` and add a section to `CHANGELOG.md`.
|
|
163
|
+
2. Commit, then tag and push: `git tag v0.1.0 && git push --tags`.
|
|
164
|
+
3. `.github/workflows/release.yml` checks that the tag matches the version, runs the tests,
|
|
165
|
+
builds, and publishes to PyPI.
|
|
166
|
+
|
|
167
|
+
Both indexes publish through trusted publishers, so no token lives in GitHub. Set each up once,
|
|
168
|
+
for repository `jbn/margin-notes` and workflow `release.yml`: at
|
|
169
|
+
<https://test.pypi.org/manage/account/publishing/> with environment `testpypi`, and at
|
|
170
|
+
<https://pypi.org/manage/account/publishing/> with environment `pypi`.
|
|
171
|
+
|
|
172
|
+
To publish from your own machine instead, run `uv build && uv publish`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
margin_notes/__init__.py,sha256=xScGeGmZYPwiUz7dfWUH9eZ4nsAmKnMR4lHgaqwBwCw,119
|
|
2
|
+
margin_notes/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
|
3
|
+
margin_notes/cli.py,sha256=5Jh-U5R7P5n9ySGcbnXIgi7IY-m6M6l-N7doDYhJ9yM,3763
|
|
4
|
+
margin_notes/notes.py,sha256=hUCSBFf5GoxB7gb9paf9wDGTU8-6lX3HbSUZCjsooNY,3885
|
|
5
|
+
margin_notes/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
margin_notes/render.py,sha256=GitpkNx_F2kAYORuKxjTHoui14klxcTeavsVQm7yCw4,5445
|
|
7
|
+
margin_notes/server.py,sha256=bg8Zht8W9bhXQ8qpooT49Al5cmhV55e0lWgBOp9n7AA,6075
|
|
8
|
+
margin_notes/static/page.css,sha256=_4hqS0izWAsWm4UVimLaMELJMhAqMot5oREpOldKgdI,5863
|
|
9
|
+
margin_notes/static/review.js,sha256=QWajXPTYn8l8GHoBezuZGLX7I_Rs5HlW3V6svGYwyJg,19907
|
|
10
|
+
margin_notes-0.1.0.dist-info/METADATA,sha256=T93J8IJ2umfqXx1D-qC1Xj8-TwEvJhwaPCQG77_BYGg,8283
|
|
11
|
+
margin_notes-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
margin_notes-0.1.0.dist-info/entry_points.txt,sha256=uuXdz4c7QBtjgG8XAJh-uRfdf3FwMDLmolV9VR9zVqo,55
|
|
13
|
+
margin_notes-0.1.0.dist-info/licenses/LICENSE,sha256=vuiei7c-4OdQIhp8N7kxSiOPbT3YJVh0qpHZB4fKaUk,1070
|
|
14
|
+
margin_notes-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 John B Nelson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|