Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
tabatkins committed Dec 15, 2023
1 parent 078b0c4 commit 38388d4
Show file tree
Hide file tree
Showing 28 changed files with 4,687 additions and 484 deletions.
12 changes: 8 additions & 4 deletions bikeshed/boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,12 +259,20 @@ def addBikeshedBoilerplate(doc: t.SpecT) -> None:
for style in doc.extraStyles.getAll():
if "style-" + style.name not in doc.md.boilerplate:
continue
if doc.extraScripts.has(style.name):
# If there's a matching script,
# but it's not insertable,
# don't insert the style either.
if not doc.extraScripts.get(style.name).insertable():
continue
container = getFillContainer("style-" + style.name, doc)
if container is None:
container = getFillContainer("bs-styles", doc, default=True)
if container is not None:
h.appendChild(container, style.toElement(darkMode=doc.md.darkMode))
for script in doc.extraScripts.getAll():
if not script.insertable():
continue
if "script-" + script.name not in doc.md.boilerplate:
continue
container = getFillContainer("script-" + script.name, doc)
Expand Down Expand Up @@ -523,7 +531,6 @@ def makeEntry(ref: t.RefWrapper, contents: t.NodesT) -> t.ElementT:

ul = h.E.ul({"class": "index"})

atLeastOnePanel = False
for specName, specData in doc.externalRefsUsed.sorted():
# Skip entries that are *solely* a biblio entry.
if not specData.refs:
Expand Down Expand Up @@ -562,9 +569,6 @@ def makeEntry(ref: t.RefWrapper, contents: t.NodesT) -> t.ElementT:
entry = makeEntry(ref, refText)
h.appendChild(termsUl, h.E.li(entry))
dfnpanels.addExternalDfnPanel(entry, ref, doc)
atLeastOnePanel = True
if atLeastOnePanel:
dfnpanels.addExternalDfnPanelStyles(doc)
h.appendChild(
container,
h.E.h3(
Expand Down
1 change: 0 additions & 1 deletion bikeshed/dfnpanels/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from .dfnpanels import (
addDfnPanels,
addExternalDfnPanel,
addExternalDfnPanelStyles,
)
33 changes: 11 additions & 22 deletions bikeshed/dfnpanels/dfnpanels.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import json
from collections import OrderedDict

from .. import h, t
Expand All @@ -10,7 +9,6 @@

def addDfnPanels(doc: t.SpecT, dfns: list[t.ElementT]) -> None:
# Constructs "dfn panels" which show all the local references to a term
atLeastOnePanel = False
# Gather all the <a href>s together
allRefs: OrderedDict[str, list[t.ElementT]] = OrderedDict()
for a in h.findAll("a", doc):
Expand All @@ -20,7 +18,9 @@ def addDfnPanels(doc: t.SpecT, dfns: list[t.ElementT]) -> None:
if not href.startswith("#"):
continue
allRefs.setdefault(href[1:], []).append(a)
scriptLines = []
script = doc.extraScripts.setFile("dfn-panel", "dfnpanels/dfnpanels.js")
panelsJSON: t.JSONT = script.initData("dfnPanelData", {})
doc.extraStyles.setFile("dfn-panel", "dfnpanels/dfnpanels.css")
for dfn in dfns:
id = dfn.get("id")
dfnText = h.textContent(dfn)
Expand All @@ -39,7 +39,6 @@ def addDfnPanels(doc: t.SpecT, dfns: list[t.ElementT]) -> None:
h.appendChild(dfn, h.E.a({"href": "#" + h.escapeUrlFrag(id), "class": "self-link"}))
continue
h.addClass(doc, dfn, "dfn-paneled")
atLeastOnePanel = True
sectionsJson = []
for text, els in refsFromSection.items():
refsJson = []
Expand All @@ -55,20 +54,15 @@ def addDfnPanels(doc: t.SpecT, dfns: list[t.ElementT]) -> None:
"title": text,
},
)
panelJson = {
panelsJSON[id] = {
"dfnID": id,
"url": "#" + h.escapeUrlFrag(id),
"dfnText": dfnText,
"refSections": sectionsJson,
"external": False,
}
scriptLines.append(f"window.dfnpanelData['{id}'] = {json.dumps(panelJson)};")
if len(scriptLines) > 0:
jsonBlock = doc.extraScripts.setDefault("dfn-panel-json", "window.dfnpanelData = {};\n")
jsonBlock.text += "\n".join(scriptLines)
if atLeastOnePanel:
doc.extraScripts.setFile("dfn-panel", "dfnpanels/dfnpanels.js")
doc.extraStyles.setFile("dfn-panel", "dfnpanels/dfnpanels.css")

if panelsJSON:
h.addDOMHelperScript(doc)


Expand All @@ -89,6 +83,10 @@ def addExternalDfnPanel(termEl: t.ElementT, ref: t.RefWrapper, doc: t.SpecT) ->
if ref.url not in doc.cachedLinksFromHref:
return

script = doc.extraScripts.setFile("dfn-panel", "dfnpanels/dfnpanels.js")
panelsJSON: t.JSONT = script.initData("dfnPanelData", {})
doc.extraStyles.setFile("dfn-panel", "dfnpanels/dfnpanels.css")

# Group the relevant links according to the section they're in.
refsFromSection: OrderedDict[str, list[t.ElementT]] = OrderedDict()
for link in doc.cachedLinksFromHref[ref.url]:
Expand Down Expand Up @@ -122,19 +120,10 @@ def addExternalDfnPanel(termEl: t.ElementT, ref: t.RefWrapper, doc: t.SpecT) ->
"title": text,
},
)
panelJson = {
panelsJSON[termID] = {
"dfnID": termID,
"url": ref.url,
"dfnText": termText,
"refSections": sectionsJson,
"external": True,
}

jsonBlock = doc.extraScripts.setDefault("dfn-panel-json", "window.dfnpanelData = {};\n")
jsonBlock.text += f"window.dfnpanelData['{termID}'] = {json.dumps(panelJson)};\n"


def addExternalDfnPanelStyles(doc: t.SpecT) -> None:
doc.extraScripts.setFile("dfn-panel", "dfnpanels/dfnpanels.js")
doc.extraStyles.setFile("dfn-panel", "dfnpanels/dfnpanels.css")
h.addDOMHelperScript(doc)
45 changes: 28 additions & 17 deletions bikeshed/stylescript/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@
class ScriptManager:
scripts: list[Script] = dataclasses.field(default_factory=list)

def set(self, name: str, text: str) -> None:
def set(self, name: str, text: str) -> Script:
for sc in self.scripts:
if sc.name == name:
sc.text = text
return sc
script = Script(name, text, {})
script = Script(name, text)
self.scripts.append(script)
return script

def setFile(self, name: str, localPath: str) -> None:
def setFile(self, name: str, localPath: str) -> Script:
if not self.has(name):
with open(config.scriptPath(localPath), "r", encoding="utf-8") as fh:
self.set(name, fh.read())
Expand All @@ -30,7 +30,7 @@ def setFile(self, name: str, localPath: str) -> None:
def setDefault(self, name: str, text: str) -> Script:
if self.has(name):
return self.get(name)
script = Script(name, text, {})
script = Script(name, text)
self.scripts.append(script)
return script

Expand Down Expand Up @@ -88,28 +88,39 @@ def getAll(self) -> list[Style]:
def has(self, name: str) -> bool:
return any(x.name == name for x in self.styles)


if t.TYPE_CHECKING:
ScriptDataT = t.TypeVar("ScriptDataT", bound=t.JSONT)


@dataclasses.dataclass
class Script:
name: str
text: str
data: dict[str, t.JSONT] | None

def getData(self, dataName: str, default: ScriptDataT) -> ScriptDataT:
if self.data is None:
self.data = {}
if dataName not in self.data:
self.data[dataName] = default
return self.data[dataName]
text: str | None
dataName: str | None = None
data: t.JSONT | None = None

def initData(self, dataName: str, default: ScriptDataT) -> ScriptDataT:
if self.dataName is not None and self.dataName != dataName:
msg = f"Programming error: tried to set script {self.name} to dataName {dataName} when it's already set to {self.dataName}."
raise Exception(msg)
if self.dataName is None:
self.dataName = dataName
self.data = default
return t.cast("ScriptDataT", self.data)

def insertable(self) -> bool:
if self.dataName is None:
return True
if self.data:
return True
return False

def toElement(self) -> t.ElementT:
assert self.text is not None
text = f"/* Boilerplate: script-{self.name} */\n"
if self.data:
for dataName, dataJSON in self.data.items():
text += f"let {dataName} = {json.dumps(dataJSON, sort_keys=True, indent=1)};\n"
text += "\n"
if self.dataName:
text += f"let {self.dataName} = {json.dumps(self.data, sort_keys=True, indent=1)};\n\n"
text += self.text
if not text.endswith("\n"):
text += "\n"
Expand Down
20 changes: 7 additions & 13 deletions bikeshed/unsortedJunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,8 +677,9 @@ def verifyUsageOfAllLocalBiblios(doc: t.SpecT) -> None:


def processAutolinks(doc: t.SpecT) -> None:
scriptLines = []
refsAdded = {}
script = doc.extraScripts.setFile("ref-hints", "refs/refhints.js")
refsJSON = script.initData("refsData", {})
doc.extraStyles.setFile("ref-hints", "refs/refhints.css")

# An <a> without an href is an autolink.
# <i> is a legacy syntax for term autolinks. If it links up, we change it into an <a>.
Expand Down Expand Up @@ -766,10 +767,8 @@ def processAutolinks(doc: t.SpecT) -> None:
el.text = replacementText
decorateAutolink(doc, el, linkType=linkType, linkText=linkText, ref=ref)

if ref.url not in refsAdded:
refsAdded[ref.url] = True
refJson = ref.__json__()
scriptLines.append(f"window.refsData['{ref.url}'] = {json.dumps(refJson)};")
if ref.url not in refsJSON:
refsJSON[ref.url] = ref.__json__()
else:
if linkType == "maybe":
el.tag = "css"
Expand All @@ -778,12 +777,7 @@ def processAutolinks(doc: t.SpecT) -> None:
if el.get("data-lt"):
del el.attrib["data-lt"]

if len(scriptLines) > 0:
jsonBlock = doc.extraScripts.setDefault("ref-hints-json", "window.refsData = {};\n")
jsonBlock.text += "\n".join(scriptLines)

doc.extraScripts.setFile("ref-hints", "refs/refhints.js")
doc.extraStyles.setFile("ref-hints", "refs/refhints.css")
if refsJSON:
h.addDOMHelperScript(doc)

h.dedupIDs(doc)
Expand Down Expand Up @@ -835,7 +829,7 @@ def decorateAutolink(doc: t.SpecT, el: t.ElementT, linkType: str, linkText: str,
doc.typeExpansions[linkText] = titleText
if titleText:
script = doc.extraScripts.setFile("link-titles", "link-titles.js")
script.getData("linkTitleData", {})[ref.url] = titleText
script.initData("linkTitleData", t.cast("dict[str, str]", {}))[ref.url] = titleText


def removeMultipleLinks(doc: t.SpecT) -> None:
Expand Down
74 changes: 64 additions & 10 deletions tests/adjacent-boilerplate/adjacent-boilerplate.html
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,41 @@ <h3 class="no-num no-ref heading settled" id="normative"><span class="content">N
<dd>Anne van Kesteren. <a href="https://fetch.spec.whatwg.org/"><cite>Fetch Standard</cite></a>. Living Standard. URL: <a href="https://fetch.spec.whatwg.org/">https://fetch.spec.whatwg.org/</a>
</dl>
<script>/* Boilerplate: script-dfn-panel */
let dfnPanelData = {
"a3f70a8b": {
"dfnID": "a3f70a8b",
"dfnText": "term",
"external": true,
"refSections": [
{
"refs": [
{
"id": "ref-for-term"
}
],
"title": "Unnamed section"
}
],
"url": "https://example.test/foo/#term"
},
"e3201629": {
"dfnID": "e3201629",
"dfnText": "response",
"external": true,
"refSections": [
{
"refs": [
{
"id": "ref-for-concept-response-response"
}
],
"title": "Unnamed section"
}
],
"url": "https://fetch.spec.whatwg.org/#concept-response-response"
}
};

"use strict";
{
// Functions, divided by link type, that wrap an autolink's
Expand Down Expand Up @@ -1025,11 +1060,6 @@ <h3 class="no-num no-ref heading settled" id="normative"><span class="content">N
});
}
</script>
<script>/* Boilerplate: script-dfn-panel-json */
window.dfnpanelData = {};
window.dfnpanelData['a3f70a8b'] = {"dfnID": "a3f70a8b", "url": "https://example.test/foo/#term", "dfnText": "term", "refSections": [{"refs": [{"id": "ref-for-term"}], "title": "Unnamed section"}], "external": true};
window.dfnpanelData['e3201629'] = {"dfnID": "e3201629", "url": "https://fetch.spec.whatwg.org/#concept-response-response", "dfnText": "response", "refSections": [{"refs": [{"id": "ref-for-concept-response-response"}], "title": "Unnamed section"}], "external": true};
</script>
<script>/* Boilerplate: script-dom-helper */
function query(sel) { return document.querySelector(sel); }

Expand Down Expand Up @@ -1227,6 +1257,35 @@ <h3 class="no-num no-ref heading settled" id="normative"><span class="content">N
}
</script>
<script>/* Boilerplate: script-ref-hints */
let refsData = {
"https://example.test/foo/#term": {
"export": true,
"for_": [],
"level": "",
"normative": true,
"shortname": "example-spec",
"spec": "example-spec",
"status": "anchor-block",
"text": "term",
"type": "dfn",
"url": "https://example.test/foo/#term"
},
"https://fetch.spec.whatwg.org/#concept-response-response": {
"export": true,
"for_": [
"Response"
],
"level": "1",
"normative": true,
"shortname": "fetch",
"spec": "fetch",
"status": "current",
"text": "response",
"type": "dfn",
"url": "https://fetch.spec.whatwg.org/#concept-response-response"
}
};

"use strict";
{
function genRefHint(link, ref) {
Expand Down Expand Up @@ -1434,9 +1493,4 @@ <h3 class="no-num no-ref heading settled" id="normative"><span class="content">N
hideAllRefHints();
});
}
</script>
<script>/* Boilerplate: script-ref-hints-json */
window.refsData = {};
window.refsData['https://example.test/foo/#term'] = {"text": "term", "type": "dfn", "spec": "example-spec", "shortname": "example-spec", "level": "", "status": "anchor-block", "url": "https://example.test/foo/#term", "export": true, "normative": true, "for_": []};
window.refsData['https://fetch.spec.whatwg.org/#concept-response-response'] = {"text": "response", "type": "dfn", "spec": "fetch", "shortname": "fetch", "level": "1", "status": "current", "url": "https://fetch.spec.whatwg.org/#concept-response-response", "export": true, "normative": true, "for_": ["Response"]};
</script>
Loading

0 comments on commit 38388d4

Please sign in to comment.