A platform for community discussion. Free, open, simple.
DEV: Give the styleguide a card anatomy, groups and a section subnav (#42385)
Sérgio Saquetimcc23c468c89d
diff --git a/plugins/styleguide/README.md b/plugins/styleguide/README.mdindex 208a04a3037..2fc77abf9d5 100644--- a/plugins/styleguide/README.md+++ b/plugins/styleguide/README.md@@ -59,10 +59,88 @@ from being possible.### Layout```-examples/<group>/<section>/<name>.gjs+examples/<category>/<section>/<name>.gjs+examples/<category>/<name>.gjs # flat, for a section with few examples```-`<group>` is `atoms`, `molecules` or `organisms`; `<section>` is the section-file name without its numeric prefix; `<name>` is a kebab-case slug for the-variant. Import with a relative specifier and no file extension, and name the-bindings `<Name>Example` and `<name>Source`.+`<category>` is `atoms`, `molecules` or `organisms`; `<section>` is the section+file name without its numeric prefix; and `<name>` is a kebab-case slug for the+variant. Both shapes are in use: a section with only a handful of examples keeps+them flat under `<category>`, named for the example rather than the section, and+a section with enough of them to be worth grouping gets its own directory.+Import with a relative specifier and no file extension, and name the bindings+`<Name>Example` and `<name>Source`.++When a section is split into groups (see below), put the group slug between the+section and the name so the source tree stays correlated with the page's+navigation. No section does this yet, so this level is a convention for the+first one that adopts groups rather than a rule the tree currently follows:++```+examples/<category>/<section>/<group>/<name>.gjs+```++## Card anatomy++`<StyleguideExample>` has a fixed set of slots, each on its own row, so cards in+a group line up with each other rather than drifting with the prose above them.+All of `@description`, `@tryThis` and `@note` take either a string or a named+block; a block wins when both are given.++| Slot | What belongs there |+| --- | --- |+| `@title` | The capability being shown. |+| `@description` | What this example proves. Prefer supplying one. |+| `@tryThis` | Something the reader can do to see it happen. Omit when there is nothing to do. |+| default block | The live component. |+| `@note` | What to notice afterwards. Give a list in the block the class `styleguide-example__note-list`. |+| `@code` | The `?source=` import, revealed by a toggle. |++Backticks render as inline `<code>` in the three prose slots — `@description`,+`@tryThis` and `@note` — so an argument or block name can sit in a sentence+without splitting it across keys. `@title` and the group heading and description+render their text as-is.++```yaml+some_key: "never mutates `@value`"+```++`@headingLevel` defaults to `2`, which suits an ungrouped page whose only+heading above the card is the page's own `h1`.++Two opt-in classes are available to markup an example yields:+`styleguide-example__result`, for the element a demo writes its output into,+which belongs in the default block; and `styleguide-example__note-list`, for a+list, which belongs in a `note` block. A card may also take `class="--wide"` to+span a whole grid row; put a wide card first in its group, since the grid places+cards sparsely and a wide card elsewhere sits flush only when the cards before+it happen to fill their row.++## Groups++A long section can be split into named groups reachable from a sticky subnav,+with the active group carried in a `?group=` query param so a link addresses one+group rather than a whole page. Pass an ordered manifest of+`{ id, title, description }`; it is the single source of truth for both the+subnav and the group order. The pills are real links, not tabs. Pass+`@ariaLabel` too — the subnav is a `<nav>` landmark and needs a name.++`StyleguideGroup` yields a `StyleguideExample` already curried to+`@headingLevel={{3}}`, so a grouped page keeps a correct `h1` → `h2` → `h3`+outline without each call site restating it:++```gjs+<StyleguideGroups+ @groups={{this.groups}}+ @section={{@section}}+ @active={{@group}}+ @ariaLabel={{i18n "styleguide.sections.thing.groups.aria_label"}}+ as |Group|+>+ <Group @id="start" as |Example|>+ <Example @title="<DThing>" @code={{thingSource}}>+ <ThingExample />+ </Example>+ </Group>+</StyleguideGroups>+```diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-stacked.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-stacked.gjsindex 3c8a1c37b4f..09fda8c57d3 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-stacked.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-stacked.gjs@@ -5,17 +5,12 @@ import UserNavStackedExample from "../../examples/molecules/user-nav-stacked";import userNavStackedSource from "../../examples/molecules/user-nav-stacked?source=file";export default <template>- <StyleguideExample- @title=".nav-stacked"- class="half-size"- @code={{navStackedSource}}- >+ <StyleguideExample @title=".nav-stacked" @code={{navStackedSource}}><NavStackedExample @navItems={{@dummy.navItems}} /></StyleguideExample><StyleguideExample@title=".user-navigation .nav-stacked"- class="half-size"@code={{userNavStackedSource}}><UserNavStackedExample @navItems={{@dummy.navItems}} />diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/basic-topic-list.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/basic-topic-list.gjsindex 0fa687934b3..199c1831d28 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/basic-topic-list.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/basic-topic-list.gjs@@ -3,11 +3,7 @@ import BasicTopicListExample from "../../examples/organisms/basic-topic-list";import basicTopicListSource from "../../examples/organisms/basic-topic-list?source=file";export default <template>- <StyleguideExample- @title="<BasicTopicList>"- class="half-size"- @code={{basicTopicListSource}}- >+ <StyleguideExample @title="<BasicTopicList>" @code={{basicTopicListSource}}><BasicTopicListExample @topics={{@dummy.topics}} /></StyleguideExample></template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-example.gjs b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-example.gjsindex 8e52a9af576..deee5072f89 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-example.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-example.gjs@@ -1,40 +1,155 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { action } from "@ember/object";+import { eq, or } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DHighlightedCode from "discourse/ui-kit/d-highlighted-code";+import { i18n } from "discourse-i18n";+import inlineCode from "discourse/plugins/styleguide/discourse/lib/inline-code";+// A plain counter rather than `guidFor`: `@ember/object/internals` is not resolvable from a+// plugin bundle, and importing it fails the whole bundle at load rather than at use.+let exampleId = 0;++/**+ * One demonstrated capability: a heading, the prose that says what it proves, the live+ * component, and an optional source snippet.+ *+ * `@description`, `@tryThis` and `@note` each accept a plain string or a named block, so prose+ * that needs inline code or a link is expressible without splitting a sentence across translation+ * keys. A block wins over the string when both are supplied.+ *+ * @param {string} title - the capability being shown. Required: it is the card's heading and+ * it names the source panel's landmark, so omitting it leaves an empty heading behind.+ * @param {number} [headingLevel=2] - heading level for the title, 2 or 3. The default suits an+ * ungrouped page, where the only heading above is the page's own `h1`. Inside a group, pass 3+ * so the group's `h2` stays above it — `StyleguideGroup` yields a component already curried+ * that way.+ * @param {string} [description] - what this example proves. Prefer supplying one: an example+ * that only shows a widget under a title leaves the reader to infer the point.+ * @param {string} [tryThis] - an instruction the reader can carry out to see it happen.+ * Omit it when there is nothing to do (a purely visual variation).+ * @param {string} [note] - background prose after the demo: what to notice once it has been+ * used. Quiet on purpose — the accent bar belongs to `tryThis`, the one thing to act on.+ * Also accepts a block, for a short list; give a list in that block the class+ * `styleguide-example__note-list` so it picks up the card's list spacing.+ * @param {string} [code] - the imported source of the example module, revealed by a toggle.+ *+ * Two opt-in classes an example may apply to its own yielded markup:+ * `styleguide-example__result`, for an element the demo writes its output into, inside the+ * default block; and `styleguide-example__note-list`, for a list inside a `note` block. Both+ * are styled as descendants rather than card slots, because yielded content lands inside the+ * slot that yielded it rather than as a grid item of the card.+ *+ * A card may also carry `class="--wide"` to span the full width of a group's grid instead of+ * one column. Put such a card first in its group: the grid places sparsely, so a wide card+ * anywhere else lands flush only when the cards before it happen to fill their row, which a+ * responsive column count cannot promise.+ */export default class StyleguideExample extends Component {@tracked showCode = false;+ codeId = `styleguide-example-code-${(exampleId += 1)}`;++ get headingLevel() {+ return this.args.headingLevel ?? 2;+ }+@actiontoggleCode() {this.showCode = !this.showCode;}<template>- <section class="styleguide-example">- <div class="example-title">- <div class="example-title--text">- {{@title}}- </div>+ <section class="styleguide-example" ...attributes>+ <div class="styleguide-example__header">+ {{! Two spelled-out branches rather than a computed tag name: only these two levels are+ supported, so naming them is plainer than indirection through a dynamic element. }}+ {{#if (eq this.headingLevel 3)}}+ <h3 class="styleguide-example__title" data-test-example-title>+ {{@title}}+ </h3>+ {{else}}+ <h2 class="styleguide-example__title" data-test-example-title>+ {{@title}}+ </h2>+ {{/if}}{{#if @code}}+ {{! Icon-only, so the tooltip and the accessible name are set separately. DButton+ builds its aria-label from the ariaLabel argument alone and never from the title+ argument, and a name coming only from a title attribute is a weak one. }}<DButton@icon="code"+ @title="styleguide.example.toggle_code"+ @ariaLabel="styleguide.example.toggle_code"@action={{this.toggleCode}}- class="btn-flat btn-transparent"+ class="btn-flat btn-transparent styleguide-example__code-toggle"+ aria-expanded={{if this.showCode "true" "false"}}+ {{! Only while the region exists — the panel is unmounted when collapsed, and a+ reference to an absent id is an ARIA validity error. }}+ aria-controls={{if this.showCode this.codeId}}/>{{/if}}</div>+ {{#if (or @description (has-block "description"))}}+ <p class="styleguide-example__description">+ {{#if (has-block "description")}}+ {{yield to="description"}}+ {{else}}+ {{inlineCode @description}}+ {{/if}}+ </p>+ {{/if}}++ {{! Placed above the demo so a keyboard or screen-reader user meets the instruction+ before the control it applies to. }}+ {{#if (or @tryThis (has-block "tryThis"))}}+ <p class="styleguide-example__try-this">+ <span class="styleguide-example__try-this-label">+ {{i18n "styleguide.example.try_this"}}+ </span>+ {{! One element around the whole instruction, because the row is a flex container:+ prose containing inline code is a mix of text nodes and elements, and each would+ otherwise become its own flex item and be laid out as a separate box, scrambling the+ sentence. }}+ <span class="styleguide-example__try-this-text">+ {{#if (has-block "tryThis")}}+ {{yield to="tryThis"}}+ {{else}}+ {{inlineCode @tryThis}}+ {{/if}}+ </span>+ </p>+ {{/if}}++ <div class="styleguide-example__body">{{yield}}</div>++ {{! The far side of the demo from the instruction: what to notice once it has been used. A+ div rather than a paragraph because a note is as often a short list as a sentence. }}+ {{#if (or @note (has-block "note"))}}+ <div class="styleguide-example__note">+ {{#if (has-block "note")}}+ {{yield to="note"}}+ {{else}}+ {{inlineCode @note}}+ {{/if}}+ </div>+ {{/if}}+{{#if this.showCode}}- <div class="styleguide-code">+ <div+ class="styleguide-example__code"+ id={{this.codeId}}+ role="region"+ {{! Named after its own example: several panels can be open at once, and landmarks+ sharing one name are indistinguishable in a screen reader's landmark list. }}+ aria-label={{i18n "styleguide.example.code_region" title=@title}}+ ><DHighlightedCode @code={{@code}} @lang="javascript" /></div>{{/if}}-- <section class="rendered">{{yield}}</section></section></template>}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-group.gjs b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-group.gjsnew file mode 100644index 00000000000..3bcc6c4d15a--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-group.gjs@@ -0,0 +1,76 @@+import Component from "@glimmer/component";+import { warn } from "@ember/debug";+import StyleguideExample from "./styleguide-example";++// Group ids are only unique within one manifest, so two sets of groups on a page could both+// hold a "start". A per-instance number keeps the heading ids distinct, which `aria-labelledby`+// depends on. A plain counter rather than `guidFor`: `@ember/object/internals` is not+// resolvable from a plugin bundle.+let groupId = 0;++/**+ * One group of a sectioned styleguide page. Renders its body only while it is the active group.+ *+ * Invoked through the curried component `StyleguideGroups` yields, so `@activeId` and `@groups`+ * are supplied for you and a call site passes only `@id`.+ *+ * Yields a `StyleguideExample` curried to `@headingLevel={{3}}`, so a grouped page keeps a+ * correct `h1` → `h2` → `h3` order without every call site restating the level. Ignoring the+ * block param and writing `<StyleguideExample>` directly still works, and renders `h2`.+ *+ * The `{{#if}}` is load-bearing and must NOT become a CSS-hidden variant: unmounting is what+ * tears down the group's live components, so each demo's own state is discarded when the reader+ * switches away rather than left running out of sight. Glimmer blocks are lazy, so an inactive+ * group's body is never instantiated in the first place.+ */+export default class StyleguideGroup extends Component {+ headingId = `styleguide-group-heading-${(groupId += 1)}`;++ constructor() {+ super(...arguments);++ // Guarded on the manifest rather than on `isActive`, and placed here rather than in a+ // getter: a mismatched id is exactly the case that can never be active, since `activeId`+ // only ever holds a manifest id, so an `isActive` guard would never fire and a getter+ // would repeat the warning on every render.+ warn(+ `<StyleguideGroup> was given @id="${this.args.id}", which no entry in the groups manifest declares. It can never become the active group, so its body will never render.`,+ this.record !== undefined,+ { id: "styleguide.group-id-not-in-manifest" }+ );+ }++ get isActive() {+ return this.args.id === this.args.activeId;+ }++ get record() {+ return (this.args.groups ?? []).find((group) => group.id === this.args.id);+ }++ <template>+ {{#if this.isActive}}+ <div+ class="styleguide-group"+ data-test-styleguide-group={{@id}}+ role="region"+ aria-labelledby={{this.headingId}}+ tabindex="-1"+ >+ <h2 class="styleguide-group__title" id={{this.headingId}}>+ {{this.record.title}}+ </h2>++ {{#if this.record.description}}+ <p class="styleguide-group__description">+ {{this.record.description}}+ </p>+ {{/if}}++ <div class="styleguide-group__examples">+ {{yield (component StyleguideExample headingLevel=3)}}+ </div>+ </div>+ {{/if}}+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-groups.gjs b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-groups.gjsnew file mode 100644index 00000000000..4e02ef6e05a--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-groups.gjs@@ -0,0 +1,80 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import didUpdate from "@ember/render-modifiers/modifiers/did-update";+import { service } from "@ember/service";+import { scrollTop } from "discourse/lib/scroll-top";+import StyleguideGroup from "./styleguide-group";+import StyleguideSubnav from "./styleguide-subnav";++/**+ * Splits a long styleguide section into navigable groups, one rendered at a time.+ *+ * The styleguide has no tab, anchor or collapsing primitive, and `StyleguideSection` scrolls to+ * the top on every attrs change, which defeats hash deep-links. So the group lives in a `group`+ * query param instead: real URLs, real history, no change to the shared section component, and+ * only one group's components mounted at a time.+ *+ * @param {Array<{id: string, title: string, description?: string}>} groups - ordered manifest;+ * the single source of truth for both the subnav and the group order.+ * @param {object} section - the styleguide section, needed to build the `<LinkTo>` route models.+ * @param {string} [active] - the requested group id. This is the `group` query param, which the+ * section component receives as `@group` and passes in here; the name differs because from+ * this component's side it is the active selection rather than a URL parameter.+ * @param {string} [ariaLabel] - accessible name for the sub-navigation landmark.+ *+ * Yields a curried `Group` component, so a call site writes `<Group @id="data">…</Group>` and+ * the active-id comparison is supplied for it. `Group` in turn yields a `StyleguideExample`+ * curried to the right heading level.+ */+export default class StyleguideGroups extends Component {+ @service a11y;++ /** The requested group, falling back to the first so an unknown or absent id still renders. */+ get activeId() {+ const groups = this.args.groups ?? [];+ const requested = groups.find((group) => group.id === this.args.active);+ return (requested ?? groups[0])?.id;+ }++ get #activeGroup() {+ return (this.args.groups ?? []).find((group) => group.id === this.activeId);+ }++ // `didUpdate` hands over the element it is installed on, which is what keeps the lookup below+ // scoped to THIS instance's body. A document-wide query would focus the first group on the+ // page, which is the wrong one the moment a section renders two of these.+ @action+ handleGroupChange(element) {+ // The pill that was clicked survives the swap, so focus is usually fine. It is not fine when+ // the group changed via Back/Forward while focus sat inside the outgoing group's body: that+ // node unmounts and focus falls to `<body>`. Only then is it ours to restore.+ if (document.activeElement === document.body) {+ element.querySelector(".styleguide-group")?.focus();+ }++ // Nothing else signals to a screen reader that the page's content was replaced.+ if (this.#activeGroup?.title) {+ this.a11y.announce(this.#activeGroup.title, "polite");+ }++ scrollTop();+ }++ <template>+ <StyleguideSubnav+ @groups={{@groups}}+ @section={{@section}}+ @activeId={{this.activeId}}+ @ariaLabel={{@ariaLabel}}+ />++ <div+ class="styleguide-groups__body"+ {{didUpdate this.handleGroupChange this.activeId}}+ >+ {{yield+ (component StyleguideGroup activeId=this.activeId groups=@groups)+ }}+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-subnav.gjs b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-subnav.gjsnew file mode 100644index 00000000000..6793a799cbd--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-subnav.gjs@@ -0,0 +1,44 @@+import { array, hash } from "@ember/helper";+import { LinkTo } from "@ember/routing";+import { eq } from "discourse/truth-helpers";+import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";++/**+ * Sub-navigation for a styleguide section that is split into groups.+ *+ * These are real navigations — each pill is a distinct URL (`?group=…`) with history and+ * open-in-new-tab — so the markup is links inside a `<nav>`, not `role="tablist"`. Giving them+ * tab roles would override the link role, lose the "this navigates" expectation, and oblige a+ * roving tabindex that fights `<LinkTo>`'s natural tab order.+ *+ * `DHorizontalOverflowNav` renders the `<ul class="nav-pills">` itself, so this yields bare+ * `<li>` elements into it; wrapping them in another `<ul>` would break both `.nav-pills > li > a`+ * styling and the component's own drag-scroll lookup.+ *+ * Active state is computed from `@activeId` rather than left to `<LinkTo>`: the default group+ * carries no `?group=` in the URL, so Ember would never mark it active. The class goes on the+ * `<a>`, which is what both `.nav-pills` styling and the overflow nav's auto-scroll key off,+ * and `aria-current` carries the state non-visually — `<LinkTo>` emits none of its own.+ */+const StyleguideSubnav = <template>+ <div class="styleguide-subnav">+ <DHorizontalOverflowNav @ariaLabel={{@ariaLabel}}>+ {{#each @groups key="id" as |group|}}+ <li>+ <LinkTo+ @route="styleguide.show"+ @models={{array @section.category @section.id}}+ @query={{hash group=group.id}}+ class={{if (eq group.id @activeId) "active"}}+ aria-current={{if (eq group.id @activeId) "page"}}+ data-test-styleguide-subnav-link={{group.id}}+ >+ {{group.title}}+ </LinkTo>+ </li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+</template>;++export default StyleguideSubnav;diff --git a/plugins/styleguide/assets/javascripts/discourse/controllers/styleguide/show.js b/plugins/styleguide/assets/javascripts/discourse/controllers/styleguide/show.jsindex bedefb4deae..bc99e6b83c5 100644--- a/plugins/styleguide/assets/javascripts/discourse/controllers/styleguide/show.js+++ b/plugins/styleguide/assets/javascripts/discourse/controllers/styleguide/show.js@@ -1,7 +1,18 @@+import { tracked } from "@glimmer/tracking";import Controller from "@ember/controller";import { action } from "@ember/object";export default class StyleguideShow extends Controller {+ /**+ * The active group of a sectioned page. Sections that are not split simply ignore it.+ *+ * `null` because no section-independent default exists — the first group's id differs per+ * section — and `StyleguideGroups` already falls back to the first manifest entry when this+ * is absent or unrecognised.+ */+ @tracked group = null;+ queryParams = ["group"];+@actiondummyAction() {}}diff --git a/plugins/styleguide/assets/javascripts/discourse/lib/inline-code.js b/plugins/styleguide/assets/javascripts/discourse/lib/inline-code.jsnew file mode 100644index 00000000000..47dd078c986--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/lib/inline-code.js@@ -0,0 +1,38 @@+import { trustHTML } from "@ember/template";+import { escapeExpression } from "discourse/lib/utilities";++/**+ * Renders backticked spans in a translated string as inline code.+ *+ * Backticks rather than markup in the YAML: a translator can move them without understanding+ * HTML, and escaping stays here rather than being trusted to every string.+ *+ * Split first, then escape each piece. Escaping first and looking for backticks afterwards+ * cannot work — `escape` turns a backtick into an entity, so the pattern being searched for has+ * already been removed by the time it is searched for. Splitting on the raw string keeps the+ * two steps independent of each other's output.+ *+ * @param {string} text - a translated string, optionally containing `backticked` identifiers.+ * @returns {SafeString} the escaped text with backticked spans wrapped in `code`.+ */+export default function inlineCode(text) {+ const parts = String(text ?? "").split("`");++ // An even part count means an odd number of backticks, so the marks are unbalanced. Pairing+ // anyway would code-format the whole tail after the stray one; rendering the string as plain+ // prose keeps a typo in a translation to one visible backtick rather than a mangled sentence.+ if (parts.length % 2 === 0) {+ return trustHTML(escapeExpression(parts.join("`")));+ }++ return trustHTML(+ parts+ .map((part, index) =>+ // Odd indices sat between a pair of backticks.+ index % 2+ ? `<code>${escapeExpression(part)}</code>`+ : escapeExpression(part)+ )+ .join("")+ );+}diff --git a/plugins/styleguide/assets/javascripts/discourse/routes/styleguide/show.js b/plugins/styleguide/assets/javascripts/discourse/routes/styleguide/show.jsindex b647a6a279f..8996d23c49d 100644--- a/plugins/styleguide/assets/javascripts/discourse/routes/styleguide/show.js+++ b/plugins/styleguide/assets/javascripts/discourse/routes/styleguide/show.js@@ -23,4 +23,20 @@ export default class StyleguideShow extends Route {dummy: createData(this.store),});}++ // Query-param stickiness is model-scoped, so `?group=` cannot leak from one section to+ // another. What it does do is survive leaving and returning to the SAME section, which would+ // silently reopen a group the reader had navigated away from. Clearing on exit keeps the bare+ // nav link meaning "the first group".+ //+ // Only on exit. Ember also runs this hook on a model change, but clearing there does not+ // reach the outgoing section's stored value: the write is picked up by an async observer that+ // reads the query-param delegate at flush time, and by then `setup()` has swapped in the+ // incoming model's params. Section-to-section navigation therefore keeps its own stickiness+ // either way, and pretending otherwise would just be a comment that is not true.+ resetController(controller, isExiting) {+ if (isExiting) {+ controller.set("group", null);+ }+ }}diff --git a/plugins/styleguide/assets/javascripts/discourse/templates/styleguide/show.gjs b/plugins/styleguide/assets/javascripts/discourse/templates/styleguide/show.gjsindex 962dc5fb116..0e610c5cc0f 100644--- a/plugins/styleguide/assets/javascripts/discourse/templates/styleguide/show.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/templates/styleguide/show.gjs@@ -1,12 +1,18 @@import StyleguideSection from "discourse/plugins/styleguide/discourse/components/styleguide-section";export default <template>+ {{! The group arg goes to the SECTION COMPONENT only, never to StyleguideSection. That wrapper+ takes exactly one arg today; adding a second invalidates its args tag, so every group change+ would re-fire its didReceiveAttrs hook and re-run the whole section wrapper's setup rather than+ only swapping the group's body. Sections that ignore these args are unaffected. }}<StyleguideSection @section={{@controller.section}}>{{#let @controller.section.component as |SectionComponent|}}<SectionComponent@dummy={{@controller.dummy}}@dummyAction={{@controller.dummyAction}}@siteSettings={{@controller.siteSettings}}+ @section={{@controller.section}}+ @group={{@controller.group}}/>{{/let}}</StyleguideSection>diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scssindex 7f86f13f9bd..0563860efa8 100644--- a/plugins/styleguide/assets/stylesheets/styleguide.scss+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss@@ -2,6 +2,10 @@@import "typography";.styleguide {+ // The comfortable reading measure, for prose that sits directly on the page with nothing+ // bounding it. Prose INSIDE a box does not get this: the box is already the measure, and+ // capping it there just left obvious dead space inside a drawn border.+ --styleguide-measure: 70ch;position: relative;// No top padding: the page header's breadcrumb brings its own top margin, and that alone lines@@ -31,6 +35,7 @@.styleguide-section {.section-description {+ max-width: var(--styleguide-measure);margin-bottom: 2em;}@@ -38,34 +43,6 @@margin: 1em 0;}- .half-size {- width: 50%;- }-- .styleguide-example {- border: 1px dotted var(--content-border-color);- background-color: var(--secondary);- padding: 1rem;-- .example-title {- color: var(--primary-medium);- font-size: var(--font-up-1);- border-bottom: 1px dotted var(--content-border-color);- margin-bottom: 1rem;- display: flex;- align-items: center;- justify-content: space-between;- }-- .rendered {- width: 100%;- position: relative;- flex-direction: column;- gap: 0.5rem;- }- margin-bottom: 2em;- }-.component-properties {width: 100%;@@ -143,7 +120,7 @@p.reason {display: inline;color: var(--primary-medium);- margin: 0 0 0 10px;+ margin: 0 0 0 var(--space-2);}&--char-counter {@@ -153,7 +130,224 @@}}-.buttons-examples .rendered {+.styleguide-example {+ border: 1px solid var(--content-border-color);+ border-radius: var(--d-border-radius);+ background-color: var(--secondary);+ padding: var(--space-4);++ // Ungrouped pages stack their cards; the grid rule overrides this.+ margin-bottom: var(--space-8);++ // The row each slot occupies. Cards in a grid share these rows through subgrid, and a+ // subgrid places its children in DOM order — so a card missing one slot would pull every+ // later slot up a row and take the whole band's alignment with it. Placing each slot+ // explicitly means a missing slot leaves its row empty instead.+ &__header {+ grid-row: 1;+ display: flex;++ // Not `baseline`: the second item is an icon-only button, and `.btn` is inline-flex+ // around an svg, so its synthesised baseline is the bottom margin edge and the toggle+ // hangs below the title rather than centring on it.+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);++ // Header rows stay level between GROUPS, including a group where no card has a code+ // toggle. Within a band the shared subgrid row already does this.+ min-height: var(--space-8);+ margin-bottom: var(--space-2);+ }++ &__title {+ color: var(--primary);+ font-size: var(--font-0);+ font-weight: 600;+ margin: 0;+ }++ &__description code,+ &__try-this code,+ &__note code {+ padding: 0 0.2em;+ background: var(--primary-very-low);+ border-radius: var(--d-border-radius);+ color: var(--primary);+ font-size: 0.9em;+ }++ &__description {+ grid-row: 2;+ color: var(--primary-high);+ margin: 0 0 var(--space-4);+ }++ &__try-this {+ grid-row: 3;+ display: flex;+ gap: var(--space-2);+ color: var(--primary-high);+ background: var(--primary-very-low);+ border-inline-start: 2px solid var(--tertiary);+ padding: var(--space-2) var(--space-3);+ margin: 0 0 var(--space-4);+ }++ &__try-this-label {+ color: var(--primary);+ font-weight: 600;+ white-space: nowrap;+ }++ // The instruction as ONE flex item, so a sentence containing inline code still wraps as a+ // sentence. min-width:0 lets it shrink below the intrinsic width of a long code span+ // instead of pushing the row wider.+ &__try-this-text {+ flex: 1 1 auto;+ min-width: 0;+ }++ // Deliberately left `overflow: visible`. Examples render floating content in place rather+ // than through a portal, positioned against this element, and any non-visible overflow+ // would clip it — on either axis, since a non-visible value on one forces the other.+ &__body {+ grid-row: 4;+ width: 100%;+ position: relative;+ min-width: 0;+ }++ // Unadorned on purpose: giving it the instruction's fill and stripe sandwiched the control+ // between two identical bars.+ &__note {+ grid-row: 5;+ color: var(--primary-medium);+ font-size: var(--font-down-1);+ margin: var(--space-3) 0 0;+ }++ // An opt-in authoring class, like `__note-list`: an example applies it to its own output+ // element inside the default block. Styled as a descendant rather than placed as a slot,+ // because that element lands within `__body` and is not a grid item of the card, so a+ // `grid-row` here would be inert. Documented in the README and the component JSDoc.+ &__result {+ display: block;+ color: var(--primary);+ background: var(--primary-very-low);+ border: 1px solid var(--content-border-color);+ border-radius: var(--d-border-radius);+ padding: var(--space-2) var(--space-3);+ margin: var(--space-3) 0 0;+ }++ &__note-list {+ margin: 0;+ padding-inline-start: var(--space-5);++ li + li {+ margin-block-start: var(--space-1);+ }+ }++ &__code {+ grid-row: 6;+ min-width: 0;+ max-width: 100%;+ margin-block-start: var(--space-4);++ pre {+ margin: 0;+ }+ }++ .d-header-wrap {+ position: relative;+ z-index: 0;+ }+}++.styleguide-subnav {+ position: sticky;++ // Below the site header. The fallback matters: --header-offset is written at runtime after+ // the header's first measurement, and until then an unresolved var() makes `top` compute+ // to `auto`, which silently stops the bar sticking at all.+ top: var(--header-offset, 0);++ // Above static card content, and deliberately BELOW the float layer: a bar that covered the+ // menu the reader just opened is worse than a menu that overlaps the bar while scrolling.+ z-index: z("base");++ // Required, not decorative: the overflow-nav's scroll fades and its scroll buttons both+ // paint --secondary, so a transparent sticky bar would show content through them.+ background: var(--secondary);+ margin-bottom: var(--space-6);+ padding-block: var(--space-2);+}++.styleguide-group {+ /* Cards subgrid over one shared band of rows, so every slot lines up across a row+ instead of drifting with the prose above it. Two rules make it hold: each slot is+ placed explicitly (see `.styleguide-example`), because a subgrid auto-places in DOM+ order and one missing slot would shift every later one; and row spacing is margin,+ not `row-gap`, on BOTH sides, so an empty row — the code row, almost always — costs+ nothing. */++ &__examples {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(min(22rem, 100%), 1fr));+ column-gap: var(--space-6);+ row-gap: 0;++ // Sparse placement on purpose: `dense` would backfill a gap left by a `--wide` card+ // with a later card, so visual order would diverge from the DOM order a keyboard or+ // screen reader follows. The cost is that a full-width card only lands flush when the+ // cards before it fill their row — guaranteed only when it comes first, since the+ // column count here is responsive.+ > .styleguide-example {+ display: grid;++ // Rows only: the card is one parent column wide, so subgridding the column axis+ // would hand it a single track it has no use for.+ grid-template-columns: 1fr;+ grid-template-rows: subgrid;++ // header · description · try-this · body · note · code+ grid-row: span 6;+ gap: 0;++ // Grid items default to min-width: auto, so a long code line or an unbreakable+ // label would otherwise stretch its track.+ min-width: 0;++ // Carried by the card rather than the parent's row-gap, per the note above. Uniform+ // across cards, so their bottom edges stay aligned.+ margin-bottom: var(--space-6);++ // Cards that own their width — a side-by-side comparison, a control strip, the+ // synthesis picker — take the whole row rather than being squeezed into a track.+ // They still span the band, so they subgrid against rows only they fill.+ &.--wide {+ grid-column: 1 / -1;+ }+ }+ }++ &__title {+ font-size: var(--font-up-2);+ font-weight: 600;+ margin: 0 0 var(--space-1);+ }++ &__description {+ color: var(--primary-high);+ max-width: var(--styleguide-measure);+ margin: 0 0 var(--space-6);+ }+}++.buttons-examples .styleguide-example__body {button {margin-right: 0.5em;margin-bottom: 0.5em;@@ -178,14 +372,16 @@.styleguide-icons {display: grid;- grid-template-columns: 150px 150px 150px 150px 150px;- gap: 10px;++ // Track count follows the width so the grid does not overflow on a narrow viewport.+ grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr));+ gap: var(--space-2);.styleguide-icon {background-color: var(--primary-low);- margin: 3px;+ margin: var(--space-1);text-align: center;- padding: 10px;+ padding: var(--space-2);overflow: hidden;svg {@@ -202,7 +398,7 @@}.styleguide__component {- border: 1px dotted var(--content-border-color);+ border: 1px solid var(--content-border-color);margin-bottom: 2rem;position: relative;@@ -210,7 +406,7 @@position: absolute;top: 0;right: 0;- padding: 3px 6px;+ padding: var(--space-1) var(--space-2);background: var(--primary-low);max-width: 25%;@@ -241,13 +437,6 @@}}-.styleguide-example {- .d-header-wrap {- position: relative;- z-index: 0;- }-}-.more-topics-examples {.more-topics__container {flex-grow: 1;diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.ymlindex c687ca456f6..066c4e498b4 100644--- a/plugins/styleguide/config/locales/client.en.yml+++ b/plugins/styleguide/config/locales/client.en.yml@@ -9,6 +9,11 @@ en:title: "Styleguide"welcome: "To get started, choose a section from the navigation menu."+ example:+ toggle_code: "Toggle code sample"+ try_this: "Try this:"+ code_region: "Source snippet: %{title}"+categories:syntax: Syntaxatoms: Atomsdiff --git a/plugins/styleguide/plugin.rb b/plugins/styleguide/plugin.rbindex c48c7ed0ad9..e8811bc8afa 100644--- a/plugins/styleguide/plugin.rb+++ b/plugins/styleguide/plugin.rb@@ -19,6 +19,13 @@ Discourse::Application.routes.append { mount Styleguide::Engine, at: "/styleguidafter_initialize doregister_asset_filter do |type, request, opts|- (opts[:path] || "").start_with?("#{Discourse.base_path}/styleguide")+ path = opts[:path]++ # Keep this plugin's assets off unrelated pages. The QUnit page is the one caller that+ # resolves plugin JS without a request, leaving no path to judge; treating that as "not my+ # page" dropped the plugin before its test bundle was collected, which made this plugin's+ # own JS tests unrunnable. Narrowed to JS on purpose — stylesheet precompilation also+ # resolves CSS without a request, and that should stay excluded.+ (type == :js && path.blank?) || path.to_s.start_with?("#{Discourse.base_path}/styleguide")endenddiff --git a/plugins/styleguide/spec/integration/assets_spec.rb b/plugins/styleguide/spec/integration/assets_spec.rbindex 0e6c825b5b5..fa86c14fae4 100644--- a/plugins/styleguide/spec/integration/assets_spec.rb+++ b/plugins/styleguide/spec/integration/assets_spec.rb@@ -1,22 +1,45 @@# frozen_string_literal: trueRSpec.describe "Styleguide assets" do- before do- SiteSetting.styleguide_enabled = true- sign_in(Fabricate(:admin))- end+ context "when rendering a page" do+ before do+ SiteSetting.styleguide_enabled = true+ sign_in(Fabricate(:admin))+ end- context "when visiting homepage" do- it "doesn't load styleguide assets" do- get "/"- expect(response.body).to_not include('data-target="styleguide"')+ context "when visiting homepage" do+ it "doesn't load styleguide assets" do+ get "/"+ expect(response.body).to_not include('data-target="styleguide"')+ end+ end++ context "when visiting styleguide" do+ it "loads styleguide assets" do+ get "/styleguide"+ expect(response.body).to include('data-target="styleguide"')+ endendend- context "when visiting styleguide" do- it "loads styleguide assets" do- get "/styleguide"- expect(response.body).to include('data-target="styleguide"')+ # The QUnit page resolves plugin JS with no request, so there is no path to match. Without the+ # no-request clause this plugin is dropped before its test bundle is collected and its JS tests+ # cannot run at all; without the `:js` narrowing, stylesheet precompilation — which also has no+ # request — would start pulling this plugin's CSS into every target.+ describe "the asset filter" do+ let(:plugin) { Discourse.plugins.find { |installed| installed.directory_name == "styleguide" } }++ it "keeps JS with no request, so the plugin's own QUnit tests can load" do+ expect(Discourse.apply_asset_filters([plugin], :js, nil)).to eq([plugin])+ end++ it "still drops CSS with no request" do+ expect(Discourse.apply_asset_filters([plugin], :css, nil)).to be_empty+ end++ it "still drops JS on an unrelated page" do+ request = ActionDispatch::TestRequest.create("PATH_INFO" => "/latest")+ expect(Discourse.apply_asset_filters([plugin], :js, request)).to be_emptyendendenddiff --git a/plugins/styleguide/spec/system/page_objects/pages/styleguide.rb b/plugins/styleguide/spec/system/page_objects/pages/styleguide.rbindex 3376e69ca79..4274b04ef73 100644--- a/plugins/styleguide/spec/system/page_objects/pages/styleguide.rb+++ b/plugins/styleguide/spec/system/page_objects/pages/styleguide.rb@@ -47,6 +47,53 @@ module PageObjectsdef has_no_color_selector?has_no_css?(".toggle-color-mode")end++ # Addressed by its visible title. Every example has one, but they are not unique across+ # every page — the forms section renders two examples titled "Input" — so a page with+ # duplicates needs a scoped lookup rather than this one, which would raise `Ambiguous`.+ def example(title)+ find("[data-test-example-title]", text: title, exact_text: true).ancestor(+ ".styleguide-example",+ )+ end++ # Found by accessible name rather than class, so a missing translation fails the test+ # instead of silently clicking a button labelled with the bracketed key.+ def example_source_toggle(title)+ example(title).find(:button, I18n.t("js.styleguide.example.toggle_code"))+ end++ def toggle_example_source(title)+ example_source_toggle(title).click+ end++ def has_example_source?(title, text:)+ example(title).has_css?(".styleguide-example__code", text: text)+ end++ # `visible: :all` on purpose: the source panel is meant to UNMOUNT, and a plain+ # `has_no_css?` would also pass for a CSS-hidden node, hiding that regression.+ def has_no_example_source?(title)+ example(title).has_no_css?(".styleguide-example__code", visible: :all)+ end++ # `expanded` is a boolean; it interpolates to the attribute's "true"/"false".+ def has_example_source_expanded?(title, expanded)+ example(title).has_css?(+ "button.styleguide-example__code-toggle[aria-expanded='#{expanded}']",+ )+ end++ # The toggle's `aria-controls` must name the revealed region, so the two are asserted+ # against each other rather than each against a hardcoded id.+ def has_example_source_wired?(title)+ card = example(title)+ # The attribute is part of the selector so Capybara waits for it, rather than reading it+ # once off a button that is present in both states.+ controls =+ card.find("button.styleguide-example__code-toggle[aria-controls]")["aria-controls"]+ controls.present? && card.has_css?(".styleguide-example__code##{controls}")+ endendendenddiff --git a/plugins/styleguide/spec/system/styleguide_example_spec.rb b/plugins/styleguide/spec/system/styleguide_example_spec.rbnew file mode 100644index 00000000000..cc478ac40f4--- /dev/null+++ b/plugins/styleguide/spec/system/styleguide_example_spec.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++RSpec.describe "Styleguide example card" do+ fab!(:admin)++ let(:styleguide) { PageObjects::Pages::Styleguide.new }+ let(:title) { "<DCharCounter>" }++ before do+ SiteSetting.styleguide_enabled = true+ sign_in(admin)+ end++ it "reveals and hides an example's source" do+ visit "/styleguide/molecules/char-counter"++ expect(styleguide).to have_no_example_source(title)+ expect(styleguide).to have_example_source_expanded(title, false)++ styleguide.toggle_example_source(title)++ # Asserted on an import line rather than the component name: the name appears inside the+ # template too, so it cannot tell `?source=file` output from `?source=template` output,+ # which is the distinction the source loader exists to make. An import can only have come+ # from the whole module.+ expect(styleguide).to have_example_source(+ title,+ text: 'import Component from "@glimmer/component"',+ )+ expect(styleguide).to have_example_source_expanded(title, true)+ expect(styleguide).to have_example_source_wired(title)++ styleguide.toggle_example_source(title)++ expect(styleguide).to have_no_example_source(title)+ expect(styleguide).to have_example_source_expanded(title, false)+ end+enddiff --git a/plugins/styleguide/test/javascripts/integration/components/styleguide-example-test.gjs b/plugins/styleguide/test/javascripts/integration/components/styleguide-example-test.gjsnew file mode 100644index 00000000000..d22c4f02f26--- /dev/null+++ b/plugins/styleguide/test/javascripts/integration/components/styleguide-example-test.gjs@@ -0,0 +1,245 @@+import { click, find, findAll, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { i18n } from "discourse-i18n";+import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";++const SOURCE = `import Thing from "discourse/thing";`;++module("Integration | Component | <StyleguideExample />", function (hooks) {+ setupRenderingTest(hooks);++ // An ungrouped page has only the page header's h1 above the card, so h2 is the level that+ // keeps the outline contiguous. h3 is for cards inside a group, whose own heading is the h2.+ test("titles default to h2", async function (assert) {+ await render(+ <template>+ <StyleguideExample @title="Buttons">demo</StyleguideExample>+ </template>+ );++ assert.dom("h2.styleguide-example__title").hasText("Buttons");+ assert.dom("h3.styleguide-example__title").doesNotExist();+ });++ test("renders h3 when nested in a group", async function (assert) {+ await render(+ <template>+ <StyleguideExample+ @title="Buttons"+ @headingLevel={{3}}+ >demo</StyleguideExample>+ </template>+ );++ assert.dom("h3.styleguide-example__title").hasText("Buttons");+ assert.dom("h2.styleguide-example__title").doesNotExist();+ });++ test("no code arg means no source toggle", async function (assert) {+ await render(+ <template>+ <StyleguideExample @title="Tokens">demo</StyleguideExample>+ </template>+ );++ assert+ .dom(".styleguide-example__code-toggle")+ .doesNotExist("a purely visual example offers nothing to reveal");+ });++ test("the source toggle reveals and hides the snippet", async function (assert) {+ await render(+ <template>+ <StyleguideExample+ @title="Buttons"+ @code={{SOURCE}}+ >demo</StyleguideExample>+ </template>+ );++ assert.dom(".styleguide-example__code").doesNotExist();+ assert+ .dom(".styleguide-example__code-toggle")+ .hasAttribute("aria-expanded", "false");++ await click(".styleguide-example__code-toggle");++ assert.dom(".styleguide-example__code").exists();+ assert+ .dom(".styleguide-example__code-toggle")+ .hasAttribute("aria-expanded", "true");++ await click(".styleguide-example__code-toggle");++ assert.dom(".styleguide-example__code").doesNotExist();+ });++ // aria-controls may only name an element that exists, and the panel is unmounted while+ // collapsed, so the attribute has to come and go with it.+ test("aria-controls names the revealed region, and only while it exists", async function (assert) {+ await render(+ <template>+ <StyleguideExample+ @title="Buttons"+ @code={{SOURCE}}+ >demo</StyleguideExample>+ </template>+ );++ assert+ .dom(".styleguide-example__code-toggle")+ .doesNotHaveAttribute("aria-controls");++ await click(".styleguide-example__code-toggle");++ const controls = find(".styleguide-example__code-toggle").getAttribute(+ "aria-controls"+ );++ assert.dom(`#${controls}`).hasClass("styleguide-example__code");+ assert+ .dom(".styleguide-example__code")+ .hasAttribute("role", "region")+ .hasAttribute(+ "aria-label",+ i18n("styleguide.example.code_region", { title: "Buttons" })+ );++ await click(".styleguide-example__code-toggle");++ assert+ .dom(".styleguide-example__code-toggle")+ .doesNotHaveAttribute(+ "aria-controls",+ "the reference goes away with the region it named"+ );+ });++ // The id comes from a module-level counter precisely so two cards on one page do not collide.+ // With a constant id, every toggle would point at the first card's panel and the page would+ // ship duplicate DOM ids.+ test("two cards on a page get distinct region ids", async function (assert) {+ await render(+ <template>+ <StyleguideExample @title="First" @code={{SOURCE}}>a</StyleguideExample>+ <StyleguideExample+ @title="Second"+ @code={{SOURCE}}+ >b</StyleguideExample>+ </template>+ );++ const toggles = findAll(".styleguide-example__code-toggle");+ await click(toggles[0]);+ await click(toggles[1]);++ const ids = findAll(".styleguide-example__code").map((panel) => panel.id);++ assert.strictEqual(ids.length, 2, "both panels are open");+ assert.notStrictEqual(ids[0], ids[1], "the two panels have different ids");++ findAll(".styleguide-example").forEach((card, index) => {+ const controls = card+ .querySelector(".styleguide-example__code-toggle")+ .getAttribute("aria-controls");++ assert.strictEqual(+ controls,+ ids[index],+ `card ${index} points at its own panel`+ );+ });+ });++ test("renders backticked prose as inline code", async function (assert) {+ await render(+ <template>+ <StyleguideExample+ @title="Buttons"+ @description="never mutates `@value`"+ >+ demo+ </StyleguideExample>+ </template>+ );++ assert.dom(".styleguide-example__description code").hasText("@value");+ });++ test("a named block wins over the string arg", async function (assert) {+ await render(+ <template>+ <StyleguideExample @title="Buttons" @description="from the arg">+ <:description><em class="from-block">from the block</em></:description>+ <:default>demo</:default>+ </StyleguideExample>+ </template>+ );++ assert.dom(".styleguide-example__description .from-block").exists();+ assert+ .dom(".styleguide-example__description")+ .doesNotIncludeText("from the arg");+ });++ test("renders the try-this and note slots from string args", async function (assert) {+ await render(+ <template>+ <StyleguideExample+ @title="Buttons"+ @tryThis="Press it twice"+ @note="It counts every press"+ >demo</StyleguideExample>+ </template>+ );++ assert+ .dom(".styleguide-example__try-this")+ .includesText("Press it twice")+ .includesText(i18n("styleguide.example.try_this"));+ assert.dom(".styleguide-example__note").hasText("It counts every press");+ });++ test("try-this and note accept blocks, which win over the args", async function (assert) {+ await render(+ <template>+ <StyleguideExample @title="Buttons" @tryThis="arg try" @note="arg note">+ <:tryThis><em class="block-try">block try</em></:tryThis>+ <:note><ul class="block-note"><li>block note</li></ul></:note>+ <:default>demo</:default>+ </StyleguideExample>+ </template>+ );++ assert.dom(".styleguide-example__try-this .block-try").exists();+ assert.dom(".styleguide-example__try-this").doesNotIncludeText("arg try");+ assert.dom(".styleguide-example__note .block-note").exists();+ assert.dom(".styleguide-example__note").doesNotIncludeText("arg note");+ });++ test("omitted slots render no elements", async function (assert) {+ await render(+ <template>+ <StyleguideExample @title="Buttons">demo</StyleguideExample>+ </template>+ );++ assert.dom(".styleguide-example__description").doesNotExist();+ assert.dom(".styleguide-example__try-this").doesNotExist();+ assert.dom(".styleguide-example__note").doesNotExist();+ });++ test("passes through plain HTML attributes", async function (assert) {+ await render(+ <template>+ <StyleguideExample @title="Buttons" class="--wide" data-flavour="x">+ demo+ </StyleguideExample>+ </template>+ );++ assert.dom(".styleguide-example").hasClass("--wide");+ assert.dom(".styleguide-example").hasAttribute("data-flavour", "x");+ });+});diff --git a/plugins/styleguide/test/javascripts/integration/components/styleguide-groups-test.gjs b/plugins/styleguide/test/javascripts/integration/components/styleguide-groups-test.gjsnew file mode 100644index 00000000000..49bc5c03f01--- /dev/null+++ b/plugins/styleguide/test/javascripts/integration/components/styleguide-groups-test.gjs@@ -0,0 +1,500 @@+import { tracked } from "@glimmer/tracking";+import { getOwner } from "@ember/owner";+import { find, findAll, focus, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import StyleguideGroups from "discourse/plugins/styleguide/discourse/components/styleguide-groups";++const GROUPS = [+ { id: "start", title: "Start here", description: "The first group." },+ { id: "data", title: "Data" },+ { id: "states", title: "States" },+];++// Deliberately shares the `start` id with GROUPS, which is legal: ids only have to be unique+// within one manifest.+const OTHER_GROUPS = [{ id: "start", title: "Getting going" }];++const SECTION = { id: "select", category: "molecules" };++module("Integration | Component | <StyleguideGroups />", function (hooks) {+ setupRenderingTest(hooks);++ test("renders the requested group", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="data"+ as |Group|+ >+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom("[data-test-styleguide-group='data']").exists();+ assert.dom("[data-test-styleguide-group='start']").doesNotExist();+ });++ // Unmounting is load-bearing: it is what resets a group's live components. A CSS-hidden+ // variant would leave them running, so absence is asserted rather than invisibility.+ test("an inactive group is not rendered at all", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="data"+ as |Group|+ >+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom(".styleguide-group").exists({ count: 1 });+ assert.dom(".styleguide-groups__body").doesNotIncludeText("start body");+ });++ test("falls back to the first group when none is requested", async function (assert) {+ await render(+ <template>+ <StyleguideGroups @groups={{GROUPS}} @section={{SECTION}} as |Group|>+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom("[data-test-styleguide-group='start']").exists();+ });++ test("falls back to the first group when the id is unknown", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="nope"+ as |Group|+ >+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert+ .dom("[data-test-styleguide-group='start']")+ .exists("an unrecognised query param still renders a usable page");+ });++ test("the group reads its heading and description from the manifest", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="start"+ as |Group|+ >+ <Group @id="start">start body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom(".styleguide-group__title").hasText("Start here");+ assert.dom(".styleguide-group__description").hasText("The first group.");+ });++ test("a group without a description renders no description element", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="data"+ as |Group|+ >+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom(".styleguide-group__description").doesNotExist();+ });++ test("the region is labelled by its own heading", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="start"+ as |Group|+ >+ <Group @id="start">start body</Group>+ </StyleguideGroups>+ </template>+ );++ const labelledBy =+ find(".styleguide-group").getAttribute("aria-labelledby");++ assert.dom(`#${labelledBy}`).hasText("Start here");+ assert.dom(".styleguide-group").hasAttribute("role", "region");+ });++ test("marks only the active pill in the subnav", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="data"+ as |Group|+ >+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert+ .dom("[data-test-styleguide-subnav-link='data']")+ .hasAttribute("aria-current", "page")+ .hasClass("active");++ assert+ .dom("[data-test-styleguide-subnav-link='start']")+ .doesNotHaveAttribute(+ "aria-current",+ "the default group is not current while another is open"+ );+ });++ test("every manifest entry gets a pill, in manifest order", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="start"+ as |Group|+ >+ <Group @id="start">start body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.deepEqual(+ findAll("[data-test-styleguide-subnav-link]").map(+ (link) => link.dataset.testStyleguideSubnavLink+ ),+ ["start", "data", "states"],+ "the manifest is the single source of order, not the yielded blocks"+ );+ });++ // The whole point of yielding a curried example: a grouped page keeps h1 -> h2 -> h3 without+ // any call site restating the level. Passing the bare component instead would leave the+ // group's own h2 followed by sibling h2s, and nothing else would fail.+ test("the yielded example renders at h3, under the group's h2", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="start"+ as |Group|+ >+ <Group @id="start" as |Example|>+ <Example @title="A thing">demo</Example>+ </Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom("h2.styleguide-group__title").hasText("Start here");+ assert.dom("h3.styleguide-example__title").hasText("A thing");+ assert+ .dom("h2.styleguide-example__title")+ .doesNotExist("the example must not sit at the group's own level");+ });++ // Group ids are unique only within one manifest, so deriving the heading id from `@id` would+ // emit duplicate DOM ids the moment a page carries two sets of groups sharing a name — and+ // `aria-labelledby` on the second region would resolve to the first region's heading.+ test("two sets of groups sharing an id still label their own headings", async function (assert) {+ await render(+ <template>+ <StyleguideGroups @groups={{GROUPS}} @section={{SECTION}} as |Group|>+ <Group @id="start">first body</Group>+ </StyleguideGroups>+ <StyleguideGroups+ @groups={{OTHER_GROUPS}}+ @section={{SECTION}}+ as |Group|+ >+ {{! The repeated id is the point of this test, and it is a component argument rather+ than a DOM id attribute — the rendered ids come from a counter. Scoped to this line so+ the rule keeps working for the rest of the file. }}+ {{! eslint-disable-next-line ember/template-no-duplicate-id }}+ <Group @id="start">second body</Group>+ </StyleguideGroups>+ </template>+ );++ const regions = findAll(".styleguide-group");+ assert.strictEqual(regions.length, 2, "both groups rendered");++ const [first, second] = regions.map((region) =>+ region.getAttribute("aria-labelledby")+ );++ assert.notStrictEqual(first, second, "the two headings have different ids");+ assert.dom(`#${first}`).hasText("Start here");+ assert.dom(`#${second}`).hasText("Getting going");+ });++ test("names the sub-navigation landmark", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="start"+ @ariaLabel="Select examples"+ as |Group|+ >+ <Group @id="start">start body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom("nav").hasAttribute("aria-label", "Select examples");+ });++ // Everything below changes the active group AFTER the initial render. Without that, the body+ // swap, the focus recovery and the announcement could all be deleted without a single+ // failure. The `scrollTop()` in the same handler is deliberately NOT claimed here: it+ // early-returns under `isTesting()`, so no test can observe it.+ test("swapping the active group swaps the rendered body", async function (assert) {+ const state = new (class {+ @tracked active = "start";+ })();++ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active={{state.active}}+ as |Group|+ >+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.dom("[data-test-styleguide-group='start']").exists();++ state.active = "data";+ await settled();++ assert.dom("[data-test-styleguide-group='data']").exists();+ assert+ .dom("[data-test-styleguide-group='start']")+ .doesNotExist("the outgoing group unmounts rather than hiding");+ assert+ .dom("[data-test-styleguide-subnav-link='data']")+ .hasAttribute("aria-current", "page", "the subnav follows the change");+ });++ test("announces the new group, since nothing else signals the swap", async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ const announced = [];+ // Priority is recorded too: swapping polite for assertive would interrupt a screen reader+ // mid-sentence, and a message-only assertion would not notice.+ a11y.announce = (message, type) => announced.push([message, type]);++ const state = new (class {+ @tracked active = "start";+ })();++ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active={{state.active}}+ as |Group|+ >+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.deepEqual(announced, [], "nothing is announced on first render");++ state.active = "data";+ await settled();++ assert.deepEqual(+ announced,+ [["Data", "polite"]],+ "the incoming group's title is announced, politely"+ );+ });++ // The real sequence, not a stand-in for it: focus sits on a control INSIDE the outgoing+ // group, that node unmounts with the group, focus falls to <body>, and only then is it ours+ // to recover.+ test("restores focus when the outgoing group took it down with it", async function (assert) {+ const state = new (class {+ @tracked active = "start";+ })();++ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active={{state.active}}+ as |Group|+ >+ <Group @id="start"><button+ type="button"+ id="inside"+ >x</button></Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ await focus("#inside");+ assert.dom("#inside").isFocused("precondition: focus is inside the group");++ state.active = "data";+ await settled();++ assert.dom("[data-test-styleguide-group='data']").isFocused();+ });++ // The other half of the guard. Focus that SURVIVES the swap is not ours to move — taking it+ // would yank the reader out of the subnav they are still using.+ test("leaves surviving focus alone", async function (assert) {+ const state = new (class {+ @tracked active = "start";+ })();++ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active={{state.active}}+ as |Group|+ >+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ await focus("[data-test-styleguide-subnav-link='data']");++ state.active = "data";+ await settled();++ assert+ .dom("[data-test-styleguide-subnav-link='data']")+ .isFocused("the pill that was clicked keeps focus");+ assert.dom("[data-test-styleguide-group='data']").isNotFocused();+ });++ // The pills are links, not tabs: each is a real URL so it carries history and opens in a new+ // tab. Tab roles would override the link role and lose that.+ test("the pills are links carrying the group query param", async function (assert) {+ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="start"+ as |Group|+ >+ <Group @id="start">start body</Group>+ </StyleguideGroups>+ </template>+ );++ assert+ .dom("[data-test-styleguide-subnav-link='data']")+ .hasTagName("a")+ .hasAttribute("href", /group=data/);+ });++ // A block whose id is in no manifest entry can never match `activeId`, which only ever holds+ // a manifest id, so it renders nothing at all and the page is a subnav above an empty body.+ // Silent because there is no error state to hit: the group is simply never the active one.+ test("warns about a group id that is in no manifest entry", async function (assert) {+ const stub = sinon.stub(console, "warn");++ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="data"+ as |Group|+ >+ <Group @id="dat">typo body</Group>+ <Group @id="data">data body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.true(+ stub.calledOnceWithMatch('@id="dat"'),+ "warns once, naming the id that matched nothing"+ );++ stub.restore();+ });++ // Guards the check against the two ways it could be trivially satisfied: warning for every+ // group, or warning for every group that is not the active one. Both would fire here, where+ // `start` and `states` are inactive but perfectly valid.+ test("stays quiet when every group id matches the manifest", async function (assert) {+ const stub = sinon.stub(console, "warn");++ await render(+ <template>+ <StyleguideGroups+ @groups={{GROUPS}}+ @section={{SECTION}}+ @active="data"+ as |Group|+ >+ <Group @id="start">start body</Group>+ <Group @id="data">data body</Group>+ <Group @id="states">states body</Group>+ </StyleguideGroups>+ </template>+ );++ assert.false(+ stub.calledWithMatch("StyleguideGroup"),+ "an inactive but declared group is not a mismatch"+ );++ stub.restore();+ });+});diff --git a/plugins/styleguide/test/javascripts/unit/lib/inline-code-test.js b/plugins/styleguide/test/javascripts/unit/lib/inline-code-test.jsnew file mode 100644index 00000000000..aa02865a346--- /dev/null+++ b/plugins/styleguide/test/javascripts/unit/lib/inline-code-test.js@@ -0,0 +1,66 @@+import { module, test } from "qunit";+import inlineCode from "discourse/plugins/styleguide/discourse/lib/inline-code";++module("Unit | Lib | inline-code", function () {+ test("wraps a backticked span in code", function (assert) {+ assert.strictEqual(+ inlineCode("never mutates `@value`").toString(),+ "never mutates <code>@value</code>",+ "the marks are consumed and the span becomes an element"+ );+ });++ test("handles several spans in one string", function (assert) {+ assert.strictEqual(+ inlineCode("`@a` then `@b`").toString(),+ "<code>@a</code> then <code>@b</code>"+ );+ });++ test("escapes markup outside a span", function (assert) {+ assert.strictEqual(+ inlineCode("<script>alert(1)</script>").toString(),+ "<script>alert(1)</script>",+ "text is escaped rather than trusted through"+ );+ });++ test("escapes markup inside a span", function (assert) {+ assert.strictEqual(+ inlineCode("pass `<img onerror=x>` here").toString(),+ "pass <code><img onerror=x></code> here",+ "the code wrapper never becomes an injection point"+ );+ });++ test("escapes quotes and ampersands", function (assert) {+ assert.strictEqual(+ inlineCode(`a & b "c" 'd'`).toString(),+ "a & b "c" 'd'"+ );+ });++ // The whole point of splitting before escaping: escaping first would turn the backtick into+ // an entity, so the pattern being searched for would already be gone.+ test("an unmatched backtick does not code-format the tail", function (assert) {+ assert.strictEqual(+ inlineCode("Pass `@value to the child").toString(),+ "Pass `@value to the child",+ "an odd backtick count renders as prose, keeping the stray mark visible"+ );+ });++ test("an unmatched backtick still escapes markup", function (assert) {+ assert.strictEqual(+ inlineCode("` <b>x</b>").toString(),+ "` <b>x</b>",+ "the unbalanced path escapes as thoroughly as the paired one"+ );+ });++ test("handles empty and nullish input", function (assert) {+ assert.strictEqual(inlineCode("").toString(), "");+ assert.strictEqual(inlineCode(null).toString(), "");+ assert.strictEqual(inlineCode(undefined).toString(), "");+ });+});