From 8f53473e3d9581cc0c3dd0da72f6ae2990b3de8e Mon Sep 17 00:00:00 2001 From: Etienne Pichot Damon Date: Wed, 18 Nov 2026 15:17:52 -0500 Subject: [PATCH 1/2] feat(specifications): edit entries and propose new ones from the registry pages Add an in-page editor to the specification registry so contributors can propose changes without editing YAML by hand. - "Suggest a change" now turns a specification page into an editor: an edit button next to every value that comes from the entry's file, each opening a control that fits the field (custom drop-downs for statuses and verdicts, a searchable licence picker with an "Other licence" option and scopes, an organization picker, mode chips, year, count, date and URL inputs with validation). - Values that depend on each other stay consistent while editing: the MDIP status follows the criteria verdicts (same rule as specs-check), a closed or restricted licence sets "Free of cost restrictions", a new adopters count takes today's date and the matching tier, and an inactive lifecycle makes the status inactive. - Changes are reviewed in a dialog and sent as a pre-filled GitHub issue from the new specification-edit.yml form, with a before/after table and the same change as YAML for the file. The draft is kept in localStorage until it is sent, so signing in or creating a GitHub account does not lose it; a sign-up link returns to the pre-filled form. - New /specifications/new/ page: a blank entry opened in the same editor, with the registry id derived from the short name and checked for uniqueness. It sends the complete new file. Linked as "Propose a new specification" on every entry and from the registry page. - History now lists who took part in each change from the GitHub timeline: "Discussed with" (up to three names, then "and N more"), "Approved by", and "Merged by" only when nobody approved. Open suggestions sent from the editor appear under "Proposed changes". - The filter panel on wide screens no longer has its own scrollbar: it scrolls with the page until its last filter is visible and comes back as soon as the page scrolls up. - The editor draws organization monograms only, so it loads nothing from third-party hosts. - Point the local preview config at config/en/properdocs.yml and document the new contribution flow in README.md and data/README.md. The issue form only takes effect once it is on main. Co-Authored-By: Claude Opus 5.5 --- .claude/launch.json | 4 +- .github/ISSUE_TEMPLATE/specification-edit.yml | 32 + README.md | 7 +- config/en/properdocs.yml | 2 + data/README.md | 20 +- hooks/specifications.py | 416 +++-- overrides/assets/javascript/spec-editor.js | 1565 +++++++++++++++++ overrides/assets/javascript/specifications.js | 300 +++- overrides/assets/stylesheets/spec-editor.css | 537 ++++++ .../assets/stylesheets/specifications.css | 12 +- 10 files changed, 2731 insertions(+), 164 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/specification-edit.yml create mode 100644 overrides/assets/javascript/spec-editor.js create mode 100644 overrides/assets/stylesheets/spec-editor.css diff --git a/.claude/launch.json b/.claude/launch.json index 530f8ca..fc790b2 100644 --- a/.claude/launch.json +++ b/.claude/launch.json @@ -4,13 +4,13 @@ { "name": "mkdocs-en", "runtimeExecutable": "mkdocs", - "runtimeArgs": ["serve", "-f", "config/en/mkdocs.yml", "--dev-addr", "127.0.0.1:8000", "--watch", "overrides", "--watch", "hooks", "--watch", "data", "--watch", "scripts"], + "runtimeArgs": ["serve", "-f", "config/en/properdocs.yml", "--dev-addr", "127.0.0.1:8000", "--watch", "overrides", "--watch", "hooks", "--watch", "data", "--watch", "scripts"], "port": 8000 }, { "name": "mkdocs-en-alt", "runtimeExecutable": "mkdocs", - "runtimeArgs": ["serve", "-f", "config/en/mkdocs.yml", "--dev-addr", "127.0.0.1:8001"], + "runtimeArgs": ["serve", "-f", "config/en/properdocs.yml", "--dev-addr", "127.0.0.1:8001"], "port": 8001 } ] diff --git a/.github/ISSUE_TEMPLATE/specification-edit.yml b/.github/ISSUE_TEMPLATE/specification-edit.yml new file mode 100644 index 0000000..ef9c3be --- /dev/null +++ b/.github/ISSUE_TEMPLATE/specification-edit.yml @@ -0,0 +1,32 @@ +name: Suggested change from a specification page +description: Filled in by "Suggest a change" on a specification's page in the MDIP registry (/specifications). +title: "Suggested change: " +labels: ["specification-registry", "suggested-change"] +body: + - type: markdown + attributes: + value: | + This form is filled in by the registry page. Submit it as it is: the + coalition reviews the change here in public, then applies it to the + specification's file in [`data/specifications/`](https://github.com/MobilityData/Mobility-Data-Interoperability-Principles/tree/main/data/specifications). + - type: input + id: spec_id + attributes: + label: Specification id + description: The file name in `data/specifications/`, without `.md`. + validations: + required: true + - type: textarea + id: change + attributes: + label: Proposed change + description: What the page shows today, what it should show, and the same change as it would be written in the file. + validations: + required: true + - type: textarea + id: evidence + attributes: + label: Sources + description: Links that support the change, such as a licence file, governance charter, changelog or adopters list. + validations: + required: false diff --git a/README.md b/README.md index bca95c8..8863710 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,10 @@ The `/specifications` page, one page per specification under `/specifications//`, and a read-only JSON API under `/api/` are generated at build time from the files in [`data/`](data/README.md). GitHub is the source of truth and the place to contribute: each specification and each -organization is one Markdown file with YAML front matter, and "Suggest a -change" on a specification's page opens that file in GitHub's editor. +organization is one Markdown file with YAML front matter. "Suggest a change" +on a specification's page edits the page in place and sends the change as a +pre-filled GitHub issue; `/specifications/new/` does the same for a new +specification. | Path | What it is | | --- | --- | @@ -50,6 +52,7 @@ change" on a specification's page opens that file in GitHub's editor. | `scripts/spec_api.py` | Builds the `/api/` files: catalogue, full records, export CSV, the OpenAPI description, and its Swagger UI page at `/api/docs/`. | | `scripts/check_specs.py` | `make specs-check`: validation, also run on every pull request. | | `hooks/specifications.py` | MkDocs hook that renders the pages and publishes the API. | +| `overrides/assets/javascript/spec-editor.js` | The in-page editor behind "Suggest a change" and `/specifications/new/`. | ```bash make specs-check # validate the data; fails on any unknown value or key diff --git a/config/en/properdocs.yml b/config/en/properdocs.yml index ae9535a..a5b014c 100644 --- a/config/en/properdocs.yml +++ b/config/en/properdocs.yml @@ -64,11 +64,13 @@ extra_javascript: - https://unpkg.com/mermaid@8.5.0/dist/mermaid.min.js - assets/javascript/fix-md-search.js - assets/javascript/specifications.js + - assets/javascript/spec-editor.js extra_css: - https://use.fontawesome.com/releases/v5.13.0/css/all.css - assets/stylesheets/additional.css - assets/stylesheets/specifications.css + - assets/stylesheets/spec-editor.css markdown_extensions: - attr_list diff --git a/data/README.md b/data/README.md index f9e865a..57466c9 100644 --- a/data/README.md +++ b/data/README.md @@ -15,13 +15,19 @@ folder on every build. ## How to contribute -- **Change an entry**: on the specification's page, "Suggest a change" opens - its file in GitHub's editor. Without write access to the repository, GitHub - offers to fork it and open a pull request, which is where the change is - reviewed. -- **Add a specification**: "Propose a specification" on the registry page - opens a new file with every field laid out. Name the file after the - specification's id. +- **Change an entry**: on the specification's page, "Suggest a change" makes + the page editable. Each value gets an edit button with a control that only + offers valid values, and values that depend on each other follow along (a + criterion that is not compliant makes the status not compliant, for + example). The change is sent as a pre-filled issue + ([`specification-edit.yml`](../.github/ISSUE_TEMPLATE/specification-edit.yml)) + showing what changes and the same change as YAML for the file. It is kept + in the browser until it is sent, so signing in or creating a GitHub account + does not lose it. Without JavaScript, the button opens the file in GitHub's + editor instead. +- **Add a specification**: "Propose a specification" opens + `/specifications/new/`, a blank page in the same editor. It sends the whole + new file, named after the registry id, as an issue. - **Report a problem or ask a question**: open a [change request](https://github.com/MobilityData/Mobility-Data-Interoperability-Principles/issues/new?template=specification-change.yml). diff --git a/hooks/specifications.py b/hooks/specifications.py index fdfd75d..59222c7 100644 --- a/hooks/specifications.py +++ b/hooks/specifications.py @@ -215,6 +215,9 @@ def new_spec_url(data): quote("new-specification-id.md"), quote(NEW_SPEC_TEMPLATE % blocks)) +NEW_SLUG = "new" + + def render_contribute(data, spec=None): """Where to change what the page shows. @@ -226,26 +229,34 @@ def render_contribute(data, spec=None): if spec: title = "Something to update about %s?" % spec["short_name"] text = ("If any information on this page is missing, outdated or incorrect, " - "suggest an edit on GitHub. The coalition reviews every change in public " + "suggest a change. The coalition reviews every change in public " "before it appears here.") primary = (spec_data.github_url("edit", spec["source_path"]), "pencil-outline", "Suggest a change") secondary = (issue_url(spec), "message-alert-outline", "Report an issue") + third = ("../%s/" % NEW_SLUG, "plus", "Propose a new specification") else: title = "Help keep this registry accurate" text = ("Every specification and organization on this page is a file kept in the " "open on GitHub. Anyone can suggest a change, or propose a specification " "that is missing.") - primary = (new_spec_url(data), "plus", "Propose a specification") + primary = ("%s/" % NEW_SLUG, "plus", "Propose a specification") secondary = (spec_data.github_url("tree", "data"), "database-outline", "Browse the data") + third = None + # On a specification page the page script turns "Suggest a change" into + # the in-page editor; the link to GitHub's editor is what it does without + # JavaScript. return ('
%s

%s

%s

' '
' - '%s%s' - '%s%s' + '%s%s' + '%s%s%s' "
" % (icon("github", "contribute__ico"), escape(title), escape(text), - escape(primary[0]), icon(primary[1]), escape(primary[2]), - escape(secondary[0]), icon(secondary[1]), escape(secondary[2]))) + escape(primary[0]), " data-edit-start" if spec else "", icon(primary[1]), + escape(primary[2]), + escape(secondary[0]), icon(secondary[1]), escape(secondary[2]), + '%s%s' + % (escape(third[0]), icon(third[1]), escape(third[2])) if third else "")) # -------------------------------------------------------------------------- @@ -592,13 +603,45 @@ def description_html(text): return markdown.markdown(escape(text, quote=False), extensions=["sane_lists"]) -def dl_row(ico, label, value_html): - return ('
%s%s
%s
' - % (icon(ico), escape(label), value_html)) +def field_attrs(path, edit=True, view=None): + """Attributes that tie an element to one field of the entry's file. + + `data-field` is the dotted path of the value in the front matter, the same + key the History section uses. The page editor (spec-editor.js) re-renders + every element bound to a field when it changes, and puts a small edit + button next to the ones marked `data-edit`. `view` names how the value is + drawn when the same field shows up in more than one form (a tag in "At a + glance", a card under "Licensing"). + """ + out = ' data-field="%s"' % escape(path) + if edit: + out += " data-edit" + if view: + out += ' data-view="%s"' % escape(view) + return out + + +def edit_only(empty): + """Keep an element in the page for the editor, out of sight until then. + + A field with no value renders nothing on the published page, but it must + still be there to be filled in, so the element is rendered hidden and the + editor reveals it. + """ + return " hidden data-edit-only" if empty else "" + +def dl_row(ico, label, value_html, field=None, empty=False, view=None, edit=True): + dd = "" % (field_attrs(field, edit, view) if field else "") + return ('
%s%s
%s%s
' + % (edit_only(empty), icon(ico), escape(label), dd, value_html)) -def render_detail(spec, data, base): - o = ['
'] + +def render_detail(spec, data, base, new=False): + """One specification's page, or with `new` the blank page on which a + specification is proposed: the same layout, every field empty, opened in + the editor straight away.""" + o = ['
' % (" data-edit-new" if new else "")] o.append('%sAll specifications' % (escape(base + SECTION + "/"), icon("arrow-left"))) @@ -607,14 +650,18 @@ def render_detail(spec, data, base): o.append('
' % escape(spec["status_tone"])) o.append('') o.append('
') - o.append('
%s%s
' - % (pill(spec["status_tone"], spec["status_label"]), + o.append('
%s%s
' + % (field_attrs("status", False, "pill"), + pill(spec["status_tone"], spec["status_label"]), meter(spec["criteria_met"], spec["criteria_total"]))) - o.append("

%s

" % escape(spec["short_name"])) - if spec["full_name"] and spec["full_name"] != spec["short_name"]: - o.append('

%s

' % escape(spec["full_name"])) - if spec["description"]: - o.append('
%s
' % description_html(spec["description"])) + o.append("

%s

" % (field_attrs("short_name"), escape(spec["short_name"]))) + show_full = bool(spec["full_name"]) and spec["full_name"] != spec["short_name"] + o.append('

%s

' + % (edit_only(not show_full), field_attrs("full_name"), + escape(spec["full_name"] if show_full else ""))) + o.append('
%s
' + % (edit_only(not spec["description"]), field_attrs("description", view="block"), + description_html(spec["description"]) if spec["description"] else "")) o.append('
') if spec["homepage_url"]: @@ -626,13 +673,14 @@ def render_detail(spec, data, base): % (escape(spec["adopters_registry"]), icon("account-group"), icon("open-in-new"))) o.append("
") - if spec["maintainers"]: - o.append('
Maintained by' - "") - for org in spec["maintainers"]: - o.append('%s%s' - % (org_logo(org, base), escape(org["name"]))) - o.append("
") + o.append('
Maintained by' + '' + % (" hidden" if not spec["maintainers"] else "", + field_attrs("maintainers", False, "chips"))) + for org in spec["maintainers"]: + o.append('%s%s' + % (org_logo(org, base), escape(org["name"]))) + o.append("
") o.append("
") # ---- in-page nav @@ -643,7 +691,8 @@ def render_detail(spec, data, base): sections.append(("adoption", "Adoption", "account-group")) if spec["maintainers"]: sections.append(("maintainers", "Maintainers", "domain")) - sections.append(("history", "History", "history")) + if not new: + sections.append(("history", "History", "history")) o.append('
") o.append(render_rules(data)) @@ -729,7 +801,7 @@ def render_detail(spec, data, base): # ---- licensing o.append('
') o.append('

%sLicensing

' % icon("scale-balance")) - o.append('
') + o.append('
' % field_attrs("licences", view="cards")) for lic in spec["licences"]: o.append('
' % escape(lic["category"])) o.append('
') @@ -754,78 +826,177 @@ def render_detail(spec, data, base): % (icon("information-outline"), escape(lic["note"]))) o.append("
") o.append("
") + o.append('
' + % (edit_only(not spec["licence_evidence"]), + field_attrs("licence_evidence_url", view="licence-text"))) for url in spec["licence_evidence"]: o.append('

%s

' % ext_link(url, "Licence text")) + o.append("
") o.append("
") # ---- adoption - if spec["adoption_tier_label"] or spec["adopters_count"] or spec["adopters_registry"]: - o.append('
') - o.append('

%sAdoption

' % icon("account-group")) - o.append('
') - if spec["adoption_tier_label"]: - o.append(dl_row("counter", "Adoption tier", - '%s' % escape(spec["adoption_tier_label"]))) - o.append(dl_row("account-check", "Confirmed by maintainer", - pill(spec["confirmed_tone"], spec["confirmed_label"]))) - if spec["adopters_count"]: - note = "" - if spec["adopters_count_updated"]: - note = ('as of %s' - % escape(spec["adopters_count_updated"])) - o.append(dl_row("counter", "Known adopters", - "%d%s" % (spec["adopters_count"], note))) - if spec["adopters_registry"]: - o.append(dl_row("database-outline", "Adopters registry", - ext_link(spec["adopters_registry"], "Open registry"))) - o.append("
") - series = spec_history.adopters_series(spec) - if len(series) >= 2: - o.append('

%sHistory

%s
' - % (icon("chart-line"), render_adopters_chart(series))) - o.append("
") + # Always rendered, so the editor can fill it in; hidden when empty. + has_adoption = bool(spec["adoption_tier_label"] or spec["adopters_count"] + or spec["adopters_registry"]) + o.append('
' % edit_only(not has_adoption)) + o.append('

%sAdoption

' % icon("account-group")) + o.append('
') + o.append(dl_row("counter", "Adoption tier", + '%s' % escape(spec["adoption_tier_label"]) + if spec["adoption_tier_label"] else "", + "adoption.tier", not spec["adoption_tier_label"])) + o.append(dl_row("account-check", "Confirmed by maintainer", + pill(spec["confirmed_tone"], spec["confirmed_label"]), + "adoption.confirmed_by_maintainer")) + count = spec["adopters_count"] + o.append(dl_row("counter", "Known adopters", + '%s%s' + % (field_attrs("adoption.adopters_count", view="count"), + "{:,}".format(count) if count is not None else "", + field_attrs("adoption.adopters_count_updated", view="as-of"), + ("as of %s" % escape(spec["adopters_count_updated"])) + if spec["adopters_count_updated"] else ""), + empty=not count)) + o.append(dl_row("database-outline", "Adopters registry", + ext_link(spec["adopters_registry"], "Open registry") + if spec["adopters_registry"] else "", + "adoption.adopters_registry_url", not spec["adopters_registry"], + view="registry")) + o.append("
") + series = spec_history.adopters_series(spec) + if len(series) >= 2: + o.append('

%sHistory

%s
' + % (icon("chart-line"), render_adopters_chart(series))) + o.append("
") # ---- maintainers - if spec["maintainers"]: - o.append('
') - o.append('

%sMaintainers

' % icon("domain")) - o.append('
') - for org in spec["maintainers"]: - o.append('
%s
' - "

%s

%s

" % (org_logo(org, base), escape(org["name"]), - escape(org["type_label"]))) - if org["url"]: - o.append('%s%s' - % (escape(org["url"]), escape(short_url(org["url"])), - icon("open-in-new"))) - o.append("
") - o.append("
") + o.append('
' + % edit_only(not spec["maintainers"])) + o.append('

%sMaintainers

' % icon("domain")) + o.append('
' % field_attrs("maintainers", view="cards")) + for org in spec["maintainers"]: + o.append('
%s
' + "

%s

%s

" % (org_logo(org, base), escape(org["name"]), + escape(org["type_label"]))) + if org["url"]: + o.append('%s%s' + % (escape(org["url"]), escape(short_url(org["url"])), + icon("open-in-new"))) + o.append("
") + o.append("
") + + related = [s for s in data["specs"] + if not new and s["id"] != spec["id"] + and set(s["maintainer_ids"]) & set(spec["maintainer_ids"])] + if related: + o.append('") + o.append("
") - related = [s for s in data["specs"] - if s["id"] != spec["id"] - and set(s["maintainer_ids"]) & set(spec["maintainer_ids"])] - if related: - o.append('") - o.append("
") - - o.append(render_history(spec, data)) + if not new: + o.append(render_history(spec, data)) o.append("
") # body - o.append(render_contribute(data, spec)) + if new: + # The proposal is made in the page's editor; without JavaScript, the + # file can still be written in GitHub's editor. + o.append('" % escape(new_spec_url(data))) + else: + o.append(render_contribute(data, spec)) + + o.append('' + % json.dumps(edit_config(spec, data, new), + separators=(",", ":")).replace("") return "\n".join(o) +# -------------------------------------------------------------------------- +# In-page editor +# -------------------------------------------------------------------------- + +EDIT_TEMPLATE = "specification-edit.yml" + +EDIT_ICONS = ( + "pencil-outline", "check", "close", "plus", "chevron-down", "magnify", "github", + "content-copy", "delete-outline", "open-in-new", "link-variant", "check-circle", + "alert-circle", "close-circle", "progress-clock", "help-circle", "undo-variant", + "account-plus-outline", "information-outline", +) + + +def _jsonable(value): + """The front matter as JSON: YAML dates become `YYYY-MM-DD` text.""" + if isinstance(value, dict): + return dict((str(k), _jsonable(v)) for k, v in value.items()) + if isinstance(value, list): + return [_jsonable(v) for v in value] + if hasattr(value, "isoformat"): + return value.isoformat() + return value + + +def edit_config(spec, data, new=False): + """What the page editor (spec-editor.js) needs, in one object. + + `front` and `description` are the file exactly as written, not the joined + record the page is drawn from, so that what the editor proposes is a + change to the file and nothing else. The vocabularies are the ones + `make specs-check` accepts, so the editor can only offer valid values, + plus a way to name a licence or a maintainer that is not listed yet. + """ + if new: + front, sections = {}, {} + else: + front, sections = spec_data.read_entry(os.path.join(ROOT, spec["source_path"])) + labels = dict(history_labels(data)["fields"], id="Registry id") + return { + "new": new, + "ids": [s["id"] for s in data["specs"]] if new else [], + "id": spec["id"], + "name": spec["short_name"], + "path": spec["source_path"], + "repo": spec_data.GITHUB_REPO, + "template": EDIT_TEMPLATE, + "front": _jsonable(front), + "description": sections.get("Description", ""), + "labels": labels, + "status": [dict(id=k, label=v["label"], tone=v["tone"]) + for k, v in spec_data.STATUS.items()], + "verdict": [dict(id=k, label=v["label"], tone=v["tone"]) + for k, v in spec_data.VERDICT.items()], + "lifecycle": [dict(id=k, label=v["label"], hint=v["hint"]) + for k, v in spec_data.LIFECYCLE.items()], + "tier": [dict(id=k, label=v["label"]) for k, v in spec_data.ADOPTION_TIER.items()], + "confirmed": [dict(id=k, label=v["label"], tone=v["tone"]) + for k, v in spec_data.CONFIRMED.items()], + "modes": [dict(id=k, label=v) for k, v in spec_data.MODES.items()], + "scopes": [dict(id=k, label=v) for k, v in spec_data.LICENCE_SCOPES.items()], + "licence_categories": [dict(id=k, label=v) + for k, v in spec_data.LICENCE_CATEGORIES.items()], + "licences": [dict(id=l["id"], name=l["name"], category=l["category"], url=l["url"], + note=l["note"]) for l in data["licences"].values()], + # No logo URLs: they point at other sites, which the privacy plugin + # keeps out of the published pages. The editor draws monograms. + "organizations": [dict(id=o["id"], name=o["name"], short=o["short"], url=o["url"], + type_label=o["type_label"]) + for o in sorted(data["organizations"].values(), + key=lambda o: o["name"].lower())], + "criteria": [dict(key=c["key"], label=c["label"]) for c in data["criteria"]], + "icons": dict((name, icon(name)) for name in EDIT_ICONS), + } + + def nice_ceiling(value): """A round number a little above `value`, for the top of a chart axis.""" import math @@ -942,7 +1113,7 @@ def history_labels(data): } icons = dict((name, icon(name)) for name in ( "source-pull", "source-merge", "source-commit", "plus-circle-outline", - "delete-outline", "open-in-new")) + "delete-outline", "open-in-new", "lightbulb-on-outline")) return {"fields": fields, "values": values, "icons": icons} @@ -1032,6 +1203,29 @@ def _collapse(html): return "\n".join(out) +def blank_spec(): + """A specification with nothing filled in, for the proposal page.""" + reg = spec_data.Registry() + spec = reg._clean_spec(NEW_SLUG, NEW_SLUG, {"status": "under_review"}, "") + spec.update(short_name="", slug=NEW_SLUG, modes=[], licences=[], + source_path=spec_data.entry_path(spec_data.SPECS_DIR, NEW_SLUG)) + return spec + + +NEW_META = """--- +title: Propose a specification +description: Propose a mobility specification for the MDIP registry. +robots: noindex +search: + exclude: true +hide: + - navigation + - toc +--- + +""" + + def on_files(files, config): data = spec_data.build_dataset() @@ -1055,6 +1249,10 @@ def on_files(files, config): files.append(File.generated( config, "%s/%s.md" % (SECTION, spec["slug"]), content=head + body)) + files.append(File.generated( + config, "%s/%s.md" % (SECTION, NEW_SLUG), + content=NEW_META + _collapse(render_detail(blank_spec(), data, "../../", new=True)))) + for path, text in spec_api.build_api(data, config.get("site_url")).items(): files.append(File.generated(config, path, content=text)) diff --git a/overrides/assets/javascript/spec-editor.js b/overrides/assets/javascript/spec-editor.js new file mode 100644 index 0000000..16d2f9c --- /dev/null +++ b/overrides/assets/javascript/spec-editor.js @@ -0,0 +1,1565 @@ +/* + * MDIP specification registry - in-page editor. + * + * "Suggest a change" at the foot of a specification page turns the page into + * an editor: a small edit button appears next to every value that comes from + * the specification's file (data/specifications/.md), and each opens a + * control that fits the field: a list for a verdict or a status, a licence + * picker, a year, a date, a URL. The page redraws the value as it would be + * published, so the person proposing the change sees the result. + * + * Values that follow from one another are kept consistent as they are edited + * (see `autoRules`): a criterion that is not compliant makes the MDIP status + * not compliant, a new adopters count takes today's date and the matching + * tier, a licence that requires a purchase fails "Free of cost restrictions". + * + * Nothing is written anywhere but GitHub. The change is sent as a pre-filled + * issue (.github/ISSUE_TEMPLATE/specification-edit.yml) that the person + * submits with their own GitHub account, and the coalition reviews it there. + * Until it is sent, the change is kept in this browser (localStorage), so + * signing in, creating an account or closing the tab does not lose it. + * + * The page works without this script: "Suggest a change" then opens the + * file in GitHub's own editor. + */ +(function () { + "use strict"; + + var SCRIPT_SRC = document.currentScript ? document.currentScript.src : ""; + var STORE = "mdip-edit:"; + /* GitHub refuses very long URLs; past this the proposal is pasted instead. */ + var URL_MAX = 7000; + var TONE_ICON = { + pass: "check-circle", warn: "alert-circle", fail: "close-circle", + info: "progress-clock", muted: "help-circle" + }; + var URL_FIELDS = /^(homepage_url|licence_evidence_url|adoption\.adopters_registry_url|principles\..+\.evidence_url)$/; + + function ready(fn) { + if (document.readyState !== "loading") { fn(); } + else { document.addEventListener("DOMContentLoaded", fn); } + } + + ready(function () { + var cfgEl = document.querySelector("[data-edit-config]"); + var root = document.querySelector(".mdip-spec"); + if (!cfgEl || !root) { return; } + var cfg; + try { cfg = JSON.parse(cfgEl.textContent); } catch (e) { return; } + editor(root, cfg); + }); + + function editor(root, cfg) { + var ICON = cfg.icons; + var CRITERIA = cfg.criteria.map(function (c) { return c.key; }); + var ORGS = index(cfg.organizations); + var LICENCES = index(cfg.licences); + var orig = normalise(cfg.front, cfg.description); + var doc = clone(orig); + var PATHS = fieldPaths(); + var editing = false; + var snapshot = null; + var pens = []; + var bar = null; + var pop = null; + /* On /specifications/new/ the page is blank and opens in the editor. The + registry id follows the short name until it is edited by hand. */ + var isNew = !!cfg["new"]; + var idByHand = false; + var ID_RE = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/; + if (isNew) { PATHS.unshift("id"); } + + if (isNew) { + start(false); + } else { + var startBtn = root.querySelector("[data-edit-start]"); + if (!startBtn) { return; } + startBtn.addEventListener("click", function (e) { + e.preventDefault(); + start(true); + }); + showDraftNotice(); + } + root.addEventListener("click", function (e) { + if (!editing || !e.target.closest) { return; } + /* While editing, a criterion stays open: its summary row holds controls. */ + if (e.target.closest("details.crit > summary")) { e.preventDefault(); } + /* An empty field is a place to click, like the edit button next to it. */ + var blank = e.target.closest(".sed-empty"); + var owner = blank && blank.closest("[data-edit]"); + if (owner && owner._pen) { + e.preventDefault(); + openEditor(owner.getAttribute("data-field"), owner._pen); + } + }); + + /* ================================================================ model */ + + function index(list) { + var out = {}; + list.forEach(function (x) { out[x.id] = x; }); + return out; + } + + function clone(v) { return JSON.parse(JSON.stringify(v)); } + + /* The file's values in the shapes the editor works with: licences as + {id, scopes}, lists as lists, and the description beside them. */ + function normalise(front, description) { + var d = clone(front || {}); + d.licences = [].concat(d.licences || []).filter(function (l) { return l !== null; }) + .map(function (l) { + if (typeof l !== "object") { return { id: String(l), scopes: [] }; } + return { id: String(l.id === undefined || l.id === null ? "" : l.id), + scopes: [].concat(l.scopes || []) }; + }); + d.modes = [].concat(d.modes || []); + d.maintainers = [].concat(d.maintainers || []); + d.adoption = isObj(d.adoption) ? d.adoption : {}; + d.principles = isObj(d.principles) ? d.principles : {}; + CRITERIA.forEach(function (k) { + if (!isObj(d.principles[k])) { d.principles[k] = {}; } + }); + d.description = description || ""; + return d; + } + + function fieldPaths() { + var p = ["short_name", "full_name", "description", "homepage_url", "status", "modes", + "maintainers", "licences", "licence_evidence_url", "first_release_year", + "adoption.lifecycle", "adoption.tier", "adoption.adopters_count", + "adoption.adopters_count_updated", "adoption.adopters_registry_url", + "adoption.confirmed_by_maintainer"]; + CRITERIA.forEach(function (k) { + ["verdict", "rationale", "evidence_url"].forEach(function (f) { + p.push("principles." + k + "." + f); + }); + }); + return p; + } + + function get(obj, path) { + var parts = path.split("."); + var v = obj; + for (var i = 0; i < parts.length; i++) { + if (!isObj(v)) { return undefined; } + v = v[parts[i]]; + } + return v; + } + + function set(obj, path, value) { + var parts = path.split("."); + var v = obj; + for (var i = 0; i < parts.length - 1; i++) { + if (!isObj(v[parts[i]])) { v[parts[i]] = {}; } + v = v[parts[i]]; + } + if (empty(value)) { delete v[parts[parts.length - 1]]; } + else { v[parts[parts.length - 1]] = value; } + } + + function empty(v) { + return v === undefined || v === null || v === "" || + (Array.isArray(v) && v.length === 0); + } + + /* Comparable form of a value: empty in any shape is one thing. */ + function key(v) { + if (empty(v)) { return ""; } + if (Array.isArray(v)) { + return JSON.stringify(v.map(function (x) { + return isObj(x) ? { id: x.id, scopes: (x.scopes || []).slice().sort(), url: x.url || "" } : x; + })); + } + return JSON.stringify(v); + } + + function changed(path) { return key(get(orig, path)) !== key(get(doc, path)); } + + function changes() { return PATHS.filter(changed); } + + function label(path) { return cfg.labels[path] || path; } + + /* ========================================================== consistency */ + + /* + * Run after the person edits `path`, before anything is redrawn. Each rule + * mirrors a rule of the registry (data/README.md): the status the verdicts + * imply, the tier an adopters count falls in, and the verdict a licence + * implies for "Free of cost restrictions". The person can still override + * any of these values afterwards. + */ + function autoRules(path) { + if (isNew && path === "id") { idByHand = !empty(get(doc, "id")); } + if (isNew && path === "short_name" && !idByHand) { set(doc, "id", slug(get(doc, path) || "")); } + if (path === "adoption.adopters_count") { + var n = get(doc, path); + if (typeof n === "number") { + set(doc, "adoption.adopters_count_updated", today()); + var tier = get(doc, "adoption.tier"); + if (n >= 100) { set(doc, "adoption.tier", "hundred_plus"); } + else if (n === 0) { set(doc, "adoption.tier", "none"); } + else if (!tier || tier === "hundred_plus" || tier === "none") { + set(doc, "adoption.tier", "early"); + } + } + } + if (path === "licences" && CRITERIA.indexOf("cost_restriction_free") !== -1) { + var cats = doc.licences.map(function (l) { + return LICENCES[l.id] ? LICENCES[l.id].category : "unknown"; + }); + var verdict = null; + if (cats.indexOf("closed") !== -1) { verdict = "not_compliant"; } + else if (cats.indexOf("restricted") !== -1) { verdict = "partially_compliant"; } + else if (cats.length && cats.every(function (c) { return c === "open"; })) { + verdict = "compliant"; + } + if (verdict) { set(doc, "principles.cost_restriction_free.verdict", verdict); } + } + if (path === "adoption.lifecycle") { + if (get(doc, path) === "inactive") { set(doc, "status", "inactive"); } + else if (get(doc, "status") === "inactive") { deriveStatus(true); } + } + if (/\.verdict$/.test(path) || path === "licences") { deriveStatus(false); } + } + + /* The status the verdicts imply, as `make specs-check` works it out. An + inactive project keeps its status; unknown verdicts imply nothing. */ + function deriveStatus(force) { + if (!force && get(doc, "status") === "inactive") { return; } + var v = CRITERIA.map(function (k) { + return get(doc, "principles." + k + ".verdict") || "not_assessed"; + }); + var all = function (ok) { return v.every(function (x) { return ok.indexOf(x) !== -1; }); }; + var status = null; + if (all(["compliant"])) { status = "compliant"; } + else if (v.indexOf("not_compliant") !== -1) { status = "not_compliant"; } + else if (all(["compliant", "partially_compliant"])) { status = "partially_compliant"; } + if (status) { set(doc, "status", status); } + } + + function slug(text) { + return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase() + .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); + } + + function idProblem(id) { + if (!id) { return "A registry id is required"; } + if (!ID_RE.test(id)) { return "Use lower case letters and digits, joined by - or _"; } + if (cfg.ids.indexOf(id) !== -1) { return "This id is already in the registry"; } + return ""; + } + + function today() { + var d = new Date(); + return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()); + } + + function pad(n) { return (n < 10 ? "0" : "") + n; } + + /* ============================================================ edit mode */ + + function bound() { + return Array.prototype.slice.call(root.querySelectorAll("[data-field]")); + } + + function start(scroll) { + if (editing) { return; } + editing = true; + takeSnapshot(); + var draft = readDraft(); + if (draft) { + Object.keys(draft.values).forEach(function (p) { + if (PATHS.indexOf(p) !== -1) { set(doc, p, draft.values[p]); } + }); + idByHand = isNew && !!draft.idByHand; + } + root.classList.add("is-editing"); + Array.prototype.forEach.call(root.querySelectorAll("[data-edit-only]"), function (el) { + el.hidden = false; + }); + Array.prototype.forEach.call(root.querySelectorAll("details.crit"), function (d) { + d.open = true; + }); + addPens(); + bound().forEach(function (el) { + var p = el.getAttribute("data-field"); + if (changed(p) || empty(get(doc, p))) { draw(el, p); } + }); + refreshDerived(); + markChanged(); + showBar(); + hideDraftNotice(); + if (scroll) { root.scrollIntoView({ behavior: "smooth", block: "start" }); } + } + + function stop() { + if (isNew) { + location.href = "../"; + return; + } + closePop(); + editing = false; + doc = clone(orig); + restoreSnapshot(); + root.classList.remove("is-editing"); + pens.forEach(function (p) { p.remove(); }); + pens = []; + if (bar) { bar.remove(); bar = null; } + document.body.classList.remove("sed-has-bar"); + showDraftNotice(); + } + + /* What the page looked like before editing, to put back on discard: the + server's markup, not a client redraw of it. */ + function takeSnapshot() { + snapshot = []; + var seen = []; + var keep = function (el) { + if (seen.indexOf(el) !== -1) { return; } + seen.push(el); + snapshot.push({ el: el, html: el.innerHTML, hidden: el.hidden, cls: el.className, + open: el.tagName === "DETAILS" ? el.open : null }); + }; + bound().forEach(keep); + Array.prototype.forEach.call(root.querySelectorAll( + "[data-edit-only], .crit, [data-view=meter], .spec-hero, .spec-hero__orgs"), keep); + Array.prototype.forEach.call(root.querySelectorAll(".crit__icon"), keep); + } + + function restoreSnapshot() { + (snapshot || []).forEach(function (s) { + s.el.innerHTML = s.html; + s.el.hidden = s.hidden; + s.el.className = s.cls; + if (s.open !== null) { s.el.open = s.open; } + }); + snapshot = null; + } + + function addPens() { + Array.prototype.forEach.call(root.querySelectorAll("[data-edit]"), function (el) { + var path = el.getAttribute("data-field"); + var b = document.createElement("button"); + b.type = "button"; + b.className = "sed-pen"; + b.setAttribute("aria-label", "Edit " + label(path)); + b.title = "Edit " + label(path).toLowerCase(); + b.innerHTML = ICON["pencil-outline"]; + b.addEventListener("click", function (e) { + e.preventDefault(); + e.stopPropagation(); + openEditor(path, b); + }); + el._pen = b; + if (el.getAttribute("data-view") === "block" || el.getAttribute("data-view") === "cards") { + el.classList.add("sed-block"); + } + el.appendChild(b); + pens.push(b); + }); + } + + /* After a change: redraw what differs from what is on screen, flash what + a rule changed on its own, save the draft. */ + function commit(path, value) { + var before = {}; + PATHS.forEach(function (p) { before[p] = key(get(doc, p)); }); + set(doc, path, value); + autoRules(path); + bound().forEach(function (el) { + var p = el.getAttribute("data-field"); + if (before[p] !== key(get(doc, p))) { + draw(el, p); + if (p !== path) { flash(el); } + } + }); + refreshDerived(); + markChanged(); + saveDraft(); + updateBar(); + } + + function flash(el) { + el.classList.remove("sed-flash"); + void el.offsetWidth; + el.classList.add("sed-flash"); + } + + function markChanged() { + bound().forEach(function (el) { + el.classList.toggle("is-changed", changed(el.getAttribute("data-field"))); + }); + } + + /* Parts of the page that follow from several fields. */ + function refreshDerived() { + var met = CRITERIA.filter(function (k) { + return get(doc, "principles." + k + ".verdict") === "compliant"; + }).length; + Array.prototype.forEach.call(root.querySelectorAll("[data-view=meter]"), function (el) { + el.innerHTML = meter(met, CRITERIA.length); + }); + Array.prototype.forEach.call(root.querySelectorAll("[data-crit]"), function (el) { + var v = vocab(cfg.verdict, get(doc, "principles." + el.getAttribute("data-crit") + ".verdict") + || "not_assessed"); + el.className = el.className.replace(/\bcrit--\w+/, "crit--" + v.tone); + var ico = el.querySelector(".crit__icon"); + if (ico) { ico.innerHTML = ICON[TONE_ICON[v.tone]]; } + }); + Array.prototype.forEach.call(root.querySelectorAll('[data-field=status][data-view=pill-met]'), + function (el) { draw(el, "status"); }); + var orgs = root.querySelector(".spec-hero__orgs"); + if (orgs) { orgs.hidden = empty(doc.maintainers); } + var hero = root.querySelector(".spec-hero"); + var st = vocab(cfg.status, get(doc, "status") || "under_review"); + if (hero) { hero.className = hero.className.replace(/\bspec-hero--\w+/, "spec-hero--" + st.tone); } + } + + /* ============================================================== drawing */ + + function draw(el, path) { + var v = get(doc, path); + var view = el.getAttribute("data-view") || ""; + var html = isNew && empty(v) && !/^(status|modes|licences|adoption\.confirmed_by_maintainer)$|\.verdict$/.test(path) + ? '' + esc(label(path)) + "" + : render(path, view, v); + el.innerHTML = html; + if (el._pen) { el.appendChild(el._pen); } + } + + function notSet(what) { + return '' + esc(what ? what + " not set" : "Not set") + ""; + } + + function render(path, view, v) { + if (path === "status") { + var st = vocab(cfg.status, v || "under_review"); + var h = pill(st.tone, st.label); + if (view === "pill-met") { + var met = CRITERIA.filter(function (k) { + return get(doc, "principles." + k + ".verdict") === "compliant"; + }).length; + h += '' + met + " of " + CRITERIA.length + + " criteria met"; + } + return h; + } + if (/\.verdict$/.test(path)) { + var vd = vocab(cfg.verdict, v || "not_assessed"); + return pill(vd.tone, vd.label); + } + if (/\.rationale$/.test(path) || path === "description") { + return empty(v) ? notSet() : paras(String(v), path === "description" ? "" : "crit__rationale"); + } + if (/\.evidence_url$/.test(path)) { return empty(v) ? notSet() : srclink(v, "Source", "srclink--crit"); } + if (path === "adoption.adopters_registry_url") { + return empty(v) ? notSet() : srclink(v, "Open registry"); + } + if (path === "licence_evidence_url") { + return empty(v) ? notSet("Licence text") : [].concat(v).map(function (u) { + return '

' + srclink(u, "Licence text") + "

"; + }).join(""); + } + if (path === "homepage_url") { + return empty(v) ? notSet() : '' + esc(v) + + ICON["open-in-new"] + ""; + } + if (path === "id") { return empty(v) ? notSet() : "" + esc(v) + ""; } + if (path === "short_name" || path === "full_name") { + return empty(v) ? notSet() : esc(v); + } + if (path === "modes") { + var modes = (v || []).map(function (m) { return vocab(cfg.modes, m).label; }); + if (!modes.length) { modes = ["Unclassified"]; } + return modes.map(function (m) { return '' + esc(m) + ""; }) + .join(" "); + } + if (path === "adoption.lifecycle") { + if (empty(v)) { return notSet(); } + var lc = vocab(cfg.lifecycle, v); + return '' + esc(lc.label) + '' + + esc(lc.hint || "") + ""; + } + if (path === "adoption.tier") { + return empty(v) ? notSet() : '' + esc(vocab(cfg.tier, v).label) + ""; + } + if (path === "adoption.confirmed_by_maintainer") { + var c = vocab(cfg.confirmed, v === true ? "yes" : v === false ? "no" : "unknown"); + return pill(c.tone, c.label); + } + if (path === "first_release_year") { + return empty(v) ? notSet() : "" + esc(v) + ""; + } + if (path === "adoption.adopters_count") { + return empty(v) ? notSet() : esc(Number(v).toLocaleString("en-US")); + } + if (path === "adoption.adopters_count_updated") { + return empty(v) ? notSet("Date") : "as of " + esc(v); + } + if (path === "licences") { return view === "cards" ? licenceCards(v) : licenceTags(v); } + if (path === "maintainers") { return view === "cards" ? orgCards(v) : orgChips(v); } + return empty(v) ? notSet() : esc(String(v)); + } + + function vocab(list, id) { + for (var i = 0; i < list.length; i++) { if (list[i].id === id) { return list[i]; } } + return { id: id, label: String(id), tone: "muted" }; + } + + function pill(tone, text) { + return '' + ICON[TONE_ICON[tone] || "help-circle"] + + "" + esc(text) + ""; + } + + function meter(met, total) { + var dots = ""; + for (var i = 0; i < total; i++) { dots += ''; } + return '' + dots + ""; + } + + function srclink(url, text, cls) { + return '' + + ICON["link-variant"] + "" + esc(text) + "" + ICON["open-in-new"] + ""; + } + + function paras(text, cls) { + return text.replace(/\r\n/g, "\n").split(/\n\s*\n/).filter(function (b) { return b.trim(); }) + .map(function (b) { + return '

' + esc(b.trim()).replace(/\n/g, "
") + "

"; + }).join(""); + } + + function licenceMeta(l) { + var m = LICENCES[l.id]; + if (m) { return m; } + if (!l.id) { return { id: "Unspecified", name: "No licence stated", category: "unknown" }; } + return { id: l.id, name: l.id, category: "unknown", url: l.url || null, other: true }; + } + + function licenceTags(list) { + if (!list || !list.length) { + return 'Unspecified'; + } + return list.map(function (l) { + var m = licenceMeta(l); + return '' + esc(m.id) + ""; + }).join(" "); + } + + function licenceCards(list) { + if (!list || !list.length) { list = [{ id: "", scopes: [] }]; } + return list.map(function (l) { + var m = licenceMeta(l); + var h = '
'; + h += m.url + ? '

' + esc(m.id) + "" + + ICON["open-in-new"] + "

" + : "

" + esc(m.id) + "

"; + if (l.scopes && l.scopes.length) { + h += '' + l.scopes.map(function (s) { + return '' + esc(vocab(cfg.scopes, s).label) + ""; + }).join(" ") + ""; + } + h += "
"; + if (m.name !== m.id) { h += '

' + esc(m.name) + "

"; } + if (m.note) { + h += '

' + ICON["information-outline"] + esc(m.note) + "

"; + } + return h + "
"; + }).join(""); + } + + function orgOf(id) { + return ORGS[id] || { id: id, name: id, short: id, url: null, + type_label: "Not in the registry yet" }; + } + + /* The generated monogram the page falls back on. Logos are left out: they + are hosted by each organization, and the editor loads nothing from + other sites. */ + function orgLogo(o) { + return '"; + } + + function hue(k) { + var h = 0; + for (var i = 0; i < k.length; i++) { h = (h * 31 + k.charCodeAt(i)) % 360; } + return h; + } + + function monogram(name) { + var words = name.replace(/-/g, " ").split(/\s+/).filter(function (w) { + return /^[A-Za-z0-9À-￿]/.test(w); + }); + if (!words.length) { return "?"; } + if (words.length === 1) { return words[0].slice(0, 2).toUpperCase(); } + return (words[0][0] + words[1][0]).toUpperCase(); + } + + function orgChips(list) { + return (list || []).map(function (id) { + var o = orgOf(id); + return '' + orgLogo(o) + "" + esc(o.name) + + ""; + }).join("") || notSet(); + } + + function orgCards(list) { + if (!list || !list.length) { return notSet(); } + return list.map(function (id) { + var o = orgOf(id); + var h = '"; + }).join(""); + } + + /* =============================================================== popover */ + + function closePop() { + if (!pop) { return; } + var back = pop._from; + pop.remove(); + pop = null; + document.removeEventListener("mousedown", outside, true); + document.removeEventListener("keydown", popKeys, true); + if (back && document.body.contains(back)) { back.focus(); } + } + + function outside(e) { + if (pop && !pop.contains(e.target) && e.target !== pop._from && + !(pop._from && pop._from.contains(e.target))) { + closePop(); + } + } + + function popKeys(e) { + if (e.key === "Escape" && pop) { + e.preventDefault(); + e.stopPropagation(); + closePop(); + } + } + + function makePop(path, from, wide) { + closePop(); + pop = document.createElement("div"); + pop.className = "sed-pop" + (wide ? " sed-pop--wide" : ""); + pop.setAttribute("role", "dialog"); + pop.setAttribute("aria-label", "Edit " + label(path)); + pop._from = from; + pop.innerHTML = '

' + esc(label(path)) + "

"; + root.appendChild(pop); + document.addEventListener("mousedown", outside, true); + document.addEventListener("keydown", popKeys, true); + return pop; + } + + function place() { + if (!pop) { return; } + var from = pop._from; + if (window.matchMedia("(max-width: 40em)").matches) { + pop.classList.add("sed-pop--sheet"); + return; + } + var r = root.getBoundingClientRect(); + var a = from.getBoundingClientRect(); + var w = pop.offsetWidth; + var left = Math.min(Math.max(a.left - r.left - 12, 12), r.width - w - 12); + pop.style.left = Math.max(left, 12) + "px"; + pop.style.top = (a.bottom - r.top + 6) + "px"; + /* Keep the whole control on screen when the value is low on the page. */ + var below = window.innerHeight - a.bottom; + if (below < pop.offsetHeight + 16 && a.top > pop.offsetHeight + 80) { + pop.style.top = (a.top - r.top - pop.offsetHeight - 6) + "px"; + } + } + + function footer(onApply) { + var f = document.createElement("div"); + f.className = "sed-pop__foot"; + f.innerHTML = '' + + '"; + f.querySelector("[data-cancel]").addEventListener("click", closePop); + f.querySelector("[data-apply]").addEventListener("click", onApply); + return f; + } + + function openEditor(path, from) { + if (path === "status") { + return listEditor(path, from, cfg.status.map(function (s) { + return { value: s.id, html: pill(s.tone, s.label) }; + }), get(doc, path) || "under_review"); + } + if (/\.verdict$/.test(path)) { + return listEditor(path, from, cfg.verdict.map(function (s) { + return { value: s.id, html: pill(s.tone, s.label) }; + }), get(doc, path) || "not_assessed"); + } + if (path === "adoption.confirmed_by_maintainer") { + var cv = get(doc, path); + return listEditor(path, from, cfg.confirmed.map(function (s) { + return { value: s.id === "yes" ? true : s.id === "no" ? false : null, + html: pill(s.tone, s.label) }; + }), cv === true || cv === false ? cv : null); + } + if (path === "adoption.lifecycle") { + return listEditor(path, from, cfg.lifecycle.map(function (s) { + return { value: s.id, html: '' + esc(s.label) + + '' + esc(s.hint) + "" }; + }).concat([unsetOption()]), get(doc, path) || null); + } + if (path === "adoption.tier") { + return listEditor(path, from, cfg.tier.map(function (s) { + return { value: s.id, html: '' + esc(s.label) + "" }; + }).concat([unsetOption()]), get(doc, path) || null); + } + if (path === "modes") { return modesEditor(path, from); } + if (path === "licences") { return licencesEditor(path, from); } + if (path === "maintainers") { return orgsEditor(path, from); } + if (path === "description" || /\.rationale$/.test(path)) { + return textEditor(path, from, "textarea"); + } + if (path === "licence_evidence_url") { return textEditor(path, from, "urls"); } + if (URL_FIELDS.test(path)) { return textEditor(path, from, "url"); } + if (path === "first_release_year") { return textEditor(path, from, "year"); } + if (path === "adoption.adopters_count") { return textEditor(path, from, "count"); } + if (path === "adoption.adopters_count_updated") { return textEditor(path, from, "date"); } + return textEditor(path, from, "text"); + } + + function unsetOption() { + return { value: null, html: 'Not set' }; + } + + /* One choice in a list: a custom listbox, applied as soon as it is + picked. Arrow keys, Home, End and Enter work as in a native select. */ + function listEditor(path, from, options, current) { + var p = makePop(path, from); + var ul = document.createElement("ul"); + ul.className = "sed-list"; + ul.setAttribute("role", "listbox"); + ul.setAttribute("tabindex", "0"); + ul.setAttribute("aria-label", label(path)); + var active = 0; + options.forEach(function (o, i) { + var li = document.createElement("li"); + li.className = "sed-opt"; + li.id = "sed-opt-" + i; + li.setAttribute("role", "option"); + var on = o.value === current; + li.setAttribute("aria-selected", on ? "true" : "false"); + li.innerHTML = '' + o.html + "" + + '' + (on ? ICON.check : "") + ""; + if (on) { active = i; } + li.addEventListener("click", function () { pick(i); }); + li.addEventListener("mousemove", function () { focusOpt(i); }); + ul.appendChild(li); + }); + p.appendChild(ul); + place(); + focusOpt(active); + ul.focus(); + ul.addEventListener("keydown", function (e) { + var n = options.length; + if (e.key === "ArrowDown") { e.preventDefault(); focusOpt((active + 1) % n); } + else if (e.key === "ArrowUp") { e.preventDefault(); focusOpt((active - 1 + n) % n); } + else if (e.key === "Home") { e.preventDefault(); focusOpt(0); } + else if (e.key === "End") { e.preventDefault(); focusOpt(n - 1); } + else if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(active); } + }); + + function focusOpt(i) { + active = i; + Array.prototype.forEach.call(ul.children, function (li, j) { + li.classList.toggle("is-active", j === i); + }); + ul.setAttribute("aria-activedescendant", "sed-opt-" + i); + var li = ul.children[i]; + if (li && li.scrollIntoView) { li.scrollIntoView({ block: "nearest" }); } + } + + function pick(i) { + var v = options[i].value; + closePop(); + if (v !== current) { commit(path, v); } + } + } + + function textEditor(path, from, kind) { + var p = makePop(path, from, kind === "textarea" || kind === "urls"); + var v = get(doc, path); + var field; + if (kind === "textarea" || kind === "urls") { + field = document.createElement("textarea"); + field.rows = path === "description" ? 9 : kind === "urls" ? 3 : 6; + field.value = kind === "urls" ? [].concat(v || []).join("\n") : (v || ""); + if (kind === "urls") { field.placeholder = "https://..., one per line"; } + } else { + field = document.createElement("input"); + field.type = { url: "url", year: "number", count: "number", date: "date" }[kind] || "text"; + if (kind === "url") { field.placeholder = "https://"; } + if (kind === "year") { field.min = 1900; field.max = new Date().getFullYear() + 1; field.step = 1; } + if (kind === "count") { field.min = 0; field.step = 1; } + field.value = empty(v) ? "" : String(v); + } + field.className = "sed-input"; + field.setAttribute("aria-label", label(path)); + var err = document.createElement("p"); + err.className = "sed-err"; + err.hidden = true; + p.appendChild(field); + p.appendChild(err); + p.appendChild(footer(apply)); + place(); + field.focus(); + if (field.select && kind !== "textarea") { field.select(); } + field.addEventListener("keydown", function (e) { + var multi = field.tagName === "TEXTAREA"; + if (e.key === "Enter" && (!multi || e.metaKey || e.ctrlKey)) { e.preventDefault(); apply(); } + }); + + function apply() { + var raw = field.value.trim(); + var out = raw; + var problem = ""; + if (kind === "url" && raw && !/^https?:\/\/\S+$/.test(raw)) { + problem = "Enter a full link starting with https://"; + } + if (kind === "urls") { + var urls = raw.split(/\s+/).filter(Boolean); + if (urls.some(function (u) { return !/^https?:\/\/\S+$/.test(u); })) { + problem = "Enter full links starting with https://"; + } + out = urls.length > 1 ? urls : urls[0] || ""; + } + if (kind === "year" && raw) { + out = Number(raw); + if (!/^\d{4}$/.test(raw)) { problem = "Enter a four-digit year"; } + } + if (kind === "count" && raw) { + out = Number(raw); + if (!/^\d+$/.test(raw)) { problem = "Enter a whole number"; } + } + if (path === "short_name" && !raw) { problem = "A short name is required"; } + if (path === "id") { problem = idProblem(raw); } + if (problem) { + err.textContent = problem; + err.hidden = false; + field.setAttribute("aria-invalid", "true"); + field.focus(); + return; + } + closePop(); + if (key(out) !== key(get(doc, path))) { commit(path, out); } + } + } + + function toggleChip(text, on) { + var b = document.createElement("button"); + b.type = "button"; + b.className = "sed-chip"; + b.setAttribute("aria-pressed", on ? "true" : "false"); + b.innerHTML = '' + ICON.check + "" + esc(text) + + ""; + b.addEventListener("click", function () { + b.setAttribute("aria-pressed", b.getAttribute("aria-pressed") === "true" ? "false" : "true"); + }); + return b; + } + + function modesEditor(path, from) { + var p = makePop(path, from, true); + var current = get(doc, path) || []; + var wrap = document.createElement("div"); + wrap.className = "sed-chips"; + cfg.modes.forEach(function (m) { + var b = toggleChip(m.label, current.indexOf(m.id) !== -1); + b.setAttribute("data-value", m.id); + wrap.appendChild(b); + }); + p.appendChild(wrap); + p.appendChild(footer(function () { + var out = Array.prototype.filter.call(wrap.children, function (b) { + return b.getAttribute("aria-pressed") === "true"; + }).map(function (b) { return b.getAttribute("data-value"); }); + closePop(); + if (key(out) !== key(current)) { commit(path, out); } + })); + place(); + wrap.firstChild.focus(); + } + + /* A search box over a list, used to pick a licence or an organization. + `items` are {value, text, html, group}; `other` offers a value that is + not in the list, built from what was typed. */ + function picker(items, opts) { + var box = document.createElement("div"); + box.className = "sed-pick"; + box.innerHTML = '
    '; + var input = box.querySelector("input"); + var ul = box.querySelector("ul"); + var shown = []; + var active = 0; + + function draw() { + var q = input.value.trim().toLowerCase(); + shown = items.filter(function (it) { + return !q || it.text.toLowerCase().indexOf(q) !== -1; + }).slice(0, 60); + if (opts.other && q && !items.some(function (it) { return it.text.toLowerCase() === q; })) { + shown.push({ value: null, other: input.value.trim(), + html: '' + ICON.plus + " " + esc(opts.otherLabel) + + ' "' + esc(input.value.trim()) + '"' }); + } + var group = null; + ul.innerHTML = ""; + shown.forEach(function (it, i) { + if (it.group && it.group !== group && !q) { + group = it.group; + var g = document.createElement("li"); + g.className = "sed-group"; + g.setAttribute("role", "presentation"); + g.textContent = group; + ul.appendChild(g); + } + var li = document.createElement("li"); + li.className = "sed-opt"; + li.setAttribute("role", "option"); + li.setAttribute("data-i", i); + li.innerHTML = '' + it.html + ""; + li.addEventListener("mousedown", function (e) { e.preventDefault(); }); + li.addEventListener("click", function () { choose(i); }); + ul.appendChild(li); + }); + if (!shown.length) { + ul.innerHTML = ''; + } + setActive(0); + } + + function setActive(i) { + active = i; + Array.prototype.forEach.call(ul.querySelectorAll(".sed-opt"), function (li) { + var on = Number(li.getAttribute("data-i")) === i; + li.classList.toggle("is-active", on); + if (on && li.scrollIntoView) { li.scrollIntoView({ block: "nearest" }); } + }); + } + + function choose(i) { + var it = shown[i]; + if (!it) { return; } + opts.onPick(it.other !== undefined ? { other: it.other } : { value: it.value }); + } + + input.addEventListener("input", draw); + input.addEventListener("keydown", function (e) { + if (e.key === "ArrowDown") { e.preventDefault(); setActive(Math.min(active + 1, shown.length - 1)); } + else if (e.key === "ArrowUp") { e.preventDefault(); setActive(Math.max(active - 1, 0)); } + else if (e.key === "Enter") { e.preventDefault(); choose(active); } + }); + draw(); + box.focusInput = function () { input.focus(); }; + return box; + } + + function licencesEditor(path, from) { + var p = makePop(path, from, true); + var rows = clone(get(doc, path) || []).map(function (l) { + var m = LICENCES[l.id]; + return { id: l.id, scopes: l.scopes || [], other: !m && !!l.id, url: l.url || "" }; + }); + var list = document.createElement("div"); + list.className = "sed-lics"; + var add = document.createElement("button"); + add.type = "button"; + add.className = "ghost sed-add"; + add.innerHTML = ICON.plus + "Add a licence"; + add.addEventListener("click", function () { + rows.push({ id: "", scopes: [], other: false, url: "" }); + drawRows(rows.length - 1); + }); + p.appendChild(list); + p.appendChild(add); + p.appendChild(footer(apply)); + + var cats = {}; + cfg.licence_categories.forEach(function (c) { cats[c.id] = c.label; }); + var items = cfg.licence_categories.reduce(function (acc, c) { + return acc.concat(cfg.licences.filter(function (l) { return l.category === c.id; }) + .map(function (l) { + return { value: l.id, text: l.id + " " + l.name, group: c.label, + html: '' + + '' + esc(l.id) + '' + + esc(l.name) + "" }; + })); + }, []); + + function drawRows(openIndex) { + list.innerHTML = ""; + rows.forEach(function (row, i) { + var el = document.createElement("div"); + el.className = "sed-lic"; + var m = LICENCES[row.id]; + var name = row.other ? row.id || "Other licence" : m ? m.id : "Choose a licence"; + var sub = row.other ? "Not in the list yet" : m ? m.name : ""; + var combo = document.createElement("button"); + combo.type = "button"; + combo.className = "sed-combo"; + combo.setAttribute("aria-expanded", "false"); + combo.innerHTML = '' + esc(name) + "" + + (sub ? "" + esc(sub) + "" : "") + "" + ICON["chevron-down"]; + var del = document.createElement("button"); + del.type = "button"; + del.className = "sed-icon"; + del.setAttribute("aria-label", "Remove " + name); + del.innerHTML = ICON["delete-outline"]; + del.addEventListener("click", function () { + rows.splice(i, 1); + drawRows(); + }); + var top = document.createElement("div"); + top.className = "sed-lic__top"; + top.appendChild(combo); + top.appendChild(del); + el.appendChild(top); + + if (row.other) { + var o = document.createElement("div"); + o.className = "sed-other"; + o.innerHTML = ''; + var ins = o.querySelectorAll("input"); + ins[0].value = row.id; + ins[1].value = row.url; + ins[0].addEventListener("input", function () { row.id = ins[0].value.trim(); }); + ins[1].addEventListener("input", function () { row.url = ins[1].value.trim(); }); + el.appendChild(o); + } + + var scopes = document.createElement("div"); + scopes.className = "sed-chips sed-chips--sm"; + cfg.scopes.forEach(function (s) { + var b = toggleChip(s.label, row.scopes.indexOf(s.id) !== -1); + b.addEventListener("click", function () { + var at = row.scopes.indexOf(s.id); + if (at === -1) { row.scopes.push(s.id); } else { row.scopes.splice(at, 1); } + }); + scopes.appendChild(b); + }); + el.appendChild(scopes); + + var pick = null; + combo.addEventListener("click", function () { + if (pick) { + pick.remove(); + pick = null; + combo.setAttribute("aria-expanded", "false"); + return; + } + pick = picker(items, { + placeholder: "Search licences", + other: true, + otherLabel: "Other licence", + onPick: function (r) { + if (r.other !== undefined) { + row.id = r.other; + row.other = true; + } else { + row.id = r.value; + row.other = false; + row.url = ""; + } + drawRows(); + } + }); + top.insertAdjacentElement("afterend", pick); + combo.setAttribute("aria-expanded", "true"); + pick.focusInput(); + }); + list.appendChild(el); + if (openIndex === i) { combo.click(); } + }); + place(); + } + + function apply() { + var out = rows.filter(function (r) { return r.id; }).map(function (r) { + var l = { id: r.id, scopes: r.scopes.slice() }; + if (r.other && r.url) { l.url = r.url; } + return l; + }); + closePop(); + if (key(out) !== key(get(doc, path))) { commit(path, out); } + } + + if (rows.length) { + drawRows(-1); + list.querySelector(".sed-combo").focus(); + } else { + rows.push({ id: "", scopes: [], other: false, url: "" }); + drawRows(0); + } + } + + function orgsEditor(path, from) { + var p = makePop(path, from, true); + var chosen = (get(doc, path) || []).slice(); + var chips = document.createElement("div"); + chips.className = "sed-picked"; + p.appendChild(chips); + var holder = document.createElement("div"); + p.appendChild(holder); + p.appendChild(footer(function () { + closePop(); + if (key(chosen) !== key(get(doc, path))) { commit(path, chosen); } + })); + + function drawChips() { + chips.innerHTML = ""; + chosen.forEach(function (id, i) { + var o = orgOf(id); + var c = document.createElement("span"); + c.className = "sed-picked__c"; + c.innerHTML = orgLogo(o) + "" + esc(o.name) + ""; + var x = document.createElement("button"); + x.type = "button"; + x.className = "sed-icon sed-icon--sm"; + x.setAttribute("aria-label", "Remove " + o.name); + x.innerHTML = ICON.close; + x.addEventListener("click", function () { + chosen.splice(i, 1); + redraw(); + }); + c.appendChild(x); + chips.appendChild(c); + }); + } + + function redraw() { + drawChips(); + holder.innerHTML = ""; + var items = cfg.organizations.filter(function (o) { return chosen.indexOf(o.id) === -1; }) + .map(function (o) { + return { value: o.id, text: o.name + " " + o.short + " " + o.id, + html: orgLogo(o) + '' + esc(o.name) + "" }; + }); + var pk = picker(items, { + placeholder: "Search organizations", + other: true, + otherLabel: "Add", + onPick: function (r) { + chosen.push(r.other !== undefined ? r.other : r.value); + redraw(); + } + }); + holder.appendChild(pk); + place(); + pk.focusInput(); + } + redraw(); + } + + /* ============================================================ edit bar */ + + function showBar() { + bar = document.createElement("div"); + bar.className = "sed-bar"; + bar.setAttribute("role", "region"); + bar.setAttribute("aria-label", "Suggest a change"); + bar.innerHTML = '
    ' + ICON["pencil-outline"] + + "" + (isNew ? "New specification" : "Editing " + esc(cfg.name) + "") + + "" + + '' + + '" + + '
    "; + root.appendChild(bar); + document.body.classList.add("sed-has-bar"); + var discard = bar.querySelector("[data-discard]"); + var armed = null; + discard.addEventListener("click", function () { + if (!changes().length || armed) { + clearTimeout(armed); + clearDraft(); + stop(); + return; + } + discard.querySelector("span").textContent = "Discard " + plural(changes().length) + "?"; + armed = setTimeout(function () { + armed = null; + if (discard.isConnected) { discard.querySelector("span").textContent = "Discard"; } + }, 3500); + }); + bar.querySelector("[data-review]").addEventListener("click", review); + updateBar(); + } + + function plural(n) { return n + (n === 1 ? " change" : " changes"); } + + function updateBar() { + if (!bar) { return; } + var n = changes().length; + bar.querySelector("[data-n]").textContent = n ? plural(n) : ""; + bar.querySelector("[data-review]").disabled = n === 0 || + (isNew && (empty(get(doc, "short_name")) || !!idProblem(get(doc, "id") || ""))); + } + + /* ============================================================== drafts */ + + function storeKey() { return STORE + (isNew ? "+new" : cfg.id); } + + function saveDraft() { + var values = {}; + changes().forEach(function (p) { + var v = get(doc, p); + values[p] = v === undefined ? null : v; + }); + try { + if (Object.keys(values).length) { + localStorage.setItem(storeKey(), JSON.stringify({ t: Date.now(), values: values, + idByHand: idByHand })); + } else { + localStorage.removeItem(storeKey()); + } + } catch (e) { /* storage off: the change lives as long as the tab */ } + } + + function readDraft() { + try { + var d = JSON.parse(localStorage.getItem(storeKey())); + return d && d.values && Object.keys(d.values).length ? d : null; + } catch (e) { return null; } + } + + function clearDraft() { + try { localStorage.removeItem(storeKey()); } catch (e) { /* nothing kept */ } + } + + function showDraftNotice() { + hideDraftNotice(); + var d = readDraft(); + var box = root.querySelector(".contribute"); + if (!d || !box) { return; } + var n = Object.keys(d.values).length; + var note = document.createElement("div"); + note.className = "sed-draft"; + note.innerHTML = ICON["progress-clock"] + "Your suggestion (" + plural(n) + + ") has not been sent yet." + + '" + + ''; + note.querySelector("[data-resume]").addEventListener("click", function () { start(true); }); + note.querySelector("[data-drop]").addEventListener("click", function () { + clearDraft(); + hideDraftNotice(); + }); + box.insertBefore(note, box.firstChild); + } + + function hideDraftNotice() { + var n = root.querySelector(".sed-draft"); + if (n) { n.remove(); } + } + + /* ======================================================== review + send */ + + function shown(path, v) { + if (empty(v)) { return ""; } + if (path === "status") { return vocab(cfg.status, v).label; } + if (/\.verdict$/.test(path)) { return vocab(cfg.verdict, v).label; } + if (path === "adoption.lifecycle") { return vocab(cfg.lifecycle, v).label; } + if (path === "adoption.tier") { return vocab(cfg.tier, v).label; } + if (path === "adoption.confirmed_by_maintainer") { return v === true ? "Yes" : "No"; } + if (path === "modes") { return v.map(function (m) { return vocab(cfg.modes, m).label; }).join(", "); } + if (path === "maintainers") { return v.map(function (id) { return orgOf(id).name; }).join(", "); } + if (path === "licences") { + return v.map(function (l) { + return l.id + (l.scopes && l.scopes.length ? " (" + l.scopes.join(", ") + ")" : ""); + }).join(", "); + } + if (path === "adoption.adopters_count") { return Number(v).toLocaleString("en-US"); } + return Array.isArray(v) ? v.join(", ") : String(v); + } + + function rows() { + return changes().map(function (p) { + return { path: p, label: label(p), before: shown(p, get(orig, p)), after: shown(p, get(doc, p)) }; + }); + } + + /* The change as it would be written in the file: only the keys that + change, nested the way the file nests them. */ + function patch() { + var out = {}; + changes().forEach(function (p) { + if (p === "description" || p === "id") { return; } + var v = get(doc, p); + if (p === "licences") { + v = (v || []).map(function (l) { + var o = { id: l.id }; + if (l.scopes && l.scopes.length) { o.scopes = l.scopes; } + return o; + }); + } + var parts = p.split("."); + var at = out; + for (var i = 0; i < parts.length - 1; i++) { + at[parts[i]] = at[parts[i]] || {}; + at = at[parts[i]]; + } + at[parts[parts.length - 1]] = empty(v) ? null : v; + }); + return out; + } + + function yamlOf(obj) { + if (!Object.keys(obj).length) { return ""; } + return window.jsyaml.dump(obj, { lineWidth: -1, noRefs: true, flowLevel: -1 }) + .replace(/: null$/gm, ":") + .trim(); + } + + function cellText(s) { + s = String(s || "").replace(/\s+/g, " ").trim(); + if (s.length > 120) { s = s.slice(0, 117).replace(/\s+\S*$/, "") + "..."; } + return s ? s.replace(/\|/g, "\\|") : "_not set_"; + } + + /* The whole file for a new specification, laid out like the others, with + every field present so the reviewer sees what is still empty. */ + function newFile() { + var a = doc.adoption || {}; + var f = { + short_name: doc.short_name || null, + full_name: doc.full_name || null, + homepage_url: doc.homepage_url || null, + status: doc.status || "under_review", + modes: doc.modes || [], + maintainers: doc.maintainers || [], + licences: (doc.licences || []).map(function (l) { + var o = { id: l.id }; + if (l.scopes && l.scopes.length) { o.scopes = l.scopes; } + return o; + }) + }; + if (!empty(doc.licence_evidence_url)) { f.licence_evidence_url = doc.licence_evidence_url; } + f.first_release_year = empty(doc.first_release_year) ? null : doc.first_release_year; + f.adoption = { lifecycle: a.lifecycle || null, tier: a.tier || null }; + ["adopters_count", "adopters_count_updated", "adopters_registry_url", + "confirmed_by_maintainer"].forEach(function (k) { + if (!empty(a[k])) { f.adoption[k] = a[k]; } + }); + f.principles = {}; + CRITERIA.forEach(function (k) { + var c = doc.principles[k] || {}; + f.principles[k] = { verdict: c.verdict || "not_assessed", rationale: c.rationale || null, + evidence_url: c.evidence_url || null }; + }); + return "---\n" + yamlOf(f) + "\n---\n\n# Description\n\n" + + (doc.description || "").trim() + "\n"; + } + + function filePath() { + return isNew ? "data/specifications/" + (doc.id || "new-specification") + ".md" : cfg.path; + } + + function proposal(withTable) { + var parts = []; + if (withTable) { + parts.push("| Field | Now | Suggested |\n| --- | --- | --- |\n" + rows().map(function (r) { + return "| " + cellText(r.label) + " | " + cellText(r.before) + " | " + cellText(r.after) + " |"; + }).join("\n")); + } + if (isNew) { + parts.push("New file `" + filePath() + "`:\n\n````markdown\n" + newFile() + "````"); + } + var y = isNew ? "" : yamlOf(patch()); + if (y) { parts.push("In `" + cfg.path + "`:\n\n```yaml\n" + y + "\n```"); } + if (!isNew && changed("description")) { + parts.push("`# Description`:\n\n```markdown\n" + (doc.description || "") + "\n```"); + } + var extra = []; + (doc.licences || []).forEach(function (l) { + if (l.id && !LICENCES[l.id]) { + extra.push("- New licence, not yet in `data/licences.csv`: " + l.id + (l.url ? " (" + l.url + ")" : "")); + } + }); + (doc.maintainers || []).forEach(function (id) { + if (!ORGS[id]) { extra.push("- New maintainer, not yet in `data/organizations/`: " + id); } + }); + if (extra.length) { parts.push(extra.join("\n")); } + return parts.join("\n\n"); + } + + function issueUrl(sources) { + var base = "https://github.com/" + cfg.repo + "/issues/new"; + var params = function (change) { + return "?template=" + encodeURIComponent(cfg.template) + + "&title=" + encodeURIComponent(isNew ? "New specification: " + (doc.short_name || "") + : "Suggested change: " + cfg.name) + + "&spec_id=" + encodeURIComponent(isNew ? doc.id || "" : cfg.id) + + "&change=" + encodeURIComponent(change) + + (sources ? "&evidence=" + encodeURIComponent(sources) : ""); + }; + var url = base + params(proposal(true)); + if (url.length > URL_MAX) { url = base + params(proposal(false)); } + if (url.length > URL_MAX) { + url = base + params("Paste the suggestion copied from the registry page here."); + return { url: url, paste: true }; + } + return { url: url, paste: false }; + } + + function review() { + closePop(); + loadYaml().then(openDialog, function () { openDialog(); }); + } + + function openDialog() { + var dlg = document.createElement("dialog"); + dlg.className = "sed-dialog"; + dlg.setAttribute("aria-labelledby", "sed-dialog-title"); + var table = rows().map(function (r) { + return '' + esc(r.label) + "" + cell(r.before, "old") + + cell(r.after, "new") + ""; + }).join(""); + dlg.innerHTML = + '
    ' + + '
    ' + + '

    ' + (isNew ? "Review your proposal" : "Review your suggestion") + + "

    " + + '
    ' + + '' + table + + "
    FieldNowSuggested
    " + + '' + + '' + + '
    ' + ICON.github + "

    Suggestions are sent and discussed on GitHub. " + + 'No account? Create one for free, your suggestion stays ' + + "saved here meanwhile.

    " + + '
    " + + '
    " + + '" + + "
    "; + root.appendChild(dlg); + var sources = dlg.querySelector("#sed-sources"); + var target = null; + + function go(viaSignup) { + target = issueUrl(sources.value.trim()); + if (target.paste) { copy(proposal(true)); } + /* After signing up, GitHub returns to the pre-filled form. */ + var url = viaSignup + ? "https://github.com/signup?return_to=" + + encodeURIComponent(target.url.replace("https://github.com", "")) + : target.url; + window.open(url, "_blank", "noopener"); + dlg.querySelector('[data-step="review"]').hidden = true; + dlg.querySelector('[data-step="sent"]').hidden = false; + dlg.querySelector(".sed-paste").hidden = !target.paste; + } + + dlg.querySelector("[data-send]").addEventListener("click", function () { go(false); }); + dlg.querySelector("[data-signup]").addEventListener("click", function (e) { + e.preventDefault(); + go(true); + }); + dlg.querySelector("[data-back]").addEventListener("click", function () { dlg.close(); }); + dlg.querySelector("[data-again]").addEventListener("click", function () { + window.open(target.url, "_blank", "noopener"); + }); + dlg.querySelector("[data-copy]").addEventListener("click", function (e) { + var b = e.currentTarget; + copy(proposal(true)).then(function () { + b.querySelector("span").textContent = "Copied"; + setTimeout(function () { b.querySelector("span").textContent = "Copy suggestion"; }, 2000); + }); + }); + dlg.querySelector("[data-done]").addEventListener("click", function () { + clearDraft(); + dlg.close(); + if (isNew) { location.href = "../"; } else { stop(); } + }); + dlg.addEventListener("close", function () { dlg.remove(); }); + dlg.showModal(); + } + + function cell(value, kind) { + if (!value) { return 'Not set'; } + var short = value.length > 160 ? value.slice(0, 158).replace(/\s+\S*$/, "") + "..." : value; + return '' + esc(short) + ""; + } + + function copy(text) { + if (navigator.clipboard && navigator.clipboard.writeText) { + return navigator.clipboard.writeText(text).catch(function () { return legacyCopy(text); }); + } + return Promise.resolve(legacyCopy(text)); + } + + function legacyCopy(text) { + var t = document.createElement("textarea"); + t.value = text; + t.style.position = "fixed"; + t.style.opacity = "0"; + document.body.appendChild(t); + t.select(); + try { document.execCommand("copy"); } catch (e) { /* nothing more to try */ } + t.remove(); + } + } + + /* js-yaml, served next to this script, to write the change as YAML. */ + var yamlLoad = null; + function loadYaml() { + if (window.jsyaml) { return Promise.resolve(); } + if (!yamlLoad) { + yamlLoad = new Promise(function (resolve, reject) { + var s = document.createElement("script"); + s.src = SCRIPT_SRC.replace(/[^/]*$/, "") + "vendor/js-yaml.min.js"; + s.onload = resolve; + s.onerror = reject; + document.head.appendChild(s); + }); + } + return yamlLoad; + } + + function isObj(v) { return v && typeof v === "object" && !Array.isArray(v); } + + function esc(s) { + return String(s === undefined || s === null ? "" : s) + .replace(/&/g, "&").replace(//g, ">") + .replace(/"/g, """); + } +})(); diff --git a/overrides/assets/javascript/specifications.js b/overrides/assets/javascript/specifications.js index 2a3adb4..c568ea7 100644 --- a/overrides/assets/javascript/specifications.js +++ b/overrides/assets/javascript/specifications.js @@ -421,6 +421,62 @@ readState(); apply(false); + initPanelScroll(root, panel); + } + + /* + * The filter panel on a wide screen: sticky, with no scrollbar of its own. + * + * A sticky element taller than the window would hide its last filters, so + * its `top` follows the scroll instead of staying fixed. Scrolling down, + * `top` decreases by as much as the page moved, so the panel travels with + * the page until its bottom edge is in view, and then stays there. + * Scrolling up, `top` increases the same way, so the panel comes back with + * the page at once rather than waiting for the top of the list, until it + * sits under the header again. A panel shorter than the window simply + * sticks under the header. The drawer used on narrow screens keeps its + * own scroll and is not touched. + */ + function initPanelScroll(root, panel) { + var wide = window.matchMedia("(min-width: 60em)"); + var GAP = 16; + var top = null; + var lastY = window.pageYOffset; + + function bounds() { + var hdr = parseFloat(getComputedStyle(root).getPropertyValue("--hdr")) || 0; + if (/rem$/.test(getComputedStyle(root).getPropertyValue("--hdr").trim())) { + hdr *= parseFloat(getComputedStyle(document.documentElement).fontSize); + } + var max = hdr + GAP; + var min = Math.min(max, window.innerHeight - panel.offsetHeight - GAP); + return [min, max]; + } + + function update() { + if (!wide.matches) { + root.style.removeProperty("--panel-top"); + top = null; + lastY = window.pageYOffset; + return; + } + var b = bounds(); + var y = window.pageYOffset; + if (top === null) { top = b[1]; } + top = Math.max(b[0], Math.min(b[1], top - (y - lastY))); + lastY = y; + root.style.setProperty("--panel-top", top + "px"); + } + + /* Set straight from the scroll event, not a later frame, so the panel + and the page move together. */ + window.addEventListener("scroll", update, { passive: true }); + window.addEventListener("resize", update); + if ("ResizeObserver" in window) { + /* Opening or closing a filter changes the panel's height. */ + new ResizeObserver(update).observe(panel); + } + update(); } /* ----------------------------------------------------------------- detail */ @@ -464,11 +520,14 @@ * API in the browser so that an open pull request shows up as soon as it * exists, without waiting for the site to be rebuilt. * - * Two lists: pull requests still open on this entry's file ("Review in - * progress"), then the last MAX_CHANGES changes merged into the branch the - * site is built from. What a change did is worked out by reading the file - * before and after it (raw.githubusercontent.com, which has no rate limit) - * and comparing the two field by field. + * Two lists: what is proposed and not merged yet (pull requests open on + * this entry's file, and changes suggested from the page's editor, which + * arrive as issues), then the last MAX_CHANGES changes merged into the + * branch the site is built from. What a change did is worked out by + * reading the file before and after it (raw.githubusercontent.com, which + * has no rate limit) and comparing the two field by field. Each change + * names who proposed it, who took part in the discussion, and who approved + * or merged it, read from the conversation's timeline. * * Without a token GitHub allows 60 API calls an hour per visitor, so every * answer is kept in sessionStorage for a few minutes and shared between @@ -480,6 +539,8 @@ var MAX_ROWS = 6; var EXCERPT = 180; var CACHE_MS = 10 * 60 * 1000; + /* A merged change's conversation is over: its people are kept longer. */ + var DAY_MS = 24 * 60 * 60 * 1000; function initHistory() { var root = document.querySelector("[data-history]"); @@ -496,27 +557,40 @@ body.innerHTML = '

    Loading changes from GitHub...

    '; - Promise.all([loadYaml(), openProposals(api, path), mergedChanges(api, repo, branch, path)]) + var specId = path.replace(/^.*\//, "").replace(/\.md$/, ""); + + Promise.all([loadYaml(), openProposals(api, path), mergedChanges(api, repo, branch, path), + suggestions(api, specId)]) .then(function (res) { var open = res[1]; var merged = res[2]; + var suggested = res[3]; return Promise.all([ Promise.all(open.map(function (pr) { - return diffOf( - raw(repo, pr.base, path), - raw(pr.headRepo || repo, pr.head, path) - ).then(function (d) { pr.diff = d; return pr; }); + return Promise.all([ + diffOf(raw(repo, pr.base, path), raw(pr.headRepo || repo, pr.head, path)), + participants(api, pr.number, pr.head) + ]).then(function (r) { pr.diff = r[0]; pr.people = r[1]; return pr; }); })), Promise.all(merged.map(function (ch) { - return diffOf( - ch.parent ? raw(repo, ch.parent, path) : Promise.resolve(null), - raw(repo, ch.sha, path) - ).then(function (d) { ch.diff = d; return ch; }); + return Promise.all([ + diffOf( + ch.parent ? raw(repo, ch.parent, path) : Promise.resolve(null), + raw(repo, ch.sha, path) + ), + ch.pr ? participants(api, ch.pr, "merged", DAY_MS) : null + ]).then(function (r) { ch.diff = r[0]; ch.people = r[1]; return ch; }); + })), + Promise.all(suggested.map(function (is) { + return Promise.all([ + suggestionDiff(raw(repo, branch, path), is.body), + participants(api, is.number, is.updated) + ]).then(function (r) { is.diff = r[0]; is.people = r[1]; return is; }); })) ]); }) .then(function (lists) { - body.innerHTML = render(lists[0], lists[1]); + body.innerHTML = render(lists[2].concat(lists[0]), lists[1]); }) .catch(function () { body.innerHTML = '

    Recent changes could not be loaded from GitHub ' + @@ -534,10 +608,11 @@ h += '

    Proposed changes

      ' + open.map(function (pr) { return item({ - tone: "info", ico: "source-pull", status: "Review in progress", + tone: "info", ico: pr.issue ? "lightbulb-on-outline" : "source-pull", + status: pr.issue ? "Suggested change" : "Review in progress", title: pr.title, number: pr.number, url: pr.url, date: pr.created, - people: [["Change proposed by", pr.user]], - text: pr.body, diff: pr.diff, after: "Proposed", folded: false + people: people(pr, null), + text: pr.issue ? "" : pr.body, diff: pr.diff, after: "Proposed", folded: false }); }).join("") + "
    "; } @@ -550,9 +625,7 @@ ico: added ? "plus-circle-outline" : ch.pr ? "source-merge" : "source-commit", status: added ? "Added to the registry" : ch.pr ? "Merged" : "Committed", title: ch.title, number: ch.pr, url: ch.url, date: ch.date, - people: ch.pr - ? [["Change proposed by", ch.user], ["Change merged by", ch.mergedBy]] - : [["Changed by", ch.user]], + people: ch.pr ? people(ch, ch.mergedBy) : [["Changed by", [ch.user]]], text: ch.body, diff: added ? null : ch.diff, after: "After", folded: true }); }).join("") + ""; @@ -572,11 +645,12 @@ h += '' + "" + esc(it.title) + "" + (it.number ? '#' + it.number + "" : "") + ""; - var people = it.people.filter(function (p) { return p[1]; }); - if (people.length) { - h += '

    ' + people.map(function (p) { - return "" + esc(p[0]) + ' @' + - esc(p[1].login) + ""; + var who = it.people.map(function (p) { + return [p[0], (p[1] || []).filter(Boolean)]; + }).filter(function (p) { return p[1].length; }); + if (who.length) { + h += '

    ' + who.map(function (p) { + return "" + esc(p[0]) + " " + names(p[1], it.url) + ""; }).join("") + "

    "; } var text = excerpt(it.text); @@ -595,6 +669,39 @@ return h + ""; } + /* + * Who took part, in the order the page reads them: the person who + * proposed the change, the people who commented or reviewed without + * approving, then who approved it. Who merged it is only named when + * nobody approved it, since an approval already says who signed off. + */ + function people(ch, mergedBy) { + var p = ch.people || { commenters: [], approvers: [] }; + var proposer = ch.user ? ch.user.login : ""; + var approvers = p.approvers.filter(function (u) { return u.login !== proposer; }); + var taken = [proposer].concat(approvers.map(function (u) { return u.login; })); + var commenters = p.commenters.filter(function (u) { return taken.indexOf(u.login) === -1; }); + var out = [[ch.issue ? "Suggested by" : "Change proposed by", [ch.user]], + ["Discussed with", commenters], ["Approved by", approvers]]; + if (!approvers.length && mergedBy) { out.push(["Merged by", [mergedBy]]); } + return out; + } + + /* "@a", "@a and @b", "@a, @b and @c", "@a, @b, @c and 4 more": past + three names the rest is a link to the conversation on GitHub. */ + function names(list, url) { + var shown = list.slice(0, 3).map(function (u) { + return '@' + esc(u.login) + ""; + }); + var rest = list.length - shown.length; + if (rest > 0) { + return shown.join(", ") + ' and ' + rest + + " more"; + } + if (shown.length < 2) { return shown.join(""); } + return shown.slice(0, -1).join(", ") + " and " + shown[shown.length - 1]; + } + function diffTable(rows, after, url) { var shown = rows.slice(0, MAX_ROWS); var h = '
    ' + @@ -629,28 +736,82 @@ var a = flatten(texts[0]); var b = flatten(texts[1]); if (!a || !b) { return null; } - var keys = Object.keys(cfg.fields).filter(function (k) { return k in a || k in b; }); - Object.keys(a).concat(Object.keys(b)).forEach(function (k) { - if (keys.indexOf(k) < 0) { keys.push(k); } - }); - var rows = []; - keys.forEach(function (k) { - var x = show(k, a[k]); - var y = show(k, b[k]); - if (x !== y) { rows.push({ label: cfg.fields[k] || k, before: x, after: y }); } - }); - return { rows: rows }; + return compare(a, b); + }); + } + + /* + * A change suggested from the page's editor is an issue, not a branch: + * its body holds the keys that change as a YAML block (and the new + * description, if any). Laid over the file as it is now, it gives the + * "after" side. + */ + function suggestionDiff(currentP, body) { + return currentP.then(function (text) { + if (!text) { return null; } + var parts = split(text); + if (!parts) { return null; } + var y = /```ya?ml\n([\s\S]*?)\n```/.exec(body || ""); + var d = /`# Description`:\s*```markdown\n([\s\S]*?)\n```/.exec(body || ""); + var patch; + try { patch = y ? window.jsyaml.load(y[1], { schema: window.jsyaml.CORE_SCHEMA }) : {}; } + catch (e) { return null; } + if (!isObj(patch)) { return null; } + var after = overlay(parts.front, patch); + return compare(flattenObj(parts.front, parts.description), + flattenObj(after, d ? d[1].trim() : parts.description)); + }); + } + + /* `patch` laid over `base`: mappings merge key by key, anything else + (a value, a list) replaces, and an empty value removes the key. */ + function overlay(base, patch) { + var out = isObj(base) ? JSON.parse(JSON.stringify(base)) : {}; + Object.keys(patch).forEach(function (k) { + var v = patch[k]; + if (v === null || v === "") { delete out[k]; } + else if (isObj(v) && isObj(out[k])) { out[k] = overlay(out[k], v); } + else { out[k] = v; } + }); + return out; + } + + /* The fields that differ between two flattened versions, in the order + the page lists them. */ + function compare(a, b) { + var keys = Object.keys(cfg.fields).filter(function (k) { return k in a || k in b; }); + Object.keys(a).concat(Object.keys(b)).forEach(function (k) { + if (keys.indexOf(k) < 0) { keys.push(k); } + }); + var rows = []; + keys.forEach(function (k) { + var x = show(k, a[k]); + var y = show(k, b[k]); + if (x !== y) { rows.push({ label: cfg.fields[k] || k, before: x, after: y }); } }); + return { rows: rows }; } /* The file's fields as { "dotted.path": value }, plus its description. */ function flatten(text) { + var parts = split(text); + return parts ? flattenObj(parts.front, parts.description) : null; + } + + /* The file as {front, description}, or null if it cannot be read. */ + function split(text) { text = text.replace(/\r\n/g, "\n"); var m = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(text); if (!m) { return null; } var front; try { front = window.jsyaml.load(m[1], { schema: window.jsyaml.CORE_SCHEMA }) || {}; } catch (e) { return null; } + if (!isObj(front)) { return null; } + var d = /^#\s+Description\s*$([\s\S]*?)(?=^#\s|$(?![\s\S]))/m.exec(m[2]); + return { front: front, description: d ? d[1].trim() : "" }; + } + + function flattenObj(front, description) { var out = {}; Object.keys(front).forEach(function (k) { var v = front[k]; @@ -673,8 +834,7 @@ out[k] = v; } }); - var d = /^#\s+Description\s*$([\s\S]*?)(?=^#\s|$(?![\s\S]))/m.exec(m[2]); - out.description = d ? d[1].trim() : ""; + out.description = description || ""; return out; } @@ -795,6 +955,64 @@ return u && u.login ? { login: u.login, url: u.html_url } : null; } + function isBot(u) { + return !u || u.type === "Bot" || /\[bot\]$/.test(u.login || ""); + } + + /* + * Everyone who took part in a pull request or an issue, from its timeline: + * one call returns the comments, the reviews and the inline review + * comments together. A review that approves makes its author an approver; + * any other comment or review makes its author a commenter. Bots are left + * out. If the timeline cannot be read, the change still shows, with only + * who proposed it. + */ + function participants(api, number, version, ttl) { + return getJSON(api + "/issues/" + number + "/timeline?per_page=100", function (events) { + var commenters = []; + var approvers = []; + var add = function (list, u) { + if (isBot(u)) { return; } + if (!list.some(function (p) { return p.login === u.login; })) { list.push(person(u)); } + }; + (events || []).forEach(function (e) { + if (e.event === "reviewed") { + var state = String(e.state || "").toLowerCase(); + add(state === "approved" ? approvers : commenters, e.user); + } else if (e.event === "commented") { + add(commenters, e.user || e.actor); + } else if (e.event === "line-commented" || e.event === "commit-commented") { + (e.comments || []).forEach(function (c) { add(commenters, c.user); }); + } + }); + /* An approval after comments is what counts for that person. */ + commenters = commenters.filter(function (c) { + return !approvers.some(function (a) { return a.login === c.login; }); + }); + return { commenters: commenters, approvers: approvers }; + }, version, ttl).catch(function () { return { commenters: [], approvers: [] }; }); + } + + /* + * Changes suggested from this page's editor and not dealt with yet: open + * issues made from the specification-edit.yml form for this entry. The + * form writes each answer under its label, so the entry is found by the + * line under "### Specification id". + */ + function suggestions(api, specId) { + return getJSON(api + "/issues?state=open&per_page=100", function (list) { + return list.filter(function (i) { return !i.pull_request; }).map(function (i) { + var m = /###\s*Specification id\s*\n+\s*(\S+)/.exec(i.body || ""); + return { + issue: true, spec: m ? m[1] : "", number: i.number, title: i.title, url: i.html_url, + body: i.body || "", created: i.created_at, updated: i.updated_at, user: person(i.user) + }; + }); + }).then(function (list) { + return list.filter(function (i) { return i.spec === specId && /```ya?ml/.test(i.body); }); + }, function () { return []; }); + } + /* A file at one commit, or null where it does not exist there. Commits never change, so the answer is kept for the whole session. */ var RAW = {}; @@ -813,11 +1031,11 @@ /* GET from the API, keep only what `pick` returns, and remember it for CACHE_MS. `version` invalidates an entry early (a pull request's head). */ - function getJSON(url, pick, version) { + function getJSON(url, pick, version, ttl) { var key = "mdip-gh:" + url + (version ? "@" + version : ""); try { var hit = JSON.parse(sessionStorage.getItem(key)); - if (hit && Date.now() - hit.t < CACHE_MS) { return Promise.resolve(hit.v); } + if (hit && Date.now() - hit.t < (ttl || CACHE_MS)) { return Promise.resolve(hit.v); } } catch (e) { /* storage off or full: fetch */ } return fetch(url, { headers: { Accept: "application/vnd.github+json" } }) .then(function (r) { diff --git a/overrides/assets/stylesheets/spec-editor.css b/overrides/assets/stylesheets/spec-editor.css new file mode 100644 index 0000000..628e72e --- /dev/null +++ b/overrides/assets/stylesheets/spec-editor.css @@ -0,0 +1,537 @@ +/* ========================================================================== + MDIP SPECIFICATION REGISTRY - in-page editor (spec-editor.js) + + Uses the tokens declared on .mdip-spec in specifications.css, so it follows + Material's light and slate schemes with no colours of its own. A changed + value is marked with a soft wash behind it, never with a coloured edge. + ========================================================================== */ + +.mdip-spec { position: relative; } + +/* -- edit buttons ---------------------------------------------------------- */ + +.mdip-spec .sed-pen { display: none; } + +.mdip-spec.is-editing .sed-pen { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 1.45rem; + height: 1.45rem; + margin-left: .35rem; + padding: 0; + border: 1px solid var(--line-strong); + border-radius: 999px; + background: var(--surface); + color: var(--brand); + font-size: .75rem; + line-height: 1; + vertical-align: middle; + cursor: pointer; + box-shadow: var(--sh-1); + transition: background-color .15s var(--ease), border-color .15s var(--ease), + transform .15s var(--ease); +} +.mdip-spec.is-editing .sed-pen .mdip-i { width: .8rem; height: .8rem; } +.mdip-spec.is-editing .sed-pen:hover { background: var(--info-bg); border-color: var(--brand); transform: scale(1.06); } +[data-md-color-scheme="slate"] .mdip-spec.is-editing .sed-pen { color: var(--info); } + +/* Values drawn as a block (the description, licence and maintainer cards) + carry their button on the top corner instead of after the last line. */ +.mdip-spec.is-editing .sed-block { position: relative; } +.mdip-spec.is-editing .sed-block > .sed-pen { + position: absolute; + top: -.7rem; + right: -.5rem; + z-index: 2; + margin: 0; +} + +.mdip-spec .sed-empty { display: none; } +.mdip-spec.is-editing .sed-empty { + display: inline; + color: var(--ink-3); + font-size: .68rem; + font-style: italic; + font-weight: 400; +} + +/* An empty field reads as a field to fill in, and opens its editor. */ +.mdip-spec.is-editing [data-edit] .sed-empty { + display: inline-flex; + align-items: center; + min-height: 1.5rem; + padding: .15em .7em; + border: 1px dashed var(--line-strong); + border-radius: var(--r-s); + background: var(--surface); + color: var(--ink-3); + font-family: "Poppins", system-ui, sans-serif; + font-size: .68rem; + font-style: normal; + font-weight: 500; + letter-spacing: 0; + line-height: 1.4; + cursor: pointer; + transition: border-color .15s var(--ease), color .15s var(--ease); +} +.mdip-spec.is-editing [data-edit] .sed-empty:hover { border-color: var(--brand); color: var(--ink); } +.mdip-spec.is-editing h1 [data-edit] .sed-empty { min-height: 2.4rem; padding: .2em .9em; font-size: 1.1rem; } +.mdip-spec.is-editing .sed-block > .sed-empty, +.mdip-spec.is-editing .spec-hero__lede .sed-empty { display: flex; min-height: 3rem; } + +/* -- what changed ---------------------------------------------------------- */ + +.mdip-spec.is-editing .is-changed { + border-radius: 6px; + background: color-mix(in srgb, var(--brand) 9%, transparent); + box-shadow: 0 0 0 .2rem color-mix(in srgb, var(--brand) 9%, transparent); +} +[data-md-color-scheme="slate"] .mdip-spec.is-editing .is-changed { + background: color-mix(in srgb, var(--info) 14%, transparent); + box-shadow: 0 0 0 .2rem color-mix(in srgb, var(--info) 14%, transparent); +} + +.mdip-spec .sed-flash { animation: sed-flash 1.2s var(--ease); } +@keyframes sed-flash { + 0%, 30% { background: color-mix(in srgb, var(--brand) 26%, transparent); } +} + +/* -- criteria while editing ------------------------------------------------ */ + +.mdip-spec.is-editing .crit__body, +.mdip-spec.is-editing .crit__src, +.mdip-spec.is-editing .crit__chev { display: none; } +.mdip-spec.is-editing details.crit > .crit__head { cursor: default; } +.mdip-spec.is-editing details.crit > .crit__head:hover { background: none; } + +.mdip-spec .crit__edit { + display: grid; + gap: .5rem; + margin: 0; + padding: .55rem .8rem .7rem 2.35rem; + border-top: 1px solid var(--line); + background: var(--surface-2); +} +.mdip-spec .crit__edit[hidden] { display: none; } +.mdip-spec .crit__edit > div { display: grid; gap: .15rem; } +@media (min-width: 42em) { + .mdip-spec .crit__edit > div { grid-template-columns: 5.5rem minmax(0, 1fr); align-items: baseline; } +} +.mdip-spec .crit__edit dt { + color: var(--ink-3); + font-size: .58rem; + font-weight: 700; + letter-spacing: .06em; + text-transform: uppercase; +} +.mdip-spec .crit__edit dd { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: .3rem; + margin: 0; +} +.mdip-spec .crit__edit .crit__rationale { margin: 0; } + +/* -- popover --------------------------------------------------------------- */ + +.mdip-spec .sed-pop { + position: absolute; + z-index: 30; + width: 19rem; + max-width: calc(100% - 24px); + padding: .65rem; + border: 1px solid var(--line); + border-radius: var(--r-m); + background: var(--surface); + color: var(--ink); + box-shadow: var(--sh-3); + animation: sed-in .18s var(--ease); +} +.mdip-spec .sed-pop--wide { width: 25rem; } +@keyframes sed-in { + from { opacity: 0; transform: translateY(-4px) scale(.98); } +} + +.mdip-spec .sed-pop--sheet { + position: fixed; + inset: auto 0 0 0; + width: auto; + max-width: none; + max-height: 82vh; + overflow-y: auto; + padding: .9rem 1rem calc(1rem + env(safe-area-inset-bottom)); + border-radius: var(--r-l) var(--r-l) 0 0; + animation: sed-up .24s var(--ease); +} +@keyframes sed-up { from { transform: translateY(30%); opacity: 0; } } + +.mdip-spec .sed-pop__head { + margin: .05rem .2rem .5rem; + color: var(--ink-3); + font-size: .58rem; + font-weight: 700; + letter-spacing: .07em; + text-transform: uppercase; +} + +.mdip-spec .sed-pop__foot { + display: flex; + justify-content: flex-end; + align-items: center; + gap: .4rem; + margin-top: .65rem; +} +.mdip-spec .sed-pop__foot .btn { padding: .42em .85em; } + +/* -- custom list (the drop-down) ------------------------------------------- */ + +.mdip-spec .sed-list { + max-height: 19rem; + margin: 0; + padding: 0; + overflow-y: auto; + list-style: none; + outline: none; + overscroll-behavior: contain; +} +.mdip-spec .sed-list:focus-visible { outline: none; } + +.mdip-spec .sed-opt { + display: flex; + align-items: center; + justify-content: space-between; + gap: .5rem; + margin: 0; + padding: .42rem .5rem; + border-radius: var(--r-s); + cursor: pointer; +} +.mdip-spec .sed-opt.is-active { background: var(--surface-2); } +.mdip-spec .sed-list:focus .sed-opt.is-active, +.mdip-spec .sed-list--pick .sed-opt.is-active { background: var(--muted-bg); } +.mdip-spec .sed-opt__v { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: .1rem .45rem; + min-width: 0; +} +.mdip-spec .sed-opt__t { color: var(--ink); font-size: .7rem; font-weight: 600; } +.mdip-spec .sed-opt__t .mdip-i { width: .9em; height: .9em; vertical-align: -.1em; } +.mdip-spec .sed-opt__t--muted { color: var(--ink-3); font-weight: 500; } +.mdip-spec .sed-opt__h { flex-basis: 100%; color: var(--ink-3); font-size: .6rem; line-height: 1.4; } +.mdip-spec .sed-opt__ck { flex: none; display: inline-flex; width: 1rem; color: var(--brand); } +.mdip-spec .sed-opt .org-logo { width: 1.25rem; height: 1.25rem; } +.mdip-spec .sed-opt .org-logo--mono { font-size: .48rem; } + +.mdip-spec .sed-group { + margin: .35rem .5rem .15rem; + color: var(--ink-3); + font-size: .55rem; + font-weight: 700; + letter-spacing: .07em; + text-transform: uppercase; +} + +.mdip-spec .sed-dot { + flex: none; + width: .5rem; + height: .5rem; + border-radius: 50%; + background: var(--muted); +} +.mdip-spec .sed-dot--open { background: var(--pass); } +.mdip-spec .sed-dot--restricted { background: var(--warn); } +.mdip-spec .sed-dot--closed { background: var(--fail); } + +/* -- inputs ---------------------------------------------------------------- */ + +.mdip-spec .sed-input { + display: block; + width: 100%; + box-sizing: border-box; + padding: .45rem .55rem; + border: 1px solid var(--line-strong); + border-radius: var(--r-s); + background: var(--surface); + color: var(--ink); + font: inherit; + font-size: .72rem; + line-height: 1.5; + transition: border-color .15s var(--ease), box-shadow .15s var(--ease); +} +.mdip-spec textarea.sed-input { resize: vertical; min-height: 4.5rem; } +.mdip-spec .sed-input:focus { + border-color: var(--brand); + outline: none; + box-shadow: 0 0 0 3px color-mix(in srgb, var(--brand) 15%, transparent); +} +.mdip-spec .sed-input[aria-invalid="true"] { border-color: var(--fail); } +.mdip-spec .sed-err { margin: .3rem .1rem 0; color: var(--fail); font-size: .62rem; } + +.mdip-spec .sed-find { + display: flex; + align-items: center; + gap: .4em; + margin-bottom: .3rem; + padding: .35em .6em; + border: 1px solid var(--line-strong); + border-radius: var(--r-s); + background: var(--surface); + color: var(--ink-3); +} +.mdip-spec .sed-find:focus-within { border-color: var(--brand); } +.mdip-spec .sed-find input { + flex: 1; + min-width: 0; + border: 0; + background: none; + color: var(--ink); + font: inherit; + font-size: .68rem; + outline: none; +} + +/* -- toggle chips (modes, licence scopes) ---------------------------------- */ + +.mdip-spec .sed-chips { display: flex; flex-wrap: wrap; gap: .35rem; } +.mdip-spec .sed-chip { + display: inline-flex; + align-items: center; + gap: .25em; + padding: .36em .75em; + border: 1px solid var(--line-strong); + border-radius: 999px; + background: var(--surface); + color: var(--ink-2); + font: inherit; + font-size: .66rem; + font-weight: 500; + cursor: pointer; + transition: background-color .15s var(--ease), color .15s var(--ease), border-color .15s var(--ease); +} +.mdip-spec .sed-chip:hover { border-color: var(--brand); } +.mdip-spec .sed-chip__ck { display: inline-flex; width: 0; overflow: hidden; transition: width .15s var(--ease); } +.mdip-spec .sed-chip__ck .mdip-i { width: .9em; height: .9em; } +.mdip-spec .sed-chip[aria-pressed="true"] { + border-color: transparent; + background: var(--info-bg); + color: var(--brand); + font-weight: 600; +} +[data-md-color-scheme="slate"] .mdip-spec .sed-chip[aria-pressed="true"] { color: var(--info); } +.mdip-spec .sed-chip[aria-pressed="true"] .sed-chip__ck { width: 1em; } +.mdip-spec .sed-chips--sm { margin-top: .4rem; gap: .25rem; } +.mdip-spec .sed-chips--sm .sed-chip { padding: .22em .6em; font-size: .6rem; } + +/* -- licences -------------------------------------------------------------- */ + +.mdip-spec .sed-lics { display: grid; gap: .45rem; } +.mdip-spec .sed-lic { padding: .45rem; border-radius: var(--r-s); background: var(--surface-2); } +.mdip-spec .sed-lic__top { display: flex; align-items: center; gap: .3rem; } +.mdip-spec .sed-combo { + display: flex; + flex: 1; + align-items: center; + gap: .45rem; + min-width: 0; + padding: .38rem .5rem; + border: 1px solid var(--line-strong); + border-radius: var(--r-s); + background: var(--surface); + color: var(--ink); + font: inherit; + text-align: left; + cursor: pointer; +} +.mdip-spec .sed-combo:hover, +.mdip-spec .sed-combo[aria-expanded="true"] { border-color: var(--brand); } +.mdip-spec .sed-combo__t { display: flex; flex: 1; flex-direction: column; min-width: 0; } +.mdip-spec .sed-combo__t > span { font-size: .7rem; font-weight: 600; } +.mdip-spec .sed-combo__t small { + overflow: hidden; + color: var(--ink-3); + font-size: .58rem; + text-overflow: ellipsis; + white-space: nowrap; +} +.mdip-spec .sed-combo > .mdip-i { flex: none; width: .9rem; height: .9rem; color: var(--ink-3); } +.mdip-spec .sed-combo[aria-expanded="true"] > .mdip-i { transform: rotate(180deg); } + +.mdip-spec .sed-pick { + margin-top: .35rem; + padding: .35rem; + border: 1px solid var(--line); + border-radius: var(--r-s); + background: var(--surface); +} +.mdip-spec .sed-list--pick { max-height: 12.5rem; } +.mdip-spec .sed-other { display: grid; gap: .3rem; margin-top: .35rem; } +.mdip-spec .sed-add { margin-top: .45rem; } + +.mdip-spec .sed-icon { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 1.75rem; + height: 1.75rem; + padding: 0; + border: 0; + border-radius: var(--r-s); + background: transparent; + color: var(--ink-3); + cursor: pointer; +} +.mdip-spec .sed-icon:hover { background: var(--fail-bg); color: var(--fail); } +.mdip-spec .sed-icon .mdip-i { width: .95rem; height: .95rem; } +.mdip-spec .sed-icon--sm { width: 1.15rem; height: 1.15rem; border-radius: 999px; } +.mdip-spec .sed-icon--sm .mdip-i { width: .7rem; height: .7rem; } + +/* -- maintainers ----------------------------------------------------------- */ + +.mdip-spec .sed-picked { display: flex; flex-wrap: wrap; gap: .3rem; margin-bottom: .45rem; } +.mdip-spec .sed-picked:empty { display: none; } +.mdip-spec .sed-picked__c { + display: inline-flex; + align-items: center; + gap: .35rem; + padding: .18rem .2rem .18rem .25rem; + border-radius: 999px; + background: var(--muted-bg); + color: var(--ink); + font-size: .64rem; + font-weight: 500; +} +.mdip-spec .sed-picked__c .org-logo { width: 1.1rem; height: 1.1rem; } +.mdip-spec .sed-picked__c .org-logo--mono { font-size: .42rem; } + +/* -- the bar while editing ------------------------------------------------- */ + +.mdip-spec .sed-bar { + position: fixed; + left: 50%; + bottom: 1rem; + z-index: 20; + width: min(36rem, calc(100% - 2rem)); + transform: translateX(-50%); + animation: sed-bar-in .3s var(--ease); +} +@keyframes sed-bar-in { from { opacity: 0; transform: translate(-50%, 1rem); } } +.mdip-spec .sed-bar__in { + display: flex; + align-items: center; + gap: .5rem; + padding: .45rem .45rem .45rem .95rem; + border: 1px solid var(--line); + border-radius: 999px; + background: color-mix(in srgb, var(--surface) 92%, transparent); + box-shadow: var(--sh-3); + backdrop-filter: blur(12px) saturate(1.3); + -webkit-backdrop-filter: blur(12px) saturate(1.3); +} +.mdip-spec .sed-bar__t { + display: flex; + flex: 1; + align-items: center; + gap: .4rem; + min-width: 0; + overflow: hidden; + color: var(--ink-2); + font-size: .68rem; + white-space: nowrap; +} +.mdip-spec .sed-bar__t > span { overflow: hidden; text-overflow: ellipsis; } +.mdip-spec .sed-bar__t .mdip-i { flex: none; color: var(--brand); } +.mdip-spec .sed-bar__n { + color: var(--ink-3); + font-size: .62rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} +.mdip-spec .sed-bar .btn:disabled { opacity: .45; cursor: default; transform: none; box-shadow: none; } +@media (max-width: 40em) { + .mdip-spec .sed-bar { bottom: .6rem; } + .mdip-spec .sed-bar__in { border-radius: var(--r-m); padding-left: .7rem; } + .mdip-spec .sed-bar__n { display: none; } +} +body.sed-has-bar .mdip-spec { padding-bottom: 4.5rem; } + +/* -- unsent suggestion ----------------------------------------------------- */ + +.mdip-spec .sed-draft { + display: flex; + flex: 1 1 100%; + flex-wrap: wrap; + align-items: center; + gap: .5rem .7rem; + margin: 0; + padding: .65rem .8rem; + border-radius: var(--r-m); + background: var(--info-bg); + color: var(--ink-2); + font-size: .68rem; +} +.mdip-spec .sed-draft > span { flex: 1 1 12rem; } +.mdip-spec .sed-draft > .mdip-i { flex: none; color: var(--brand); } + +/* -- review dialog --------------------------------------------------------- */ + +.mdip-spec .sed-dialog { + width: min(40rem, calc(100% - 2rem)); + max-height: calc(100vh - 3rem); + padding: 0; + border: 0; + border-radius: var(--r-l); + background: var(--surface); + color: var(--ink); + box-shadow: var(--sh-3); + font-family: "Poppins", system-ui, -apple-system, "Segoe UI", sans-serif; +} +.mdip-spec .sed-dialog[open] { animation: sed-in .2s var(--ease); } +.mdip-spec .sed-dialog::backdrop { + background: rgba(16, 25, 43, .45); + backdrop-filter: blur(3px); +} +.mdip-spec .sed-dialog__in { padding: 1.2rem 1.3rem 1.1rem; } +.mdip-spec .sed-dialog h2 { + margin: 0 0 .8rem; + color: var(--ink); + font-family: "Raleway", system-ui, sans-serif; + font-size: 1.05rem; + font-weight: 700; +} +.mdip-spec .sed-dialog p { margin: 0; color: var(--ink-2); font-size: .7rem; line-height: 1.55; } +.mdip-spec .sed-dialog .hist__scroll { margin-top: 0; max-height: 40vh; overflow: auto; } +.mdip-spec .sed-label { + display: block; + margin: .9rem 0 .3rem; + color: var(--ink-2); + font-size: .64rem; + font-weight: 600; +} +.mdip-spec .sed-gh { + display: flex; + align-items: flex-start; + gap: .6rem; + margin-top: .9rem; + padding: .6rem .75rem; + border-radius: var(--r-s); + background: var(--surface-2); +} +.mdip-spec .sed-gh > .mdip-i { flex: none; width: 1.1rem; height: 1.1rem; color: var(--ink-2); } +.mdip-spec .sed-dialog .sed-gh p { font-size: .64rem; } +.mdip-spec .sed-paste { display: flex; gap: .4rem; margin-top: .7rem !important; } +.mdip-spec .sed-paste[hidden] { display: none; } +.mdip-spec .sed-dialog__foot { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + align-items: center; + gap: .45rem; + margin-top: 1.1rem; +} +.mdip-spec .sed-dialog .btn .mdip-i:last-child:not(:first-child) { width: .8em; height: .8em; opacity: .7; } diff --git a/overrides/assets/stylesheets/specifications.css b/overrides/assets/stylesheets/specifications.css index fc87ee8..c487e38 100644 --- a/overrides/assets/stylesheets/specifications.css +++ b/overrides/assets/stylesheets/specifications.css @@ -550,11 +550,17 @@ buttons min-height: 0; } +/* On a wide screen the panel is part of the page, not a box with its own + scrollbar. When it is taller than the window, the page script moves its + sticky offset with the scroll (see initPanelScroll): it travels down with + the page until its last filter is in view, and comes back up as soon as + the page does, so every filter is reachable with the page's own scroll. + --panel-top is that offset; without the script it is a plain sticky + panel, and a long one scrolls along with the page. */ @media (min-width: 60em) { :is(.mdip-specs, .mdip-spec) .specs-panel { position: sticky; - top: calc(var(--hdr) + .8rem); - max-height: calc(100vh - var(--hdr) - 1.6rem); + top: var(--panel-top, calc(var(--hdr) + .8rem)); padding: .55rem .6rem; border: 1px solid var(--line); border-radius: var(--r-m); @@ -632,7 +638,7 @@ buttons scrollbar-width: thin; } @media (min-width: 60em) { - :is(.mdip-specs, .mdip-spec) .specs-panel__scroll { padding-right: .25rem; } + :is(.mdip-specs, .mdip-spec) .specs-panel__scroll { overflow: visible; } } /* -- one facet ------------------------------------------------------------- */ From 7a6629d2ad2e1af703004197acb9b96ed5eba77f Mon Sep 17 00:00:00 2001 From: Etienne Pichot Damon Date: Wed, 18 Nov 2026 17:00:26 -0500 Subject: [PATCH 2/2] chore: rename remaining MkDocs references to ProperDocs Address review feedback on PR #77: the project switched to ProperDocs, so leftover MkDocs mentions are updated. - .claude/launch.json: rename the preview configurations to properdocs-en / properdocs-en-alt and run the properdocs executable. - README, Makefile, hooks/specifications.py, scripts/spec_api.py, overrides/sitemap.xml, .gitignore: say ProperDocs in prose and comments. Left unchanged on purpose: the `mkdocs` Python import and logger name in hooks/specifications.py, PyPI package names in requirements.txt and the Makefile, and the "Material for MkDocs" theme name, since those are real identifiers or third-party product names. Co-Authored-By: Claude Opus 5.5 --- .claude/launch.json | 8 ++++---- .gitignore | 2 +- Makefile | 4 ++-- README.md | 2 +- hooks/specifications.py | 2 +- overrides/sitemap.xml | 2 +- scripts/spec_api.py | 2 +- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.claude/launch.json b/.claude/launch.json index fc790b2..4dd9dbd 100644 --- a/.claude/launch.json +++ b/.claude/launch.json @@ -2,14 +2,14 @@ "version": "0.0.1", "configurations": [ { - "name": "mkdocs-en", - "runtimeExecutable": "mkdocs", + "name": "properdocs-en", + "runtimeExecutable": "properdocs", "runtimeArgs": ["serve", "-f", "config/en/properdocs.yml", "--dev-addr", "127.0.0.1:8000", "--watch", "overrides", "--watch", "hooks", "--watch", "data", "--watch", "scripts"], "port": 8000 }, { - "name": "mkdocs-en-alt", - "runtimeExecutable": "mkdocs", + "name": "properdocs-en-alt", + "runtimeExecutable": "properdocs", "runtimeArgs": ["serve", "-f", "config/en/properdocs.yml", "--dev-addr", "127.0.0.1:8001"], "port": 8001 } diff --git a/.gitignore b/.gitignore index e72257d..a03cbc3 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ __pycache__/ *.py[cod] -# MkDocs +# ProperDocs site/ generated/ node_modules diff --git a/Makefile b/Makefile index a154b4b..364f6c8 100644 --- a/Makefile +++ b/Makefile @@ -11,8 +11,8 @@ setup: pip3 install --upgrade --force-reinstall properdocs && \ pip3 install --upgrade --force-reinstall mkdocs-material -# --watch: mkdocs only watches docs/ and the config by itself, so the -# specification registry's sources (hooks/, scripts/, data/) have to be named. Note that mkdocs caches +# --watch: ProperDocs only watches docs/ and the config by itself, so the +# specification registry's sources (hooks/, scripts/, data/) have to be named. Note that ProperDocs caches # the hook module -- an edit to hooks/ or scripts/ triggers a rebuild but the # old code runs, so restart the server after changing those. serve: clean diff --git a/README.md b/README.md index 8863710..6777f46 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ specification. | `scripts/spec_data.py` | Loads, validates and joins the files. | | `scripts/spec_api.py` | Builds the `/api/` files: catalogue, full records, export CSV, the OpenAPI description, and its Swagger UI page at `/api/docs/`. | | `scripts/check_specs.py` | `make specs-check`: validation, also run on every pull request. | -| `hooks/specifications.py` | MkDocs hook that renders the pages and publishes the API. | +| `hooks/specifications.py` | ProperDocs hook that renders the pages and publishes the API. | | `overrides/assets/javascript/spec-editor.js` | The in-page editor behind "Suggest a change" and `/specifications/new/`. | ```bash diff --git a/hooks/specifications.py b/hooks/specifications.py index 59222c7..aa63f1e 100644 --- a/hooks/specifications.py +++ b/hooks/specifications.py @@ -1152,7 +1152,7 @@ def short_url(url): # -------------------------------------------------------------------------- -# MkDocs entry point +# ProperDocs entry point # -------------------------------------------------------------------------- INDEX_META = """--- diff --git a/overrides/sitemap.xml b/overrides/sitemap.xml index 9bd293b..0d1ad26 100644 --- a/overrides/sitemap.xml +++ b/overrides/sitemap.xml @@ -1,5 +1,5 @@ -{#- MkDocs' own sitemap template, plus one rule: pages whose front matter sets +{#- ProperDocs' own sitemap template, plus one rule: pages whose front matter sets `robots: noindex` are left out, so an unlisted page is not advertised to search engines here either. -#} diff --git a/scripts/spec_api.py b/scripts/spec_api.py index 6681b66..692b5ad 100644 --- a/scripts/spec_api.py +++ b/scripts/spec_api.py @@ -1,7 +1,7 @@ """The registry's read-only JSON API, written as static files at build time. `build_api` takes the joined dataset from spec_data.build_dataset() and -returns {published path: text}. The MkDocs hook publishes those files under +returns {published path: text}. The ProperDocs hook publishes those files under /api/, and `make specs-export` writes the same files to a local folder. api/index.json what is here, and the vocabularies