Compare commits
2 Commits
6aadbaaf0c
...
837ce735aa
Author | SHA1 | Date |
---|---|---|
Tim Van Baak | 837ce735aa | |
Tim Van Baak | 241ec45430 |
|
@ -2,6 +2,9 @@
|
||||||
Article query interface
|
Article query interface
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
from amanuensis.db import *
|
from amanuensis.db import *
|
||||||
|
@ -42,3 +45,10 @@ def create(
|
||||||
db.session.add(new_article)
|
db.session.add(new_article)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return new_article
|
return new_article
|
||||||
|
|
||||||
|
|
||||||
|
def try_from_public_id(db: DbContext, public_id: UUID) -> Optional[Article]:
|
||||||
|
"""Get an article by its public id."""
|
||||||
|
return db(
|
||||||
|
select(Article).where(Article.public_id == public_id)
|
||||||
|
).scalar_one_or_none()
|
||||||
|
|
|
@ -4,7 +4,6 @@ html, body {
|
||||||
margin: 0px;
|
margin: 0px;
|
||||||
}
|
}
|
||||||
div#wrapper {
|
div#wrapper {
|
||||||
max-width: 1128px;
|
|
||||||
height: 100%;
|
height: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
|
|
|
@ -1,126 +1,154 @@
|
||||||
// Reduce unnecessary requests by checking for no further changes being made
|
(function(){
|
||||||
// before updating in response to a change.
|
/** Article submission state. */
|
||||||
var nonce = 0;
|
const ArticleState = {
|
||||||
|
DRAFT: 0,
|
||||||
|
SUBMITTED: 1,
|
||||||
|
APPROVED: 2
|
||||||
|
};
|
||||||
|
|
||||||
function ifNoFurtherChanges(callback, timeout=2000) {
|
/** Article state to be tracked in addition to the editable content. */
|
||||||
var nonce_local = Math.random();
|
var article = {
|
||||||
|
state: undefined,
|
||||||
|
ersatz: false
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Article content as last received from the server. */
|
||||||
|
var preview = {
|
||||||
|
title: undefined,
|
||||||
|
rendered: undefined,
|
||||||
|
citations: [],
|
||||||
|
errors: []
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The nonce of the last-made update request. */
|
||||||
|
let nonce = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update request debounce wrapper that executes the callback if no further
|
||||||
|
* calls are made during the timeout period. If a new call is made, any
|
||||||
|
* previous calls are skipped.
|
||||||
|
*/
|
||||||
|
function ifNoFurtherChanges(callback, timeout)
|
||||||
|
{
|
||||||
|
// Stake a claim on the nonce, potentially overwriting a previous
|
||||||
|
// nonce value.
|
||||||
|
const nonce_local = 1 + Math.random();
|
||||||
|
console.log("ifNoFurtherChanges: timeout=" + timeout.toString() + ", nonce=" + nonce_local.toString());
|
||||||
nonce = nonce_local;
|
nonce = nonce_local;
|
||||||
|
// Wait to see if this call is overwritten in turn.
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (nonce == nonce_local) {
|
if (nonce == nonce_local)
|
||||||
|
{
|
||||||
|
console.log("Executing for: " + nonce.toString());
|
||||||
callback();
|
callback();
|
||||||
nonce = 0;
|
nonce = 0;
|
||||||
}
|
}
|
||||||
}, timeout);
|
}, timeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read data out of params and initialize editor
|
/** Update the editor controls and preview to match the current state. */
|
||||||
window.onload = function() {
|
function refreshEditor()
|
||||||
// Kill noscript message first
|
{
|
||||||
document.getElementById("preview").innerHTML = "<p> </p>";
|
// Enable or disable controls
|
||||||
|
const isEditable = article.state == ArticleState.DRAFT;
|
||||||
|
const blocked = preview.errors.filter(err => err.severity == 2).length > 0;
|
||||||
|
document.getElementById("editor-title").disabled = !isEditable;
|
||||||
|
document.getElementById("editor-content").disabled = !isEditable;
|
||||||
|
document.getElementById("button-submit").innerText = isEditable ? "Submit article" : "Edit article";
|
||||||
|
document.getElementById("button-submit").disabled = blocked;
|
||||||
|
|
||||||
if (document.body.contains(document.getElementById("editor-content"))) {
|
// Update the preview
|
||||||
onContentChange(0);
|
const previewHtml = "<h1>" + preview.title + "</h1>\n" + preview.rendered;
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
function buildArticleObject() {
|
|
||||||
var title = document.getElementById("editor-title").value;
|
|
||||||
var contents = document.getElementById("editor-content").value;
|
|
||||||
return {
|
|
||||||
aid: params.article.aid,
|
|
||||||
title: title,
|
|
||||||
status: params.article.status,
|
|
||||||
contents: contents
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function update(article) {
|
|
||||||
var req = new XMLHttpRequest();
|
|
||||||
req.open("POST", params.updateURL, true);
|
|
||||||
req.setRequestHeader("Content-type", "application/json");
|
|
||||||
req.responseType = "json";
|
|
||||||
req.onreadystatechange = function () {
|
|
||||||
if (req.readyState == 4 && req.status == 200) {
|
|
||||||
// Update internal state with the returned article object
|
|
||||||
params.status = req.response.status;
|
|
||||||
params.errors = req.response.error.length;
|
|
||||||
document.getElementById("editor-title").value = req.response.title;
|
|
||||||
// Set editor editability based on article status
|
|
||||||
updateEditorStatus();
|
|
||||||
// Update the preview with the parse information
|
|
||||||
updatePreview(req.response);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
var payload = { article: article };
|
|
||||||
req.send(JSON.stringify(payload));
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateEditorStatus() {
|
|
||||||
var ready = !!params.status.ready || !!params.status.approved;
|
|
||||||
document.getElementById("editor-title").disabled = ready;
|
|
||||||
document.getElementById("editor-content").disabled = ready;
|
|
||||||
var hasErrors = params.errors > 0;
|
|
||||||
var submitButton = document.getElementById("button-submit");
|
|
||||||
submitButton.innerText = ready ? "Edit article" : "Submit article";
|
|
||||||
submitButton.disabled = hasErrors;
|
|
||||||
}
|
|
||||||
|
|
||||||
function updatePreview(response) {
|
|
||||||
var previewHtml = "<h1>" + response.title + "</h1>\n" + response.rendered;
|
|
||||||
document.getElementById("preview").innerHTML = previewHtml;
|
document.getElementById("preview").innerHTML = previewHtml;
|
||||||
|
|
||||||
var citations = "<ol>";
|
// Fill in the citation block
|
||||||
for (var i = 0; i < response.citations.length; i++) {
|
let citations = "<ol>";
|
||||||
citations += "<li>" + response.citations[i] + "</li>";
|
preview.citations.forEach(cit => citations += "<li>" + JSON.stringify(cit) + "</li>");
|
||||||
}
|
|
||||||
citations += "</ol>";
|
citations += "</ol>";
|
||||||
document.getElementById("preview-citations").innerHTML = citations;
|
document.getElementById("preview-citations").innerHTML = citations;
|
||||||
|
|
||||||
var info = "";
|
// Fill in the status message block
|
||||||
for (var i = 0; i < response.info.length; i++) {
|
let statuses = "<ol>";
|
||||||
info += "<span class=\"message-info\">" + response.info[i] + "</span><br>";
|
preview.errors.forEach(err => statuses += "<li>" + JSON.stringify(err) + "</li>");
|
||||||
}
|
statuses += "<ol>";
|
||||||
var warning = "";
|
document.getElementById("preview-control").innerHTML = statuses;
|
||||||
for (var i = 0; i < response.warning.length; i++) {
|
|
||||||
warning += "<span class=\"message-warning\">" +
|
|
||||||
response.warning[i] + "</span><br>";
|
|
||||||
}
|
|
||||||
var error = "";
|
|
||||||
for (var i = 0; i < response.error.length; i++) {
|
|
||||||
error += "<span class=\"message-error\">" + response.error[i] + "</span><br>";
|
|
||||||
}
|
|
||||||
var control = info + warning + error;
|
|
||||||
document.getElementById("preview-control").innerHTML = control;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onContentChange(timeout=2000) {
|
/** Update the current state with the given data and refresh the editor. */
|
||||||
|
function updateState(data)
|
||||||
|
{
|
||||||
|
article.state = data.state;
|
||||||
|
article.ersatz = data.ersatz;
|
||||||
|
preview.title = data.title;
|
||||||
|
preview.rendered = data.rendered;
|
||||||
|
preview.citations = data.citations;
|
||||||
|
preview.errors = data.errors;
|
||||||
|
refreshEditor();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Send the article's current content to the server. */
|
||||||
|
function update()
|
||||||
|
{
|
||||||
|
const updateUrl = document.body.dataset.amanuensisUpdateUrl;
|
||||||
|
const data = {
|
||||||
|
title: document.getElementById("editor-title").value,
|
||||||
|
body: document.getElementById("editor-content").value,
|
||||||
|
state: article.state
|
||||||
|
};
|
||||||
|
fetch(updateUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
}).then(response => response.json()).then(updateState);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onContentChange(e, timeout=2000)
|
||||||
|
{
|
||||||
|
ifNoFurtherChanges(update, timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitArticle()
|
||||||
|
{
|
||||||
ifNoFurtherChanges(() => {
|
ifNoFurtherChanges(() => {
|
||||||
var article = buildArticleObject();
|
article.state = ArticleState.SUBMITTED;
|
||||||
update(article);
|
update();
|
||||||
}, timeout);
|
},
|
||||||
|
/* timeout: */ 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
function submitArticle() {
|
/** Initialize the editor on page load. */
|
||||||
ifNoFurtherChanges(() => {
|
function initializeEditor()
|
||||||
params.article.status.ready = !params.article.status.ready;
|
{
|
||||||
var article = buildArticleObject();
|
// Kill the noscript message
|
||||||
update(article);
|
document.getElementById("preview").innerHTML = "<p>Loading...</p>";
|
||||||
}, 0);
|
document.getElementById("preview-citations").innerHTML = "<p>Loading...</p>";
|
||||||
}
|
document.getElementById("preview-control").innerHTML = "<p>Loading...</p>";
|
||||||
|
|
||||||
window.addEventListener("beforeunload", function(e) {
|
// Hook up the controls
|
||||||
if (nonce != 0) {
|
document.getElementById("button-submit").onclick = submitArticle;
|
||||||
|
document.getElementById("editor-title").oninput = onContentChange;
|
||||||
|
document.getElementById("editor-content").oninput = onContentChange;
|
||||||
|
window.addEventListener("beforeunload", e =>
|
||||||
|
{
|
||||||
|
if (nonce > 0)
|
||||||
|
{
|
||||||
e.returnValue = "Are you sure?";
|
e.returnValue = "Are you sure?";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
window.addEventListener("keydown", e =>
|
||||||
window.addEventListener("keydown", function(event) {
|
|
||||||
if (event.ctrlKey || event.metaKey)
|
|
||||||
{
|
{
|
||||||
if (String.fromCharCode(event.which).toLowerCase() == 's')
|
if (e.ctrlKey && e.key == 's')
|
||||||
{
|
{
|
||||||
event.preventDefault();
|
e.preventDefault();
|
||||||
onContentChange(0);
|
onContentChange(e, 0);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Get the article status information.
|
||||||
|
const updateUrl = document.body.dataset.amanuensisUpdateUrl;
|
||||||
|
fetch(updateUrl).then(response => response.json()).then(updateState);
|
||||||
|
}
|
||||||
|
window.onload = initializeEditor;
|
||||||
|
})();
|
||||||
|
|
|
@ -15,6 +15,9 @@
|
||||||
{% if current_page == "contents" %}class="current-page"
|
{% if current_page == "contents" %}class="current-page"
|
||||||
{% else %}href="{{ url_for('lexicon.contents', lexicon_name=g.lexicon.name) }}"
|
{% else %}href="{{ url_for('lexicon.contents', lexicon_name=g.lexicon.name) }}"
|
||||||
{% endif %}>Contents</a>{% endblock %}
|
{% endif %}>Contents</a>{% endblock %}
|
||||||
|
{% block sb_editor %}<a
|
||||||
|
href="{{ url_for('lexicon.editor.select', lexicon_name=g.lexicon.name) }}"
|
||||||
|
>Editor</a>{% endblock %}
|
||||||
{% block sb_posts %}<a
|
{% block sb_posts %}<a
|
||||||
{% if current_page == "posts" %}class="current-page"
|
{% if current_page == "posts" %}class="current-page"
|
||||||
{% else %}href="{{ url_for('lexicon.posts.list', lexicon_name=g.lexicon.name) }}"
|
{% else %}href="{{ url_for('lexicon.posts.list', lexicon_name=g.lexicon.name) }}"
|
||||||
|
@ -35,6 +38,7 @@
|
||||||
{% set template_sidebar_rows = [
|
{% set template_sidebar_rows = [
|
||||||
self.sb_characters(),
|
self.sb_characters(),
|
||||||
self.sb_contents(),
|
self.sb_contents(),
|
||||||
|
self.sb_editor(),
|
||||||
self.sb_posts(),
|
self.sb_posts(),
|
||||||
self.sb_rules(),
|
self.sb_rules(),
|
||||||
self.sb_settings(),
|
self.sb_settings(),
|
||||||
|
|
|
@ -7,6 +7,7 @@ from amanuensis.errors import ArgumentError
|
||||||
from amanuensis.server.helpers import lexicon_param, player_required_if_not_public
|
from amanuensis.server.helpers import lexicon_param, player_required_if_not_public
|
||||||
|
|
||||||
from .characters import bp as characters_bp
|
from .characters import bp as characters_bp
|
||||||
|
from .editor import bp as editor_bp
|
||||||
from .forms import LexiconJoinForm
|
from .forms import LexiconJoinForm
|
||||||
from .posts import bp as posts_bp
|
from .posts import bp as posts_bp
|
||||||
from .settings import bp as settings_bp
|
from .settings import bp as settings_bp
|
||||||
|
@ -16,6 +17,7 @@ bp = Blueprint(
|
||||||
"lexicon", __name__, url_prefix="/lexicon/<lexicon_name>", template_folder="."
|
"lexicon", __name__, url_prefix="/lexicon/<lexicon_name>", template_folder="."
|
||||||
)
|
)
|
||||||
bp.register_blueprint(characters_bp)
|
bp.register_blueprint(characters_bp)
|
||||||
|
bp.register_blueprint(editor_bp)
|
||||||
bp.register_blueprint(posts_bp)
|
bp.register_blueprint(posts_bp)
|
||||||
bp.register_blueprint(settings_bp)
|
bp.register_blueprint(settings_bp)
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,167 @@
|
||||||
|
import re
|
||||||
|
|
||||||
|
from flask import Blueprint, render_template, g, abort, request
|
||||||
|
|
||||||
|
from amanuensis.backend import *
|
||||||
|
from amanuensis.db import *
|
||||||
|
from amanuensis.parser import *
|
||||||
|
from amanuensis.parser.core import Renderable
|
||||||
|
from amanuensis.server.helpers import lexicon_param, player_required
|
||||||
|
|
||||||
|
|
||||||
|
bp = Blueprint("editor", __name__, url_prefix="/editor", template_folder=".")
|
||||||
|
|
||||||
|
|
||||||
|
class PreviewHtmlRenderer(RenderableVisitor):
|
||||||
|
"""Parses stylistic markdown and stores citations as footnotes."""
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.citations: list = []
|
||||||
|
self.rendered: str = ""
|
||||||
|
|
||||||
|
# Translate the leaf spans to text
|
||||||
|
def TextSpan(self, span):
|
||||||
|
return span.innertext
|
||||||
|
|
||||||
|
def LineBreak(self, span):
|
||||||
|
return '<br>'
|
||||||
|
|
||||||
|
# Translate the simple container spans to text
|
||||||
|
def BoldSpan(self, span):
|
||||||
|
return f'<b>{"".join(span.recurse(self))}</b>'
|
||||||
|
|
||||||
|
def ItalicSpan(self, span):
|
||||||
|
return f'<i>{"".join(span.recurse(self))}</i>'
|
||||||
|
|
||||||
|
# Record citations in the visitor, then translate the span to text as an
|
||||||
|
# underline and footnote number
|
||||||
|
def CitationSpan(self, span):
|
||||||
|
self.citations.append({
|
||||||
|
"title": span.cite_target,
|
||||||
|
"type": "phantom"
|
||||||
|
})
|
||||||
|
return f'<u>{"".join(span.recurse(self))}</u>[{len(self.citations)}]'
|
||||||
|
|
||||||
|
# Translate the paragraph-level containers to their text contents
|
||||||
|
def BodyParagraph(self, span):
|
||||||
|
return f'<p>{"".join(span.recurse(self))}</p>'
|
||||||
|
|
||||||
|
def SignatureParagraph(self, span):
|
||||||
|
return (
|
||||||
|
'<hr><span class="signature"><p>'
|
||||||
|
f'{"".join(span.recurse(self))}'
|
||||||
|
'</p></span>'
|
||||||
|
)
|
||||||
|
|
||||||
|
# Return the visitor from the top-level article span after saving the full
|
||||||
|
# text parsed from the child spans
|
||||||
|
def ParsedArticle(self, span):
|
||||||
|
self.contents = '\n'.join(span.recurse(self))
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class ConstraintCheck(RenderableVisitor):
|
||||||
|
"""Analyzes an article for content-based constraint violations."""
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.word_count: int = 0
|
||||||
|
self.signatures: int = 0
|
||||||
|
self.tmp: bool = False
|
||||||
|
|
||||||
|
def TextSpan(self, span):
|
||||||
|
self.word_count += len(re.split(r'\s+', span.innertext.strip()))
|
||||||
|
return self
|
||||||
|
|
||||||
|
def BoldSpan(self, span):
|
||||||
|
self.tmp = True
|
||||||
|
return self
|
||||||
|
|
||||||
|
def SignatureParagraph(self, span):
|
||||||
|
self.signatures += 1
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
def constraint_check(parsed: Renderable):
|
||||||
|
check_result: ConstraintCheck = parsed.render(ConstraintCheck())
|
||||||
|
errors = []
|
||||||
|
errors.append({
|
||||||
|
"severity": 0,
|
||||||
|
"message": f"Word count: {check_result.word_count}"
|
||||||
|
})
|
||||||
|
if check_result.signatures < 1:
|
||||||
|
errors.append({
|
||||||
|
"severity": 1,
|
||||||
|
"message": "Missing signature paragraph"
|
||||||
|
})
|
||||||
|
if check_result.signatures > 1:
|
||||||
|
errors.append({
|
||||||
|
"severity": 1,
|
||||||
|
"message": "More than one signature paragraph"
|
||||||
|
})
|
||||||
|
if check_result.tmp:
|
||||||
|
errors.append({
|
||||||
|
"severity": 2,
|
||||||
|
"message": "Temporary error"
|
||||||
|
})
|
||||||
|
return errors
|
||||||
|
|
||||||
|
|
||||||
|
@bp.get("/")
|
||||||
|
@lexicon_param
|
||||||
|
@player_required
|
||||||
|
def select(lexicon_name):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
@bp.get("/<uuid:article_id>")
|
||||||
|
@lexicon_param
|
||||||
|
@player_required
|
||||||
|
def open(lexicon_name, article_id):
|
||||||
|
article = artiq.try_from_public_id(g.db, article_id)
|
||||||
|
if not article:
|
||||||
|
return abort(404)
|
||||||
|
return render_template(
|
||||||
|
"session.editor.jinja",
|
||||||
|
lexicon_name=lexicon_name,
|
||||||
|
article=article,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.get("/<uuid:article_id>/update")
|
||||||
|
@lexicon_param
|
||||||
|
@player_required
|
||||||
|
def load(lexicon_name, article_id):
|
||||||
|
article = artiq.try_from_public_id(g.db, article_id)
|
||||||
|
if not article:
|
||||||
|
return abort(404)
|
||||||
|
parsed = parse_raw_markdown(article.body)
|
||||||
|
preview_result: PreviewHtmlRenderer = parsed.render(PreviewHtmlRenderer())
|
||||||
|
errors = constraint_check(parsed)
|
||||||
|
return {
|
||||||
|
'title': article.title,
|
||||||
|
'rendered': preview_result.contents,
|
||||||
|
'state': article.state.value,
|
||||||
|
'ersatz': article.ersatz,
|
||||||
|
'citations': preview_result.citations,
|
||||||
|
'errors': errors,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@bp.post("/<uuid:article_id>/update")
|
||||||
|
def update(lexicon_name, article_id):
|
||||||
|
article = artiq.try_from_public_id(g.db, article_id)
|
||||||
|
if not article:
|
||||||
|
return abort(404)
|
||||||
|
article.title = request.json['title']
|
||||||
|
article.body = request.json['body']
|
||||||
|
article.state = ArticleState(request.json['state'])
|
||||||
|
g.db.session.commit()
|
||||||
|
parsed = parse_raw_markdown(article.body)
|
||||||
|
preview_result: PreviewHtmlRenderer = parsed.render(PreviewHtmlRenderer())
|
||||||
|
errors = constraint_check(parsed)
|
||||||
|
return {
|
||||||
|
'title': article.title,
|
||||||
|
'rendered': preview_result.contents,
|
||||||
|
'state': article.state.value,
|
||||||
|
'ersatz': article.ersatz,
|
||||||
|
'citations': preview_result.citations,
|
||||||
|
'errors': errors,
|
||||||
|
}
|
|
@ -1,187 +1,122 @@
|
||||||
"""
|
# """
|
||||||
Handler helper functions pertaining to the article editor
|
# Handler helper functions pertaining to the article editor
|
||||||
"""
|
# """
|
||||||
import json
|
# import json
|
||||||
import uuid
|
# import uuid
|
||||||
|
|
||||||
from flask import (
|
# from flask import (
|
||||||
flash, redirect, url_for, render_template, Markup)
|
# flash, redirect, url_for, render_template, Markup)
|
||||||
from flask_login import current_user
|
# from flask_login import current_user
|
||||||
|
|
||||||
from amanuensis.lexicon import (
|
# from amanuensis.lexicon import (
|
||||||
get_player_characters,
|
# get_player_characters,
|
||||||
get_player_drafts,
|
# get_player_drafts,
|
||||||
get_draft,
|
# get_draft,
|
||||||
title_constraint_analysis,
|
# title_constraint_analysis,
|
||||||
content_constraint_analysis)
|
# content_constraint_analysis)
|
||||||
from amanuensis.models import LexiconModel
|
# from amanuensis.models import LexiconModel
|
||||||
from amanuensis.parser import (
|
# from amanuensis.parser import (
|
||||||
normalize_title,
|
# normalize_title,
|
||||||
parse_raw_markdown)
|
# parse_raw_markdown)
|
||||||
from amanuensis.parser.core import RenderableVisitor
|
# from amanuensis.parser.core import RenderableVisitor
|
||||||
|
|
||||||
|
|
||||||
class PreviewHtmlRenderer(RenderableVisitor):
|
# class PreviewHtmlRenderer(RenderableVisitor):
|
||||||
def __init__(self, lexicon):
|
# def __init__(self, lexicon):
|
||||||
with lexicon.ctx.read('info') as info:
|
# with lexicon.ctx.read('info') as info:
|
||||||
self.article_map = {
|
# self.article_map = {
|
||||||
title: article.character
|
# title: article.character
|
||||||
for title, article in info.items()
|
# for title, article in info.items()
|
||||||
}
|
# }
|
||||||
self.citations = []
|
# self.citations = []
|
||||||
self.contents = ""
|
# self.contents = ""
|
||||||
|
|
||||||
def TextSpan(self, span):
|
# def TextSpan(self, span):
|
||||||
return span.innertext
|
# return span.innertext
|
||||||
|
|
||||||
def LineBreak(self, span):
|
# def LineBreak(self, span):
|
||||||
return '<br>'
|
# return '<br>'
|
||||||
|
|
||||||
def ParsedArticle(self, span):
|
# def ParsedArticle(self, span):
|
||||||
self.contents = '\n'.join(span.recurse(self))
|
# self.contents = '\n'.join(span.recurse(self))
|
||||||
return self
|
# return self
|
||||||
|
|
||||||
def BodyParagraph(self, span):
|
# def BodyParagraph(self, span):
|
||||||
return f'<p>{"".join(span.recurse(self))}</p>'
|
# return f'<p>{"".join(span.recurse(self))}</p>'
|
||||||
|
|
||||||
def SignatureParagraph(self, span):
|
# def SignatureParagraph(self, span):
|
||||||
return (
|
# return (
|
||||||
'<hr><span class="signature"><p>'
|
# '<hr><span class="signature"><p>'
|
||||||
f'{"".join(span.recurse(self))}'
|
# f'{"".join(span.recurse(self))}'
|
||||||
'</p></span>'
|
# '</p></span>'
|
||||||
)
|
# )
|
||||||
|
|
||||||
def BoldSpan(self, span):
|
# def BoldSpan(self, span):
|
||||||
return f'<b>{"".join(span.recurse(self))}</b>'
|
# return f'<b>{"".join(span.recurse(self))}</b>'
|
||||||
|
|
||||||
def ItalicSpan(self, span):
|
# def ItalicSpan(self, span):
|
||||||
return f'<i>{"".join(span.recurse(self))}</i>'
|
# return f'<i>{"".join(span.recurse(self))}</i>'
|
||||||
|
|
||||||
def CitationSpan(self, span):
|
# def CitationSpan(self, span):
|
||||||
if span.cite_target in self.article_map:
|
# if span.cite_target in self.article_map:
|
||||||
if self.article_map.get(span.cite_target):
|
# if self.article_map.get(span.cite_target):
|
||||||
link_class = '[extant]'
|
# link_class = '[extant]'
|
||||||
else:
|
# else:
|
||||||
link_class = '[phantom]'
|
# link_class = '[phantom]'
|
||||||
else:
|
# else:
|
||||||
link_class = '[new]'
|
# link_class = '[new]'
|
||||||
self.citations.append(f'{span.cite_target} {link_class}')
|
# self.citations.append(f'{span.cite_target} {link_class}')
|
||||||
return f'<u>{"".join(span.recurse(self))}</u>[{len(self.citations)}]'
|
# return f'<u>{"".join(span.recurse(self))}</u>[{len(self.citations)}]'
|
||||||
|
|
||||||
|
|
||||||
def load_editor(lexicon: LexiconModel, aid: str):
|
# def update_draft(lexicon: LexiconModel, article_json):
|
||||||
"""
|
# """
|
||||||
Load the editor page
|
# Update a draft and perform analysis on it
|
||||||
"""
|
# """
|
||||||
if aid:
|
# # Check if the update is permitted
|
||||||
# Article specfied, load editor in edit mode
|
# aid = article_json.get('aid')
|
||||||
article = get_draft(lexicon, aid)
|
# article = get_draft(lexicon, aid)
|
||||||
if not article:
|
# if not article:
|
||||||
flash("Draft not found")
|
# raise ValueError("missing article")
|
||||||
return redirect(url_for('session.session', name=lexicon.cfg.name))
|
# if lexicon.cfg.character.get(article.character).player != current_user.uid:
|
||||||
# Check that the player owns this article
|
# return ValueError("bad user")
|
||||||
character = lexicon.cfg.character.get(article.character)
|
# if article.status.approved:
|
||||||
if character.player != current_user.uid:
|
# raise ValueError("bad status")
|
||||||
flash("Access forbidden")
|
|
||||||
return redirect(url_for('session.session', name=lexicon.cfg.name))
|
|
||||||
return render_template(
|
|
||||||
'session.editor.jinja',
|
|
||||||
character=character,
|
|
||||||
article=article,
|
|
||||||
jsonfmt=lambda obj: Markup(json.dumps(obj)))
|
|
||||||
|
|
||||||
# Article not specified, load editor in load mode
|
# # Perform the update
|
||||||
characters = list(get_player_characters(lexicon, current_user.uid))
|
# title = article_json.get('title')
|
||||||
articles = list(get_player_drafts(lexicon, current_user.uid))
|
# contents = article_json.get('contents')
|
||||||
return render_template(
|
# status = article_json.get('status')
|
||||||
'session.editor.jinja',
|
|
||||||
characters=characters,
|
|
||||||
articles=articles)
|
|
||||||
|
|
||||||
|
# parsed = parse_raw_markdown(contents)
|
||||||
|
|
||||||
def new_draft(lexicon: LexiconModel, cid: str):
|
# # HTML parsing
|
||||||
"""
|
# preview = parsed.render(PreviewHtmlRenderer(lexicon))
|
||||||
Create a new draft and open it in the editor
|
# # Constraint analysis
|
||||||
"""
|
# title_infos, title_warnings, title_errors = title_constraint_analysis(
|
||||||
if cid:
|
# lexicon, current_user, article.character, title)
|
||||||
new_aid = uuid.uuid4().hex
|
# content_infos, content_warnings, content_errors = content_constraint_analysis(
|
||||||
# TODO harden this
|
# lexicon, current_user, article.character, parsed)
|
||||||
character = lexicon.cfg.character.get(cid)
|
# if any(title_errors) or any(content_errors):
|
||||||
article = {
|
# status['ready'] = False
|
||||||
"version": "0",
|
|
||||||
"aid": new_aid,
|
|
||||||
"lexicon": lexicon.lid,
|
|
||||||
"character": cid,
|
|
||||||
"title": "",
|
|
||||||
"turn": 1,
|
|
||||||
"status": {
|
|
||||||
"ready": False,
|
|
||||||
"approved": False
|
|
||||||
},
|
|
||||||
"contents": f"\n\n{character.signature}",
|
|
||||||
}
|
|
||||||
filename = f"{cid}.{new_aid}"
|
|
||||||
with lexicon.ctx.draft.new(filename) as j:
|
|
||||||
j.update(article)
|
|
||||||
return redirect(url_for(
|
|
||||||
'session.editor',
|
|
||||||
name=lexicon.cfg.name,
|
|
||||||
cid=cid,
|
|
||||||
aid=new_aid))
|
|
||||||
|
|
||||||
# Character not specified
|
# # Article update
|
||||||
flash('Character not found')
|
# filename = f'{article.character}.{aid}'
|
||||||
return redirect(url_for('session.session', name=lexicon.cfg.name))
|
# with lexicon.ctx.draft.edit(filename) as draft:
|
||||||
|
# draft.title = normalize_title(title)
|
||||||
|
# draft.contents = contents
|
||||||
|
# draft.status.ready = status.get('ready', False)
|
||||||
|
|
||||||
|
# # Return canonical information to editor
|
||||||
def update_draft(lexicon: LexiconModel, article_json):
|
# return {
|
||||||
"""
|
# 'title': draft.title,
|
||||||
Update a draft and perform analysis on it
|
# 'status': {
|
||||||
"""
|
# 'ready': draft.status.ready,
|
||||||
# Check if the update is permitted
|
# 'approved': draft.status.approved,
|
||||||
aid = article_json.get('aid')
|
# },
|
||||||
article = get_draft(lexicon, aid)
|
# 'rendered': preview.contents,
|
||||||
if not article:
|
# 'citations': preview.citations,
|
||||||
raise ValueError("missing article")
|
# 'info': title_infos + content_infos,
|
||||||
if lexicon.cfg.character.get(article.character).player != current_user.uid:
|
# 'warning': title_warnings + content_warnings,
|
||||||
return ValueError("bad user")
|
# 'error': title_errors + content_errors,
|
||||||
if article.status.approved:
|
# }
|
||||||
raise ValueError("bad status")
|
|
||||||
|
|
||||||
# Perform the update
|
|
||||||
title = article_json.get('title')
|
|
||||||
contents = article_json.get('contents')
|
|
||||||
status = article_json.get('status')
|
|
||||||
|
|
||||||
parsed = parse_raw_markdown(contents)
|
|
||||||
|
|
||||||
# HTML parsing
|
|
||||||
preview = parsed.render(PreviewHtmlRenderer(lexicon))
|
|
||||||
# Constraint analysis
|
|
||||||
title_infos, title_warnings, title_errors = title_constraint_analysis(
|
|
||||||
lexicon, current_user, article.character, title)
|
|
||||||
content_infos, content_warnings, content_errors = content_constraint_analysis(
|
|
||||||
lexicon, current_user, article.character, parsed)
|
|
||||||
if any(title_errors) or any(content_errors):
|
|
||||||
status['ready'] = False
|
|
||||||
|
|
||||||
# Article update
|
|
||||||
filename = f'{article.character}.{aid}'
|
|
||||||
with lexicon.ctx.draft.edit(filename) as draft:
|
|
||||||
draft.title = normalize_title(title)
|
|
||||||
draft.contents = contents
|
|
||||||
draft.status.ready = status.get('ready', False)
|
|
||||||
|
|
||||||
# Return canonical information to editor
|
|
||||||
return {
|
|
||||||
'title': draft.title,
|
|
||||||
'status': {
|
|
||||||
'ready': draft.status.ready,
|
|
||||||
'approved': draft.status.approved,
|
|
||||||
},
|
|
||||||
'rendered': preview.contents,
|
|
||||||
'citations': preview.citations,
|
|
||||||
'info': title_infos + content_infos,
|
|
||||||
'warning': title_warnings + content_warnings,
|
|
||||||
'error': title_errors + content_errors,
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,6 +1,3 @@
|
||||||
{% if character and not article %}
|
|
||||||
{% set characters = [character] %}
|
|
||||||
{% endif %}
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
|
@ -10,85 +7,31 @@
|
||||||
<link rel="icon" type="image/png" href="{{ url_for('static', filename='amanuensis.png') }}">
|
<link rel="icon" type="image/png" href="{{ url_for('static', filename='amanuensis.png') }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='page.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='page.css') }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='editor.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='editor.css') }}">
|
||||||
<script>
|
|
||||||
params = {
|
|
||||||
updateURL: "{{ url_for('session.editor_update', name=g.lexicon.cfg.name) }}",
|
|
||||||
{% if character %}
|
|
||||||
character: {{ jsonfmt(character) }},
|
|
||||||
{% else %}
|
|
||||||
character: null,
|
|
||||||
{% endif %}
|
|
||||||
{% if article %}
|
|
||||||
article: {
|
|
||||||
aid: {{ jsonfmt(article.aid) }},
|
|
||||||
status: {{ jsonfmt(article.status) }},
|
|
||||||
errors: 1,
|
|
||||||
}
|
|
||||||
{% else %}
|
|
||||||
article: null
|
|
||||||
{% endif %}
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
<script type="text/javascript" src="{{ url_for('static', filename='editor.js') }}"></script>
|
<script type="text/javascript" src="{{ url_for('static', filename='editor.js') }}"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body
|
||||||
|
data-amanuensis-update-url="{{ url_for('lexicon.editor.load', lexicon_name=lexicon_name, article_id=article.public_id) }}"
|
||||||
|
>
|
||||||
<div id="wrapper">
|
<div id="wrapper">
|
||||||
<div id="editor-left" class="column">
|
<div id="editor-left" class="column">
|
||||||
<section>
|
<section>
|
||||||
{# Thin header bar #}
|
{# Thin header bar #}
|
||||||
<div id="editor-header">
|
<div id="editor-header">
|
||||||
{# Header always includes backlink to lexicon #}
|
{# Header always includes backlink to lexicon #}
|
||||||
<a href="{{ url_for('session.session', name=g.lexicon.cfg.name) }}">
|
<a href="{{ url_for('lexicon.contents', lexicon_name=lexicon_name) }}">
|
||||||
{{ g.lexicon.title }}
|
{{ g.lexicon.full_title }}
|
||||||
</a>
|
</a>
|
||||||
{# If article is not finalized, show button to submit and retract #}
|
{# If article is not finalized, show button to submit and retract #}
|
||||||
{% if article and not article.status.approved %}
|
{# {% if article and not article.status.approved %} #}
|
||||||
<button id="button-submit" onclick="submitArticle()" disabled>Submit article</button>
|
{% if article %}
|
||||||
|
<button
|
||||||
|
id="button-submit"
|
||||||
|
disabled
|
||||||
|
>Submit article</button>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{# Header always includes character/player info #}
|
{# Header always includes character/player info #}
|
||||||
<span>
|
<span>{{ article.character.name }}</span>
|
||||||
<b>
|
|
||||||
{% if character %}
|
|
||||||
{{ character.name }} /
|
|
||||||
{% endif %}
|
|
||||||
{{ current_user.cfg.username }}
|
|
||||||
</b>
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
{# In load mode, `characters` is specified and `article` is #}
|
|
||||||
{# not, and the main body of the editor column contains a #}
|
|
||||||
{# list of articles that can be loaded. #}
|
|
||||||
{% for char in characters %}
|
|
||||||
<div id="editor-charselect">
|
|
||||||
<b>{{ char.name }}</b>
|
|
||||||
<ul>
|
|
||||||
{% for article in articles %}
|
|
||||||
{% if article.character == char.cid %}
|
|
||||||
<li>
|
|
||||||
<a href="{{ url_for('session.editor', name=g.lexicon.cfg.name, aid=article.aid) }}">
|
|
||||||
{{ article.title if article.title.strip() else "Untitled" }}</a>
|
|
||||||
<span>
|
|
||||||
{% if not article.status.ready %}
|
|
||||||
[Draft]
|
|
||||||
{% elif not article.status.approved %}
|
|
||||||
[Pending]
|
|
||||||
{% else %}
|
|
||||||
[Approved]
|
|
||||||
{% endif %}
|
|
||||||
</span>
|
|
||||||
</li>
|
|
||||||
{% endif %}
|
|
||||||
{% endfor %}
|
|
||||||
<li>
|
|
||||||
<a href="{{ url_for('session.editor_new', name=g.lexicon.cfg.name, cid=char.cid) }}">
|
|
||||||
New
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
{# In edit mode, `article` is specified and `characters` is #}
|
|
||||||
{# not, and the editor pane contains the article editor. #}
|
|
||||||
{% if article %}
|
{% if article %}
|
||||||
{# <div id="editor-buttons">
|
{# <div id="editor-buttons">
|
||||||
Character literals:
|
Character literals:
|
||||||
|
@ -98,23 +41,23 @@
|
||||||
<button>]</button>
|
<button>]</button>
|
||||||
<button>~</button>
|
<button>~</button>
|
||||||
</div> #}
|
</div> #}
|
||||||
<input id="editor-title" placeholder="Title" oninput="onContentChange()" disabled value="{{ article.title }}">
|
<input id="editor-title" placeholder="Title" disabled value="{{ article.title }}">
|
||||||
<textarea id="editor-content" class="fullwidth" oninput="onContentChange()" disabled>
|
<textarea id="editor-content" class="fullwidth" disabled>
|
||||||
{# #}{{ article.contents }}{#
|
{{- article.body -}}
|
||||||
#}</textarea>
|
</textarea>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<div id="editor-right" class="column">
|
<div id="editor-right" class="column">
|
||||||
<section id="preview">
|
<section id="preview">
|
||||||
<p>This editor requires Javascript to function.</p>
|
<p>This editor requires Javascript to function.</p>
|
||||||
</div>
|
</section>
|
||||||
<section id="preview-citations">
|
<section id="preview-citations">
|
||||||
<p> </p>
|
<p> </p>
|
||||||
</div>
|
</section>
|
||||||
<section id="preview-control">
|
<section id="preview-control">
|
||||||
<p> </p>
|
<p> </p>
|
||||||
</div>
|
</fieldset>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
|
|
|
@ -8,17 +8,9 @@
|
||||||
<span style="color:#ff0000">{{ message }}</span><br>
|
<span style="color:#ff0000">{{ message }}</span><br>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|
||||||
{% for index in indexed %}
|
{% for article in current_lexicon.articles %}
|
||||||
<b>{{ index }}</b>
|
<p>{{ article.title }} - {{ article.public_id }}</p>
|
||||||
{% if indexed[index] %}
|
<p>{{ article.body }}</p>
|
||||||
<ul>
|
|
||||||
{% for article in indexed[index] %}
|
|
||||||
<li><a href="{{ article.title|articlelink }}" class="{{ 'phantom' if not article.character else '' }}">
|
|
||||||
{{ article.title }}
|
|
||||||
</a></li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
{% endif %}
|
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
Loading…
Reference in New Issue