A platform for community discussion. Free, open, simple.
FEATURE: Design wizard (#42178)
Jordan Vidrine8933d383f245
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scssindex 882c9106c8a..fa74929a94e 100644--- a/app/assets/stylesheets/common/components/_index.scss+++ b/app/assets/stylesheets/common/components/_index.scss@@ -57,6 +57,7 @@@import "relative-time-picker";@import "add-pm-participants";@import "admin-onboarding-banner";+@import "design-wizard";@import "download-calendar";@import "sidebar/edit-navigation-menu/categories-modal";@import "sidebar/edit-navigation-menu/modal";diff --git a/app/assets/stylesheets/common/components/admin-onboarding-banner.scss b/app/assets/stylesheets/common/components/admin-onboarding-banner.scssindex 06f3158a936..ea0b8e4b71d 100644--- a/app/assets/stylesheets/common/components/admin-onboarding-banner.scss+++ b/app/assets/stylesheets/common/components/admin-onboarding-banner.scss@@ -2,104 +2,145 @@@import "common/foundation/mixins";.admin-onboarding-banner {- margin-bottom: var(--space-4);- color: var(--secondary);+ padding-block: var(--d-main-content-gap);@include viewport.until(sm) {- display: none;+ padding-block: 0;+ padding-block-end: var(--space-4);}&__wrap {box-sizing: border-box;position: relative;- padding: var(--space-5) var(--space-8);- border-radius: var(--d-border-radius-large);- background: var(--accent-color, var(--tertiary-low));- color: var(--accent-text-color, var(--primary));-- @include viewport.until(md) {- padding: var(--space-4) var(--space-5);- margin-top: var(--space-2);- }-- @include viewport.until(sm) {- display: block;- padding: var(--space-2);- margin-top: 0;- }+ border-radius: var(--d-border-radius);+ border: 1px solid var(--content-border-color);+ overflow: hidden;+ }- .btn-close {- position: absolute;- top: var(--space-1);- right: var(--space-1);+ &__title {+ font-weight: 600;+ }- .d-icon {- color: var(--accent-text-color, var(--primary));- }- }+ &__title-icon {+ margin-right: var(--space-2);+ font-size: var(--font-down-1);}&__header {display: flex;align-items: center;justify-content: space-between;- margin-bottom: var(--space);+ height: min-content;+ padding-inline-start: var(--space-4);+ background: var(--background-color, var(--primary-100));+ }- @include viewport.until(md) {- font-size: var(--font-down-1);- }+ &__header-text {+ display: flex;+ flex-direction: row;+ gap: var(--space-4);+ align-items: center;+ }++ &__subtitle {+ font-size: var(--font-down-2);+ color: var(--primary-700);}&__content {text-align: center;-- @include viewport.until(md) {- margin-top: var(--space-3);- }}&__steps {- margin-bottom: var(--space-2);- display: grid;- grid-template-columns: 1fr 1fr 1fr;+ display: flex;+ flex-direction: column;+ }++ .onboarding-step {+ display: flex;flex-direction: row;+ padding: var(--space-2) var(--space-4);+ border-bottom: 1px solid var(--content-border-color);+ gap: var(--space-4);align-items: center;- gap: var(--space-2) var(--space-12);- text-wrap: pretty;- @include viewport.until(md) {- font-size: var(--font-down-1);+ @include viewport.until(sm) {+ display: grid;+ gap: 0;+ grid-template-columns: 1fr auto;+ grid-template-areas: "text action" "description action";+ padding: var(--space-2);}+ }- .onboarding-step {- display: grid;- grid-template-rows: subgrid;- grid-row: span 3;- justify-content: start;- flex-direction: column;- align-items: flex-start;- text-align: left;- gap: var(--space-2);-- &__checkbox {- gap: var(--space-2);- display: flex;- align-items: baseline;- font-weight: bold;-- .d-icon {- position: relative;- top: var(--space-half);- }- }+ .onboarding-step:last-child {+ border-bottom: none;+ }- &__text {- max-width: 16em;- }+ .onboarding-step:first-child {+ border-top: 1px solid var(--content-border-color);+ }- button {- margin-top: var(--space-2);- }+ .onboarding-step__checkbox {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--space-2);++ @include viewport.until(sm) {+ display: block;+ justify-self: baseline;+ }+ }++ .onboarding-step__checkbox-icon {+ font-size: var(--font-down-1);++ &.--completed {+ color: var(--success);+ }+ }++ .onboarding-step__title {+ font-weight: 600;+ font-size: var(--font-down-1);++ @include viewport.until(sm) {+ grid-area: text;+ }+ }++ .onboarding-step__description {+ font-size: var(--font-down-1);+ color: var(--primary-700);++ @include viewport.until(sm) {+ grid-area: description;+ justify-self: baseline;+ }+ }++ .onboarding-step__action {+ margin-left: auto;++ @include viewport.until(sm) {+ grid-area: action;+ margin-left: 0;+ }++ --d-button-transparent-text-color: var(--tertiary);+ }++ .onboarding-step__action .btn-link {+ font-weight: 600;++ &.--completed {+ --d-button-transparent-text-color: var(--primary-medium);+ font-weight: 400;+ }++ &.--completed:hover {+ --d-button-transparent-text-color--hover: var(--primary-high);}}}@@ -184,87 +225,3 @@max-width: var(--modal-max-width);}}--.theme-picker-modal {- &__loading {- display: flex;- justify-content: center;- padding: var(--space-6);- }-- &__themes {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));- gap: var(--space-8);- }-- &__card {- position: relative;- display: flex;- flex-direction: column;- cursor: pointer;-- .theme-card-preview__image-wrapper {- border: 2px solid var(--content-border-color);- height: 250px;- border-radius: var(--d-border-radius);-- @include viewport.from(md) {- height: 24vw; // adjusts with window width (like the modal itself)- }- }-- &:hover,- &.--selected {- .theme-card-preview__image-wrapper {- border-color: var(--tertiary);- }- }- }-- .theme-card-preview__image {- image-rendering: -webkit-optimize-contrast;- image-rendering: crisp-edges;- }-- &__footer {- display: flex;- justify-content: center;- margin-top: var(--space-8);- }-- &__enabled-badge {- position: absolute;- top: 0;- right: -2px;- display: inline-flex;- align-items: center;- gap: var(--space-1);- font-size: var(--font-down-2);- font-weight: 700;- color: var(--secondary);- background: var(--tertiary);- padding: var(--space-1) var(--space-2);- border-radius: var(--d-border-radius);- border-top-left-radius: 0;- border-bottom-right-radius: 0;- z-index: 1;- }-- &__browse-all,- &__upgrade-text {- margin-top: var(--space-4);- font-size: var(--font-down-1);- color: var(--primary-medium);- text-align: center;- }-- &__browse-all a,- &__upgrade-link {- color: var(--tertiary);-- &:hover {- color: var(--tertiary-hover);- }- }-}diff --git a/app/assets/stylesheets/common/components/design-wizard.scss b/app/assets/stylesheets/common/components/design-wizard.scssnew file mode 100644index 00000000000..6fc38af15e1--- /dev/null+++ b/app/assets/stylesheets/common/components/design-wizard.scss@@ -0,0 +1,779 @@+@use "lib/viewport";+@import "common/foundation/mixins";++// Common stylesheets compile with the active scheme injected into+// $primary/$secondary/$tertiary, so referencing those (or their derived shades)+// would let the previewed palette restyle the tool. Pin base-light instead.+$dw-primary: #222;+$dw-secondary: #fff;+$dw-tertiary: #08c;+$dw-tertiary-hover: #069;+$dw-tertiary-high: #0aadff;+$dw-selected: #d1f0ff;+$dw-hover: #f2f2f2;+$dw-primary-very-low: #f8f8f8;+$dw-primary-low: #e9e9e9;+$dw-primary-low-mid: #bdbdbd;+$dw-primary-medium: #919191;+$dw-primary-high: #646464;+$dw-primary-very-high: #434343;+$dw-button-default-border: #d3d3d3;++.design-wizard,+.design-wizard__font-select-content {+ --primary: #{$dw-primary};+ --secondary: #{$dw-secondary};+ --d-content-background: #{$dw-secondary};+ --tertiary: #{$dw-tertiary};+ --tertiary-hover: #{$dw-tertiary-hover};+ --tertiary-low: #{$dw-selected};+ --primary-very-low: #{$dw-primary-very-low};+ --primary-low: #{$dw-primary-low};+ --primary-low-mid: #{$dw-primary-low-mid};+ --primary-medium: #{$dw-primary-medium};+ --primary-high: #{$dw-primary-high};+ --primary-very-high: #{$dw-primary-very-high};+ --d-hover: #{$dw-hover};+ --d-link-color: #{$dw-tertiary};+ --primary-100: #{$dw-hover};+ --primary-200: #{$dw-primary-low};+ --tertiary-300: #{$dw-selected};+ --tertiary-high: #{$dw-tertiary-high};++ // Theme-defined button accents, including Horizon's button overrides.+ --accent-color: #{$dw-tertiary};+ --accent-text-color: #{$dw-secondary};+ --button-box-shadow: #{$dw-selected};+ --content-border-color: #{$dw-primary-low};++ // Default buttons keep the modernized Foundation treatment.+ --d-button-default-text-color: #{$dw-primary-very-high};+ --d-button-default-text-color--hover: #{$dw-primary};+ --d-button-default-bg-color: #{$dw-secondary};+ --d-button-default-bg-color--hover: #{$dw-primary-low};+ --d-button-default-icon-color: #{$dw-primary-very-high};+ --d-button-default-icon-color--hover: #{$dw-primary};+ --d-button-default-border: 1px solid #{$dw-button-default-border};+ --d-button-default-border--hover: 1px solid #{$dw-primary-low-mid};+ --d-button-primary-text-color: #{$dw-secondary};+ --d-button-primary-text-color--hover: #{$dw-secondary};+ --d-button-primary-bg-color: #{$dw-tertiary};+ --d-button-primary-bg-color--hover: #{$dw-tertiary-hover};+ --d-button-primary-icon-color: #{$dw-secondary};+ --d-button-primary-icon-color--hover: #{$dw-secondary};+ --d-button-flat-text-color: #{$dw-tertiary};+ --d-button-flat-text-color--hover: #{$dw-primary};+ --d-button-flat-icon-color: #{$dw-primary-low-mid};+ --d-button-flat-icon-color--hover: #{$dw-primary};+ --d-button-flat-bg-color: transparent;+ --d-button-flat-bg-color--hover: #{$dw-hover};+ --d-button-flat-bg-color--focus: #{$dw-hover};+ --d-button-flat-text-color--disabled: #{$dw-primary};+ --d-button-flat-close-text-color: #{$dw-primary-high};+ --d-button-flat-close-bg-color: transparent;+ --d-button-flat-close-icon-color: #{$dw-primary-high};+ --d-button-flat-close-icon-color--hover: #{$dw-primary};+ --d-button-transparent-text-color: #{$dw-primary};+ --d-button-transparent-text-color--hover: #{$dw-tertiary-hover};+ --d-button-transparent-icon-color: #{$dw-primary-high};+ --d-button-transparent-icon-color--hover: #{$dw-tertiary-hover};+ color: var(--primary);+ color-scheme: light;+ font-family:+ system-ui,+ -apple-system,+ "Segoe UI",+ Roboto,+ Helvetica,+ Arial,+ sans-serif;++ // pinned so the previewed theme's root font size cannot resize the tool+ font-size: 16px;++ h1,+ h2,+ h3,+ h4,+ h5,+ h6 {+ font-family: inherit;+ }+}++.design-wizard {+ // also read by the panel component, for its closing animation+ --design-wizard-slide-out: translateX(100%);+ --design-wizard-category-1: #25aae2;+ --design-wizard-category-2: #9eb83b;+ --design-wizard-category-3: #e45735;+ --design-wizard-category-4: #7159c1;+ position: fixed;+ z-index: z("design-wizard");+ inset-block: calc(var(--header-offset) - var(--space-2)) 0;+ inset-inline-end: 0;+ display: flex;+ flex-direction: column;+ box-sizing: border-box;+ width: min(24em, 100vw);+ background: var(--secondary);+ border: 1px solid var(--content-border-color);+ border-inline-end: none;+ border-start-start-radius: var(--d-border-radius-large);+ box-shadow: var(--shadow-card);++ @include d-animation(design-wizard-slide-in, 0.25s, ease-out);++ html[dir="rtl"] & {+ --design-wizard-slide-out: translateX(-100%);+ }++ // a full-height rail would cover the page it previews+ @include viewport.until(sm) {+ --design-wizard-slide-out: translateY(100%);+ inset-block: auto 0;+ inset-inline: 0;+ width: 100%;+ max-height: 65vh;+ border-inline-end: 1px solid var(--content-border-color);+ border-start-end-radius: var(--d-border-radius-large);++ html[dir="rtl"] & {+ --design-wizard-slide-out: translateY(100%);+ }+ }++ &.--no-entrance {+ animation: none;+ }++ &__close {+ position: absolute;+ inset-block-start: var(--space-2);+ inset-inline-end: var(--space-2);+ }++ &__content {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ height: 100%;++ // so the sections scroll rather than pushing the footer actions out+ min-height: 0;+ padding: var(--space-4);+ }++ &__subtitle {+ font-size: var(--font-down-1);+ color: var(--primary-medium);+ }++ &__sections {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-4);+ min-height: 0;+ overflow-y: auto;+ overscroll-behavior: contain;+ }++ &__section {+ width: calc(100% - 2px);+ }++ &__section-title {+ font-weight: 600;+ color: var(--primary);+ }++ &__section-body {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ &__custom-theme-notice {+ margin: 0;+ padding: var(--space-1) var(--space-2);+ font-size: var(--font-down-2);+ color: var(--primary-medium);+ background: var(--primary-100);+ border-radius: var(--d-border-radius);+ }++ &__theme-cards {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ min-width: 0;+ padding: 0;+ margin: 0;+ border: 0;+ }++ &__theme-card-wrapper {+ position: relative;+ }++ &__theme-card {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ width: 100%;+ font-size: var(--font-down-1);+ color: inherit;+ cursor: pointer;++ &.--selected .design-wizard__theme-screenshot {+ border-color: var(--tertiary);+ box-shadow: 0 0 0 1px var(--tertiary);+ }++ &:focus-within .design-wizard__theme-screenshot,+ html.discourse-no-touch &:hover .design-wizard__theme-screenshot {+ border-color: var(--tertiary);+ box-shadow: 0 0 0 1px var(--tertiary);+ }+ }++ &__theme-screenshot {+ position: relative;+ display: flex;+ align-items: center;+ overflow: hidden;+ border: 1px solid var(--content-border-color);+ border-radius: var(--d-border-radius);+ }++ &__theme-screenshot-image {+ display: block;+ width: 100%;+ height: 100%;+ object-fit: cover;++ /*! rtl:ignore */+ object-position: top left;+ image-rendering: -webkit-optimize-contrast;+ image-rendering: crisp-edges;+ }++ &__theme-name {+ font-weight: 600;+ }++ &__theme-description {+ display: block;+ margin: 0;+ font-weight: normal;+ }++ &__theme-enabled-badge {+ position: absolute;+ z-index: z("base");+ inset-block-start: var(--space-2);+ inset-inline-end: var(--space-2);+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ padding: var(--space-1) var(--space-2);+ font-size: var(--font-down-1);+ font-weight: 700;+ color: var(--secondary);+ background: var(--tertiary);+ border-radius: var(--d-border-radius);++ .d-icon {+ color: currentcolor;+ }+ }++ &__color {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ &__color-modes {+ display: flex;+ justify-content: flex-end;+ }++ &__color-mode {+ padding: var(--space-1) var(--space-2);+ font-size: var(--font-down-2);+ font-weight: 600;+ background: none;+ border: 1px solid var(--content-border-color);+ cursor: pointer;++ &:first-child {+ border-start-start-radius: var(--d-border-radius);+ border-end-start-radius: var(--d-border-radius);+ }++ &:last-child {+ border-start-end-radius: var(--d-border-radius);+ border-end-end-radius: var(--d-border-radius);+ border-inline-start: none;+ }++ &.--active {+ color: var(--tertiary);+ background: var(--tertiary-low);+ }++ &:disabled {+ cursor: default;+ opacity: 0.4;+ }+ }++ &__swatches {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: var(--space-2);+ }++ &__homepage-card,+ &__style-block,+ &__swatch {+ background: none;+ border: 1px solid var(--content-border-color);+ border-radius: var(--d-border-radius);+ cursor: pointer;++ &.--selected {+ font-weight: 600;+ color: var(--tertiary);+ border-color: var(--tertiary);+ box-shadow: 0 0 0 1px var(--tertiary);+ }++ html.discourse-no-touch &:hover {+ border-color: var(--tertiary);+ box-shadow: 0 0 0 1px var(--tertiary);+ }+ }++ &__swatch {+ padding: var(--space-1);+ text-align: center;+ }++ &__swatch-preview {+ display: block;+ height: 1.25em;+ border-radius: var(--token-radius-small);+ }++ &__swatch-name {+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ margin-block-start: var(--space-1);+ font-size: var(--font-down-2);++ .d-icon {+ font-size: var(--font-down-3);+ color: var(--primary-medium);+ }+ }++ &__color-note {+ margin: 0;+ font-size: var(--font-down-2);+ color: var(--primary-medium);+ }++ &__user-selectable {+ display: flex;+ gap: var(--space-2);+ padding: var(--space-2);+ border: 1px solid var(--content-border-color);+ border-radius: var(--d-border-radius);+ }++ &__user-selectable-title {+ display: block;+ font-size: var(--font-down-1);+ font-weight: 600;+ }++ &__user-selectable-description {+ display: block;+ font-size: var(--font-down-2);+ color: var(--primary-medium);+ }++ &__font-group {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ &__label {+ display: block;+ font-size: var(--font-down-1-rem);+ font-weight: 600;+ color: var(--primary);+ }++ &__font-select.btn-default.btn {+ justify-content: space-between;+ width: 100%;+ border-radius: var(--d-border-radius);+ background: var(--content-background);++ &:hover {+ background: var(--content-background);+ }+ }++ &__font-select-caret.d-icon.d-icon-angle-down.svg-icon {+ margin-inline-start: var(--space-1);+ color: var(--primary-medium);+ }++ &__homepage-cards {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: var(--space-2);+ }++ &__homepage-card {+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: var(--space-1);+ padding: var(--space-2);+ font-size: var(--font-down-1);+ }++ &__homepage-thumbnail {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ height: 4.5em;+ padding: var(--space-1);+ overflow: hidden;+ background: var(--secondary);+ border: 1px solid var(--content-border-color);+ border-radius: var(--token-radius-small);++ &.--topics.--horizon {+ background: var(--primary-very-low);+ }++ &.--categories {+ display: grid;+ grid-template-columns: 1fr 1fr;+ grid-auto-rows: 1fr;+ }+ }++ &__homepage-detail {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ &__style-blocks,+ &__topic-page-options {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ &__style-block {+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: var(--space-1);+ padding: var(--space-2);+ font-size: var(--font-down-1);+ }++ &__homepage-style-preview {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ height: 4.5em;+ padding: var(--space-2);+ overflow: hidden;+ background: var(--secondary);+ border: 1px solid var(--content-border-color);+ border-radius: var(--token-radius-small);++ &.--boxes {+ display: grid;+ grid-template-columns: 1fr 1fr;+ grid-auto-rows: 1fr;+ }+ }++ &__mock-card {+ position: relative;+ display: block;+ flex: 1;+ padding-block: var(--space-1);+ padding-inline: var(--space-5) var(--space-1);+ background: var(--secondary);+ border: 1px solid var(--content-border-color);+ border-radius: var(--d-border-radius);++ .design-wizard__mock-avatar {+ position: absolute;+ inset-block-start: var(--space-1);+ inset-inline-start: var(--space-1);+ }++ .design-wizard__mock-badge {+ display: block;+ width: 1.125em;+ height: 0.25em;+ margin-block-start: var(--space-1);+ background: var(--tertiary-low);+ border-radius: var(--token-radius-small);+ }+ }++ &__mock-row {+ display: flex;+ flex: 1;+ align-items: center;+ gap: var(--space-1);++ + .design-wizard__mock-row {+ border-block-start: 1px solid var(--primary-very-low);+ }++ .design-wizard__mock-line.--title {+ margin-inline-end: auto;+ }+ }++ &__mock-avatar {+ display: block;+ flex: none;+ width: 0.5em;+ height: 0.5em;+ background: var(--primary-low-mid);+ border-radius: 50%;+ }++ &__mock-line {+ display: block;+ height: 0.25em;+ border-radius: var(--token-radius-small);++ &.--title {+ width: 55%;+ margin-block-end: var(--space-1);+ background: var(--primary-low-mid);+ }++ &.--text {+ width: 80%;+ margin-block-end: var(--space-1);+ background: var(--primary-low);+ }++ &.--count {+ flex: none;+ width: 0.625em;+ background: var(--primary-low);+ }+ }++ &__mock-cat-badge {+ display: block;+ flex: none;+ width: 0.5em;+ height: 0.5em;+ border-radius: var(--token-radius-small);++ &.--c1 {+ background: var(--design-wizard-category-1);+ }++ &.--c2 {+ background: var(--design-wizard-category-2);+ }++ &.--c3 {+ background: var(--design-wizard-category-3);+ }++ &.--c4 {+ background: var(--design-wizard-category-4);+ }+ }++ &__mock-columns {+ display: flex;+ flex: 1;+ gap: var(--space-2);+ min-height: 0;+ }++ &__mock-column {+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: var(--space-1);++ + .design-wizard__mock-column {+ padding-inline-start: var(--space-2);+ border-inline-start: 1px solid var(--primary-very-low);+ }+ }++ &__mock-box {+ display: flex;+ flex-direction: column;+ justify-content: center;+ padding: var(--space-1);+ margin: 1px;+ background: var(--secondary);+ border: 1px solid var(--content-border-color);+ border-inline-start-width: 3px;+ border-radius: var(--token-radius-small);++ .design-wizard__mock-line.--title {+ width: 65%;+ }++ .design-wizard__mock-line.--text {+ width: 90%;+ margin-block-end: 2px;+ }++ &.--c1 {+ border-inline-start-color: var(--design-wizard-category-1);+ }++ &.--c2 {+ border-inline-start-color: var(--design-wizard-category-2);+ }++ &.--c3 {+ border-inline-start-color: var(--design-wizard-category-3);+ }++ &.--c4 {+ border-inline-start-color: var(--design-wizard-category-4);+ }+ }++ // Rendered inline like the notification tracking menu's selectable rows.+ &__topic-page-option {+ display: flex;+ box-sizing: border-box;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2);+ background: none;+ border: 1px solid var(--content-border-color);+ border-radius: var(--d-border-radius);+ cursor: pointer;++ &.--selected {+ border-color: var(--tertiary);+ box-shadow: 0 0 0 1px var(--tertiary);+ }++ html.discourse-no-touch &:hover {+ border-color: var(--tertiary);+ box-shadow: 0 0 0 1px var(--tertiary);+ }+ }++ &__topic-page-option-texts {+ display: flex;+ flex: 1 1 0%;+ flex-direction: column;+ flex-wrap: wrap;+ align-items: flex-start;+ line-height: var(--line-height-medium);+ }++ &__topic-page-option-label {+ flex: 1 1 auto;+ max-width: 100%;+ font-size: var(--font-0);+ font-weight: bold;+ color: var(--primary);++ @include ellipsis;+ }++ &__topic-page-option-description {+ flex: 1 1 auto;+ font-size: var(--font-down-1);+ color: var(--primary-medium);+ text-align: start;+ white-space: normal;+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ margin-block-start: auto;+ }++ &__step-dots {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ margin-inline-end: auto;+ }++ &__step-dot {+ box-sizing: border-box;+ width: 0.5em;+ height: 0.5em;+ padding: 0;+ background: var(--primary-low-mid);+ border: none;+ border-radius: 50%;+ cursor: pointer;++ &.--active {+ background: var(--tertiary);+ }++ html.discourse-no-touch &:hover {+ background: var(--primary-medium);+ }++ html.discourse-no-touch &.--active:hover {+ background: var(--tertiary-hover);+ }+ }+}++.design-wizard__font-select-content {+ z-index: z("modal", "popover");+}++.design-wizard__font-list {+ max-height: 40vh;+ overflow-y: auto;+ overscroll-behavior: contain;+ scrollbar-width: thin;+ scrollbar-color: var(--primary-low-mid) transparent;+}++@keyframes design-wizard-slide-in {+ from {+ transform: var(--design-wizard-slide-out);+ }++ to {+ transform: translate(0, 0);+ }+}diff --git a/app/assets/stylesheets/common/foundation/variables.scss b/app/assets/stylesheets/common/foundation/variables.scssindex fc210c9414c..f65ed48c274 100644--- a/app/assets/stylesheets/common/foundation/variables.scss+++ b/app/assets/stylesheets/common/foundation/variables.scss@@ -98,6 +98,8 @@ $z-layers: ("content": 1300,"overlay": 1200,),+ // below modals, so dialogs opened from the page behind it stay reachable+ "design-wizard": 1160,"fullscreen": 1150,"mobile-header": 1150,"mobile-composer": 1100,diff --git a/app/controllers/admin/config/design_wizard_controller.rb b/app/controllers/admin/config/design_wizard_controller.rbnew file mode 100644index 00000000000..c93cb32728d--- /dev/null+++ b/app/controllers/admin/config/design_wizard_controller.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++class Admin::Config::DesignWizardController < Admin::AdminController+ def index+ core_themes =+ Theme+ .where(id: Theme::CORE_THEMES.values)+ .includes(:locale_fields, theme_fields: :upload)+ .order(:id)++ render_serialized(Theme.find_default, DesignWizardSerializer, root: false, themes: core_themes)+ end++ def update+ DesignWizard::Apply.call(service_params) do |result|+ on_success { render json: success_json }+ on_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request+ end+ on_model_not_found(:theme) { raise Discourse::NotFound }+ # unreachable via AdminController, but don't let it 422 if that changes+ on_failed_policy(:current_user_is_admin) { raise Discourse::InvalidAccess }+ on_failed_policy(:palettes_available_to_theme) do+ render json:+ failed_json.merge(errors: [I18n.t("design_wizard.errors.palette_unavailable")]),+ status: :unprocessable_entity+ end+ on_failed_step(:update_site_settings) do+ render json:+ failed_json.merge(+ errors: [I18n.t("design_wizard.errors.site_settings_update_failed")],+ ),+ status: :unprocessable_entity+ end+ on_failure { render json: failed_json, status: :unprocessable_entity }+ end+ end+enddiff --git a/app/controllers/stylesheets_controller.rb b/app/controllers/stylesheets_controller.rbindex c79b41f23a7..ed9005dc1c6 100644--- a/app/controllers/stylesheets_controller.rb+++ b/app/controllers/stylesheets_controller.rb@@ -25,7 +25,7 @@ class StylesheetsController < ApplicationControllerparams.permit("theme_id")theme_id = params[:theme_id]&.to_i- theme_id = nil if theme_id && !guardian.allow_themes?([theme_id])+ theme_id = nil if theme_id && !guardian.allow_themes?([theme_id], include_preview: true)manager = Stylesheet::Manager.new(theme_id: theme_id)stylesheet = manager.color_scheme_stylesheet_details(params[:id], fallback_to_base: true)diff --git a/app/models/theme.rb b/app/models/theme.rbindex 2584624925f..7f1070e6235 100644--- a/app/models/theme.rb+++ b/app/models/theme.rb@@ -752,6 +752,13 @@ class Theme < ActiveRecord::Basetranslations(internal: true, preloaded_locale_fields: preloaded_locale_fields)end+ # preload and pass `:locale_fields` when iterating themes, to avoid N+1+ def description(preloaded_locale_fields: locale_fields)+ internal_translations(preloaded_locale_fields: preloaded_locale_fields)+ .find { |translation| translation.key == "theme_metadata.description" }+ &.value+ end+def translations(internal: false, preloaded_locale_fields: nil)fallbacks = I18n.fallbacks[I18n.locale]begindiff --git a/app/serializers/basic_theme_serializer.rb b/app/serializers/basic_theme_serializer.rbindex 7c909f05e7b..c065fc2affd 100644--- a/app/serializers/basic_theme_serializer.rb+++ b/app/serializers/basic_theme_serializer.rb@@ -10,11 +10,4 @@ class BasicThemeSerializer < ApplicationSerializerdef defaulttrueend-- def description- object- .internal_translations(preloaded_locale_fields: object.locale_fields)- .find { |t| t.key == "theme_metadata.description" }- &.value- endenddiff --git a/app/serializers/design_wizard_serializer.rb b/app/serializers/design_wizard_serializer.rbnew file mode 100644index 00000000000..ab6dafc08d8--- /dev/null+++ b/app/serializers/design_wizard_serializer.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++class DesignWizardSerializer < ApplicationSerializer+ attributes :current_theme, :base_font, :heading_font, :homepage, :palettes_user_selectable++ has_many :themes, serializer: DesignWizardThemeSerializer, embed: :objects++ def themes+ @options[:themes]+ end++ def current_theme+ return if object.nil? || Theme::CORE_THEMES.value?(object.id)++ { id: object.id, name: object.name }+ end++ def base_font+ SiteSetting.base_font+ end++ def heading_font+ SiteSetting.heading_font+ end++ def homepage+ SiteSetting.homepage+ end++ def palettes_user_selectable+ offered = ColorScheme.where(theme_id: preselected_theme&.id)+ offered = ColorScheme.where(via_wizard: true) if offered.none?+ offered.exists? && offered.where(user_selectable: false).none?+ end++ private++ # The wizard offers Horizon when the current default is not a core theme.+ def preselected_theme+ return object if Theme::CORE_THEMES.value?(object&.id)++ Theme.horizon_theme+ end+enddiff --git a/app/serializers/design_wizard_theme_serializer.rb b/app/serializers/design_wizard_theme_serializer.rbnew file mode 100644index 00000000000..19b9784b105--- /dev/null+++ b/app/serializers/design_wizard_theme_serializer.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++class DesignWizardThemeSerializer < ApplicationSerializer+ attributes :id,+ :name,+ :description,+ :default,+ :color_scheme_id,+ :dark_color_scheme_id,+ :screenshot_light_url,+ :screenshot_dark_url,+ :palette_pairs++ def description+ object.description(preloaded_locale_fields: object.locale_fields)+ end++ def default+ object.default?+ end++ def palette_pairs+ DesignWizard::PalettePairs.for_theme(object)+ end+enddiff --git a/app/services/design_wizard/action/resolve_palette.rb b/app/services/design_wizard/action/resolve_palette.rbnew file mode 100644index 00000000000..08feb1630ad--- /dev/null+++ b/app/services/design_wizard/action/resolve_palette.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++class DesignWizard::Action::ResolvePalette < Service::ActionBase+ option :palette_id++ def call+ return if palette_id.blank?+ return ColorScheme.find_by(id: palette_id) if palette_id.positive?++ find_materialized_built_in || materialize_built_in+ end++ private++ def find_materialized_built_in+ ColorScheme.find_by(base_scheme_id: palette_id, via_wizard: true)+ end++ def materialize_built_in+ ColorScheme.create_from_base(name: built_in_name, base_scheme_id: palette_id, via_wizard: true)+ end++ def built_in_name+ scheme_name = ColorScheme::NAMES_TO_ID_MAP.invert[palette_id]+ I18n.t("color_schemes.#{scheme_name.downcase.tr(" ", "_")}_theme_name")+ end+enddiff --git a/app/services/design_wizard/action/update_palette_selectability.rb b/app/services/design_wizard/action/update_palette_selectability.rbnew file mode 100644index 00000000000..0db4097ab3f--- /dev/null+++ b/app/services/design_wizard/action/update_palette_selectability.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++# Every save re-states the whole offering, so palettes an admin made selectable+# outside the wizard are reset too.+#+# update_all skips callbacks deliberately: user_selectable does not affect+# compiled CSS, and the caller expires the one cache that matters. ColorScheme's+# default scope excludes remote copies, which is what keeps this from bypassing+# no_edits_for_remote_copies.+class DesignWizard::Action::UpdatePaletteSelectability < Service::ActionBase+ option :theme+ option :selectable++ def call+ revoke_palettes_no_longer_offered+ offered.update_all(user_selectable: selectable)+ end++ private++ def offered+ @offered ||=+ begin+ theme_palettes = ColorScheme.where(theme_id: theme.id)+ theme_palettes.none? ? ColorScheme.where(via_wizard: true) : theme_palettes+ end+ end++ def revoke_palettes_no_longer_offered+ ColorScheme+ .where(theme_id: Theme::CORE_THEMES.values)+ .or(ColorScheme.where(via_wizard: true))+ .where.not(id: offered.select(:id))+ .update_all(user_selectable: false)+ end+enddiff --git a/app/services/design_wizard/apply.rb b/app/services/design_wizard/apply.rbnew file mode 100644index 00000000000..311a1d43e3f--- /dev/null+++ b/app/services/design_wizard/apply.rb@@ -0,0 +1,147 @@+# frozen_string_literal: true++# Applies the design choices made in the admin design wizard in one atomic+# operation: default theme, the theme's light/dark palettes, fonts, homepage+# and whether members can switch between the offered palettes.+class DesignWizard::Apply+ include Service::Base++ BASE_LIGHT_PALETTE_ID = ColorScheme::NAMES_TO_ID_MAP[ColorScheme::LIGHT_PALETTE_NAME]++ params do+ attribute :theme_id, :integer+ attribute :light_palette_id, :integer+ attribute :dark_palette_id, :integer+ attribute :palettes_user_selectable, :boolean, default: false+ attribute :base_font, :string+ attribute :heading_font, :string+ attribute :homepage, :string+ attribute :category_page_style, :string++ before_validation do+ # the built-in light palette is represented by a theme without an+ # assigned light palette+ self.light_palette_id = nil if light_palette_id == BASE_LIGHT_PALETTE_ID+ end++ validates :theme_id, presence: true, inclusion: { in: Theme::CORE_THEMES.values }+ validates :base_font,+ :heading_font,+ inclusion: {+ in: BaseFontSetting.values.map { |font| font[:value] },+ },+ allow_blank: true+ validates :homepage, inclusion: { in: %w[latest new hot categories] }, allow_blank: true+ validates :category_page_style,+ inclusion: {+ in: CategoryPageStyle.values.map { |style| style[:value] },+ },+ allow_blank: true+ validate :built_in_palettes_exist++ def site_settings(theme_id:)+ {+ default_theme_id: theme_id,+ base_font: base_font.presence,+ heading_font: heading_font.presence,+ default_homepage: homepage.presence,+ desktop_category_page_style: category_page_style.presence,+ }.compact.map { |setting_name, value| { setting_name:, value: } }+ end++ private++ def built_in_palettes_exist+ %i[light_palette_id dark_palette_id].each do |attribute|+ palette_id = public_send(attribute)+ next if palette_id.nil? || palette_id.positive?+ errors.add(attribute, :inclusion) if !ColorScheme::NAMES_TO_ID_MAP.value?(palette_id)+ end+ end+ end++ policy :current_user_is_admin+ model :theme+ policy :palettes_available_to_theme++ transaction do+ model :light_palette, :resolve_light_palette, optional: true+ model :dark_palette, :resolve_dark_palette, optional: true+ step :assign_theme_palettes+ only_if :enabling_built_in_palettes do+ step :offer_built_in_palettes+ end+ step :update_palette_selectability+ end++ step :update_site_settings+ step :expire_user_color_schemes_cache++ private++ def current_user_is_admin(guardian:)+ guardian.is_admin?+ end++ def fetch_theme(params:)+ Theme.find_by(id: params.theme_id)+ end++ def palettes_available_to_theme(params:, theme:)+ [params.light_palette_id, params.dark_palette_id].all? do |palette_id|+ palette_id.nil? || palette_id.negative? ||+ ColorScheme.where(id: palette_id, theme_id: [nil, theme.id]).exists?+ end+ end++ def resolve_light_palette(params:)+ DesignWizard::Action::ResolvePalette.call(palette_id: params.light_palette_id)+ end++ def resolve_dark_palette(params:)+ DesignWizard::Action::ResolvePalette.call(palette_id: params.dark_palette_id)+ end++ def assign_theme_palettes(theme:, light_palette:, dark_palette:)+ theme.update!(color_scheme_id: light_palette&.id, dark_color_scheme_id: dark_palette&.id)+ end++ def enabling_built_in_palettes(params:, theme:)+ params.palettes_user_selectable && ColorScheme.where(theme_id: theme.id).none?+ end++ def offer_built_in_palettes+ DesignWizard::PalettePairs::BUILT_IN_PAIRS.each do |pair|+ pair+ .values_at(:light, :dark)+ .compact+ .each do |name|+ DesignWizard::Action::ResolvePalette.call(palette_id: ColorScheme::NAMES_TO_ID_MAP[name])+ end+ end+ end++ def update_palette_selectability(params:, theme:)+ DesignWizard::Action::UpdatePaletteSelectability.call(+ theme:,+ selectable: params.palettes_user_selectable,+ )+ end++ # default_theme_id is hidden, so it has to be explicitly allowed.+ def update_site_settings(params:, theme:, guardian:)+ SiteSetting::Update.call(+ params: {+ settings: params.site_settings(theme_id: theme.id),+ },+ options: {+ allow_changing_hidden: %i[default_theme_id],+ },+ guardian:,+ ) { on_failure { fail!("failed to update site settings") } }+ end++ def expire_user_color_schemes_cache+ ApplicationSerializer.expire_cache_fragment!("user_color_schemes")+ end+enddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex eef96232573..23323bd8004 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -560,27 +560,29 @@ en:pm_title: "Suggested Messages"admin_onboarding_banner:- launch_in_easy_steps: "Launch in %{step_count} easy steps"+ launch_in_easy_steps: "Set up your community"+ launch_in_easy_steps_subtitle: "%{completed_steps} of %{step_count} steps completed"congrats_onboarding_complete: "Congratulations on completing the onboarding process!"+ expand: "Expand setup steps"+ collapse: "Collapse setup steps"+ dismiss: "Dismiss setup"select_theme:title: "Customize your site"- description: "Choose a starting theme for your community"- action: "Select theme"- modal_title: "Choose a theme"- use_theme: "Use selected theme"- enabled: "Selected"- applying_theme: "Applying theme..."- browse_all: "Manage themes"+ description: "Choose colors, fonts, and a homepage."+ action: "See options"+ completed: "Change options"show_light_screenshot: "Show light screenshot"show_dark_screenshot: "Show dark screenshot"invite_collaborators:- title: "Invite Collaborators"- description: "Early members help bring your community to life"+ title: "Invite collaborators"+ description: "Early members bring it to life."action: "Create invite"+ completed: "Invite more"start_posting:- title: "Start Posting"- description: "Give people something to talk about together"+ title: "Start posting"+ description: "Give people something to discuss."action: "See ideas"+ completed: "See more ideas"choose_option: "How would you like to start?"predefined_topics: "Icebreaker templates"predefined_topics_subtitle: "Give new members something to talk about, pick a template to edit and make your own."@@ -601,6 +603,45 @@ en:title: "What is your favorite food?"body: "Share your favorite food with the community! I'll start: I love pizza, especially with extra cheese and pepperoni."+ design_wizard:+ title: "Customize your site"+ subtitle: "Choose colors, fonts, and a homepage."+ step_label: "Go to step %{index}"+ save: "Save and finish"+ back: "Back"+ next: "Next"+ sections:+ theme: "Theme"+ colors: "Default color"+ fonts: "Fonts"+ homepage: "Homepage"+ theme:+ selected: "Selected"+ custom_theme_notice: "Your site currently uses %{name} as its default theme. Choose a theme below to preview it. Saving will replace your current theme."+ colors:+ light: "Light"+ dark: "Dark"+ dark_only: "%{name} only has a dark mode"+ both_modes: "Each palette includes a matching light and dark mode"+ user_selectable: "Let members switch palettes"+ user_selectable_description: "Show these palettes in a menu members can pick from"+ fonts:+ base_font: "Base font"+ heading_font: "Heading font"+ homepage:+ topics: "Topics"+ categories: "Categories"+ topic_page_type: "Topic page type"+ topic_pages:+ latest: "Topics sorted by their most recent activity, newest first."+ new: "Topics created in the last few days, newest first."+ hot: "Topics trending right now, blending overall popularity with recent engagement."+ category_page_style: "Category page style"+ styles:+ boxes: "Boxes"+ with_topics: "Categories with topics"+ only: "Categories only"+about:edit: "Edit this page"simple_title: "About"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 6c93957b2e5..d50c7111fb1 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -5985,6 +5985,15 @@ en:title: "Developer Mode"enable_rack_mini_profiler: "Enable Rack Mini Profiler to persist across session changes for 1 hour"enter: "Enter Developer Mode"+ design_wizard:+ errors:+ palette_unavailable: "One of the selected color palettes is not available for the selected theme."+ site_settings_update_failed: "The site settings could not be updated."+ palette_pairs:+ default: "Default"+ wcag: "WCAG"+ solarized: "Solarized"+ dracula: "Dracula"wizard:title: "Discourse Setup"step:diff --git a/config/routes.rb b/config/routes.rbindex 62d94225b91..3d46f1a3aad 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -462,6 +462,8 @@ Discourse::Application.routes.draw doget "/welcome-banner" => "welcome_banner#index"put "/logo" => "logo#update"put "/fonts" => "fonts#update"+ get "/design-wizard" => "design_wizard#index"+ put "/design-wizard" => "design_wizard#update"get "colors/:id" => "color_palettes#show"get "colors" => "color_palettes#index"get "upcoming-changes" => "upcoming_changes#index"diff --git a/frontend/discourse/admin/lib/color-scheme-manager.js b/frontend/discourse/admin/lib/color-scheme-manager.jsindex 194ac7b6c1f..fff6caa8636 100644--- a/frontend/discourse/admin/lib/color-scheme-manager.js+++ b/frontend/discourse/admin/lib/color-scheme-manager.js@@ -1,6 +1,105 @@import ColorScheme from "discourse/admin/models/color-scheme";import { ajax } from "discourse/lib/ajax";+const MODES = ["light", "dark"];++function schemeLink(mode) {+ return document.querySelector(`link.${mode}-scheme`);+}++/**+ * @typedef {Object} ColorSchemeLinkState+ * @property {?{href: ?string, media: ?string}} light+ * @property {?{href: ?string, media: ?string}} dark+ */++/**+ * Snapshots the light/dark stylesheet links so a preview can be undone.+ *+ * @returns {ColorSchemeLinkState}+ */+export function captureColorSchemeLinks() {+ return Object.fromEntries(+ MODES.map((mode) => {+ const link = schemeLink(mode);++ return [+ mode,+ link+ ? {+ href: link.getAttribute("href"),+ media: link.getAttribute("media"),+ }+ : null,+ ];+ })+ );+}++/**+ * Restores links snapshotted by {@link captureColorSchemeLinks}.+ *+ * @param {?ColorSchemeLinkState} original+ */+export function restoreColorSchemeLinks(original) {+ if (!original) {+ return;+ }++ for (const mode of MODES) {+ const link = schemeLink(mode);+ const originalLink = original[mode];++ if (!link || !originalLink) {+ continue;+ }++ for (const attribute of ["href", "media"]) {+ if (originalLink[attribute] === null) {+ link.removeAttribute(attribute);+ } else {+ link.setAttribute(attribute, originalLink[attribute]);+ }+ }++ link.removeAttribute("data-scheme-id");+ }+}++/**+ * Which color mode the page is currently rendering.+ *+ * @returns {"light" | "dark"}+ */+export function renderedColorMode() {+ const isActive = (link) =>+ link &&+ link.media !== "none" &&+ window.matchMedia(link.media || "all").matches;++ const lightIsActive = isActive(schemeLink("light"));+ const darkIsActive = isActive(schemeLink("dark"));++ return darkIsActive && !lightIsActive ? "dark" : "light";+}++/**+ * Forces the page to render one color mode.+ *+ * @param {"light" | "dark"} mode+ */+export function showColorMode(mode) {+ const lightTag = schemeLink("light");+ const darkTag = schemeLink("dark");++ if (lightTag && darkTag) {+ lightTag.media = mode === "light" ? "all" : "none";+ darkTag.media = mode === "dark" ? "all" : "none";+ } else {+ (lightTag ?? darkTag)?.setAttribute("media", "all");+ }+}+/*** Apply color scheme by updating stylesheet links*@@ -8,11 +107,19 @@ import { ajax } from "discourse/lib/ajax";* @param {Object} options* @param {boolean} options.replace - replace existing tags? (default: false)* @param {boolean} options.save - save changes to the server? (default: false)+ * @param {number} options.themeId - compile against this theme's color+ * definitions instead of the default theme's (default: none)+ * @param {"light" | "dark"} options.mode - stylesheet to replace* @returns {Promise}*/export async function applyColorScheme(scheme, options = {}) {- const { replace = false, save = false } = options;+ const {+ replace = false,+ save = false,+ themeId = null,+ mode = "light",+ } = options;try {if (save && scheme?.save) {@@ -69,13 +176,19 @@ export async function applyColorScheme(scheme, options = {}) {return;}- const data = await ajax(`/color-scheme-stylesheet/${id}.json`);+ const themeSegment = themeId === null ? "" : `/${themeId}`;+ const data = await ajax(+ `/color-scheme-stylesheet/${id}${themeSegment}.json`+ );++ const targetTag =+ mode === "dark" ? (darkTag ?? lightTag) : (lightTag ?? darkTag);- if (data?.new_href && lightTag) {- lightTag.href = data.new_href;+ if (data?.new_href && targetTag) {+ targetTag.href = data.new_href;if (replace) {- lightTag.setAttribute("data-scheme-id", id);+ targetTag.setAttribute("data-scheme-id", id);}}@@ -107,7 +220,7 @@ export async function setDefaultColorScheme(try {if (previewMode === "live") {- await applyColorScheme(scheme, { replace: true });+ await applyColorScheme(scheme, { replace: true, mode });}if (!defaultTheme) {diff --git a/frontend/discourse/app/components/admin-onboarding/banner.gjs b/frontend/discourse/app/components/admin-onboarding/banner.gjsindex ff584d93f0c..183992e9211 100644--- a/frontend/discourse/app/components/admin-onboarding/banner.gjs+++ b/frontend/discourse/app/components/admin-onboarding/banner.gjs@@ -2,12 +2,11 @@ import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { hash } from "@ember/helper";import { action } from "@ember/object";-import { trackedArray } from "@ember/reactive/collections";+import { trackedArray, trackedSet } from "@ember/reactive/collections";import { service } from "@ember/service";import SiteSetting from "discourse/admin/models/site-setting";import PredefinedTopicsOptionsModal from "discourse/components/admin-onboarding/modal/predefined-topics-options";import StartPostingOptions from "discourse/components/admin-onboarding/modal/start-posting-options";-import ThemePickerModal from "discourse/components/admin-onboarding/modal/theme-picker";import PredefinedTopicOption from "discourse/components/admin-onboarding/predefined-topics-option";import OnboardingStep from "discourse/components/admin-onboarding/step";import { logOnboardingEvent } from "discourse/lib/admin-onboarding";@@ -15,21 +14,35 @@ import { showCreateInviteModal } from "discourse/lib/invite-modal";import { applyValueTransformer } from "discourse/lib/transformer";import { defaultHomepage } from "discourse/lib/utilities";import DButton from "discourse/ui-kit/d-button";+import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";const STEPS = [class SelectTheme extends OnboardingStep {static name = "select_theme";- @service modal;+ @service designWizard;icon = "paintbrush";+ #onComplete = () => this.markAsCompleted();++ constructor() {+ super(...arguments);+ this.designWizard.resumeAfterThemePreview({+ onComplete: this.#onComplete,+ });+ }++ // a homepage preview routes away from this component while the sheet lives on+ willDestroy() {+ super.willDestroy(...arguments);+ this.designWizard.clearCompletionCallback(this.#onComplete);+ }+@actionperformAction() {- this.modal.show(ThemePickerModal, {- model: { onThemeSelected: () => this.markAsCompleted() },- });+ this.designWizard.start({ onComplete: this.#onComplete });}},class InviteCollaborators extends OnboardingStep {@@ -130,12 +143,43 @@ const STEPS = [];export default class AdminOnboardingBanner extends Component {+ @service appEvents;@service currentUser;@service keyValueStore;@service router;@service toasts;@tracked dismissed = false;+ @tracked minimized = false;+ // the key value store isn't reactive, but the progress count must be+ completedStepNames = trackedSet(+ STEPS.filter(+ (Step) => !!this.keyValueStore.get(`onboarding_step_${Step.name}`)+ ).map((Step) => Step.name)+ );++ constructor() {+ super(...arguments);+ this.appEvents.on(+ "onboarding-step:completed",+ this,+ this.markStepCompleted+ );+ }++ willDestroy() {+ super.willDestroy(...arguments);+ this.appEvents.off(+ "onboarding-step:completed",+ this,+ this.markStepCompleted+ );+ }++ @action+ markStepCompleted(name) {+ this.completedStepNames.add(name);+ }get shouldDisplay() {if (this.dismissed) {@@ -150,6 +194,10 @@ export default class AdminOnboardingBanner extends Component {return currentRouteName === `discovery.${defaultHomepage()}`;}+ get completedSteps() {+ return this.completedStepNames.size;+ }+@actionasync checkIfOnboardingIsComplete() {const allStepsAreDone = STEPS.every(@@ -161,6 +209,11 @@ export default class AdminOnboardingBanner extends Component {}}+ @action+ minimize() {+ this.minimized = !this.minimized;+ }+@actionasync endOnboarding({ skipped = true } = {}) {await SiteSetting.update("enable_site_owner_onboarding", false);@@ -169,6 +222,7 @@ export default class AdminOnboardingBanner extends Component {STEPS.forEach((Step) => {this.keyValueStore.remove(`onboarding_step_${Step.name}`);});+ this.completedStepNames.clear();if (!skipped) {this.toasts.success({@@ -184,25 +238,51 @@ export default class AdminOnboardingBanner extends Component {<div class="admin-onboarding-banner"><div class="admin-onboarding-banner__wrap"><div class="admin-onboarding-banner__header">- <h2>- {{i18n- "admin_onboarding_banner.launch_in_easy_steps"- (hash step_count=STEPS.length)- }}- </h2>- <DButton- @action={{this.endOnboarding}}- @icon="xmark"- class="btn no-text btn-transparent btn-close"- />- </div>- <div class="admin-onboarding-banner__content">- <div class="admin-onboarding-banner__steps">- {{#each STEPS as |Step|}}- <Step @onCompleted={{this.checkIfOnboardingIsComplete}} />- {{/each}}+ <div class="admin-onboarding-banner__header-text">+ <span class="admin-onboarding-banner__title">+ {{dIcon "list" class="admin-onboarding-banner__title-icon"}}+ {{i18n "admin_onboarding_banner.launch_in_easy_steps"}}+ </span>+ {{#if this.minimized}}+ <span class="admin-onboarding-banner__subtitle">+ {{i18n+ "admin_onboarding_banner.launch_in_easy_steps_subtitle"+ (hash+ completed_steps=this.completedSteps+ step_count=STEPS.length+ )+ }}+ </span>+ {{/if}}+ </div>+ <div class="admin-onboarding-banner__header-actions">+ <DButton+ @action={{this.minimize}}+ @icon={{if this.minimized "angle-down" "angle-up"}}+ @ariaLabel={{if+ this.minimized+ "admin_onboarding_banner.expand"+ "admin_onboarding_banner.collapse"+ }}+ class="btn no-text btn-transparent btn-minimize"+ />+ <DButton+ @action={{this.endOnboarding}}+ @icon="xmark"+ @ariaLabel="admin_onboarding_banner.dismiss"+ class="btn no-text btn-transparent btn-close"+ /></div></div>+ {{#unless this.minimized}}+ <div class="admin-onboarding-banner__content">+ <div class="admin-onboarding-banner__steps">+ {{#each STEPS as |Step|}}+ <Step @onCompleted={{this.checkIfOnboardingIsComplete}} />+ {{/each}}+ </div>+ </div>+ {{/unless}}</div></div>{{/if}}diff --git a/frontend/discourse/app/components/admin-onboarding/modal/theme-picker.gjs b/frontend/discourse/app/components/admin-onboarding/modal/theme-picker.gjsdeleted file mode 100644index 4cfc1241c31..00000000000--- a/frontend/discourse/app/components/admin-onboarding/modal/theme-picker.gjs+++ /dev/null@@ -1,153 +0,0 @@-import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";-import { fn } from "@ember/helper";-import { on } from "@ember/modifier";-import { action } from "@ember/object";-import PluginOutlet from "discourse/components/plugin-outlet";-import ThemeCardPreview from "discourse/components/theme-card-preview";-import { ajax } from "discourse/lib/ajax";-import { popupAjaxError } from "discourse/lib/ajax-error";-import getURL from "discourse/lib/get-url";-import {- FOUNDATION_THEME_ID,- HORIZON_THEME_ID,- setLocalTheme,-} from "discourse/lib/theme-selector";-import { eq } from "discourse/truth-helpers";-import DButton from "discourse/ui-kit/d-button";-import DModal from "discourse/ui-kit/d-modal";-import dIcon from "discourse/ui-kit/helpers/d-icon";-import { i18n } from "discourse-i18n";--const ALLOWED_THEME_IDS = [FOUNDATION_THEME_ID, HORIZON_THEME_ID];--const ThemeCard = <template>- <div- class="theme-picker-modal__card {{if @isSelected '--selected'}}"- {{on "click" (fn @onSelect @theme)}}- role="button"- >- {{#if @isSelected}}- <span class="theme-picker-modal__enabled-badge">- {{dIcon "check"}}- {{i18n "admin_onboarding_banner.select_theme.enabled"}}- </span>- {{/if}}- <ThemeCardPreview @theme={{@theme}} />- </div>-</template>;--export default class ThemePickerModal extends Component {- @tracked themes = [];- @tracked loading = true;- @tracked saving = false;- @tracked selectedTheme = null;-- constructor() {- super(...arguments);- this.loadThemes();- }-- async loadThemes() {- try {- const result = await ajax("/admin/themes.json");- this.themes = result.themes.filter((theme) =>- ALLOWED_THEME_IDS.includes(theme.id)- );- this.selectedTheme = this.themes.find((t) => t.default) || null;- } catch (error) {- popupAjaxError(error);- } finally {- this.loading = false;- }- }-- get applyDisabled() {- return !this.selectedTheme || this.saving;- }-- @action- selectTheme(theme) {- this.selectedTheme = theme;- }-- @action- async applyTheme() {- if (this.applyDisabled) {- return;- }-- if (this.selectedTheme.default) {- await this.args.model?.onThemeSelected?.();- this.args.closeModal();- return;- }-- this.saving = true;-- try {- await ajax(`/admin/themes/${this.selectedTheme.id}.json`, {- type: "PUT",- data: { theme: { default: true } },- });-- setLocalTheme([], 0);-- await this.args.model?.onThemeSelected?.();- window.location.reload();- } catch (error) {- this.saving = false;- popupAjaxError(error);- }- }-- <template>- <DModal- class="theme-picker-modal --max"- @title={{i18n "admin_onboarding_banner.select_theme.modal_title"}}- @closeModal={{@closeModal}}- >- <:body>- {{#if this.loading}}- <div class="theme-picker-modal__loading">- <div class="spinner"></div>- </div>- {{else}}- <div class="theme-picker-modal__themes">- {{#each this.themes as |theme|}}- <ThemeCard- @theme={{theme}}- @isSelected={{if- this.selectedTheme- (eq this.selectedTheme.id theme.id)- false- }}- @onSelect={{this.selectTheme}}- />- {{/each}}- </div>- <div class="theme-picker-modal__footer">- <DButton- @action={{this.applyTheme}}- @translatedLabel={{if- this.saving- (i18n "admin_onboarding_banner.select_theme.applying_theme")- (i18n "admin_onboarding_banner.select_theme.use_theme")- }}- @disabled={{this.applyDisabled}}- @isLoading={{this.saving}}- class="btn-primary"- />- </div>- <PluginOutlet @name="theme-picker-modal-below-themes">- <p class="theme-picker-modal__browse-all">- <a href={{getURL "/admin/config/customize/themes"}}>- {{i18n "admin_onboarding_banner.select_theme.browse_all"}}- </a>- </p>- </PluginOutlet>- {{/if}}- </:body>- </DModal>- </template>-}diff --git a/frontend/discourse/app/components/admin-onboarding/step.gjs b/frontend/discourse/app/components/admin-onboarding/step.gjsindex ce3b0c5cadb..b5ed32f774c 100644--- a/frontend/discourse/app/components/admin-onboarding/step.gjs+++ b/frontend/discourse/app/components/admin-onboarding/step.gjs@@ -4,8 +4,8 @@ import { concat } from "@ember/helper";import { action } from "@ember/object";import { service } from "@ember/service";import { logOnboardingEvent } from "discourse/lib/admin-onboarding";-import { currentThemeId, HORIZON_THEME_ID } from "discourse/lib/theme-selector";import DButton from "discourse/ui-kit/d-button";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";@@ -26,14 +26,14 @@ export default class OnboardingStep extends Component {return this.constructor.name;}- get icon() {- throw new Error("Icon is required for OnboardingStep");+ get checkboxIcon() {+ return this.completed ? "circle-check" : "far-circle";}- get btnClass() {- return currentThemeId() === HORIZON_THEME_ID- ? "btn-default"- : "btn-primary";+ get buttonLabel() {+ return this.completed+ ? `admin_onboarding_banner.${this.name}.completed`+ : `admin_onboarding_banner.${this.name}.action`;}@action@@ -66,25 +66,30 @@ export default class OnboardingStep extends Component {<div class="onboarding-step" id={{this.name}}><div class="onboarding-step__checkbox">{{~dIcon- (if this.completed "square-check" "far-square")- class=(if this.completed "checked")+ this.checkboxIcon+ class=(dConcatClass+ "onboarding-step__checkbox-icon" (if this.completed "--completed")+ )}}- <span>{{i18n (concat this.i18nKey this.name ".title")}}</span>+ <span class="onboarding-step__title">{{i18n+ (concat this.i18nKey this.name ".title")+ }}</span>+</div><div class="onboarding-step__description">- <div class="onboarding-step__text">- {{i18n (concat this.i18nKey this.name ".description")}}- </div>+ {{i18n (concat this.i18nKey this.name ".description")}}</div>-<div class="onboarding-step__action"><DButton- @icon={{this.icon}}- @label={{concat this.i18nKey this.name ".action"}}+ @label={{this.buttonLabel}}@action={{this.performAction}}- class={{this.btnClass}}+ class={{dConcatClass+ "btn-transparent btn-small btn-link"+ (if this.completed "--completed")+ }}/>+</div></div></template>diff --git a/frontend/discourse/app/components/design-wizard-panel.gjs b/frontend/discourse/app/components/design-wizard-panel.gjsnew file mode 100644index 00000000000..6141b61eae2--- /dev/null+++ b/frontend/discourse/app/components/design-wizard-panel.gjs@@ -0,0 +1,59 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { service } from "@ember/service";+import DesignWizardControls from "discourse/components/design-wizard/controls";+import { isTesting } from "discourse/lib/environment";+import { prefersReducedMotion } from "discourse/lib/utilities";+import DButton from "discourse/ui-kit/d-button";++export default class DesignWizardPanel extends Component {+ @service designWizard;++ element;++ @action+ registerElement(element) {+ this.element = element;+ }++ @action+ async close() {+ if (this.element && !isTesting() && !prefersReducedMotion()) {+ const slideOut =+ getComputedStyle(this.element)+ .getPropertyValue("--design-wizard-slide-out")+ .trim() || "translateX(100%)";++ await this.element+ .animate([{ transform: "translate(0, 0)" }, { transform: slideOut }], {+ duration: 250,+ easing: "ease-in",+ fill: "forwards",+ })+ .finished.catch(() => {});+ }++ this.designWizard.stop();+ }++ <template>+ {{#if this.designWizard.active}}+ <aside+ class="design-wizard+ {{unless this.designWizard.animateEntrance '--no-entrance'}}"+ aria-labelledby="design-wizard-title"+ {{didInsert this.registerElement}}+ ...attributes+ >+ <DButton+ @action={{this.close}}+ @icon="xmark"+ @title="modal.close"+ class="btn-transparent design-wizard__close"+ />+ <DesignWizardControls />+ </aside>+ {{/if}}+ </template>+}diff --git a/frontend/discourse/app/components/design-wizard/colors-section.gjs b/frontend/discourse/app/components/design-wizard/colors-section.gjsnew file mode 100644index 00000000000..6a8f1506b6f--- /dev/null+++ b/frontend/discourse/app/components/design-wizard/colors-section.gjs@@ -0,0 +1,90 @@+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { swatchStyle } from "discourse/lib/design-wizard-preview";+import { eq } from "discourse/truth-helpers";+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";++function swatchPalette(pair) {+ return pair.light ?? pair.dark;+}++const DesignWizardColorsSection = <template>+ <div class="design-wizard__color">+ <div class="design-wizard__color-modes">+ <button+ type="button"+ class="design-wizard__color-mode+ {{if (eq @colorMode 'light') '--active'}}"+ aria-pressed={{if (eq @colorMode "light") "true" "false"}}+ disabled={{@darkOnly}}+ {{on "click" (fn @onSelectMode "light")}}+ >+ {{i18n "design_wizard.colors.light"}}+ </button>+ <button+ type="button"+ class="design-wizard__color-mode+ {{if (eq @colorMode 'dark') '--active'}}"+ aria-pressed={{if (eq @colorMode "dark") "true" "false"}}+ {{on "click" (fn @onSelectMode "dark")}}+ >+ {{i18n "design_wizard.colors.dark"}}+ </button>+ </div>+ <div class="design-wizard__swatches">+ {{#each @pairs as |pair|}}+ <button+ type="button"+ class="design-wizard__swatch+ {{if (eq pair.key @selectedPairKey) '--selected'}}"+ aria-pressed={{if (eq pair.key @selectedPairKey) "true" "false"}}+ data-pair-key={{pair.key}}+ {{on "click" (fn @onSelectPair pair.key)}}+ >+ <span+ class="design-wizard__swatch-preview"+ style={{swatchStyle (swatchPalette pair)}}+ ></span>+ <span class="design-wizard__swatch-name">+ {{pair.name}}+ {{#if pair.dark_only}}{{dIcon "moon"}}{{/if}}+ </span>+ </button>+ {{/each}}+ </div>+ <p class="design-wizard__color-note">+ {{#if @darkOnly}}+ {{i18n "design_wizard.colors.dark_only" name=@selectedPairName}}+ {{else}}+ {{i18n "design_wizard.colors.both_modes"}}+ {{/if}}+ </p>+ </div>++ <div class="design-wizard__user-selectable">+ <div>+ <span+ id="design-wizard-user-selectable-title"+ class="design-wizard__user-selectable-title"+ >+ {{i18n "design_wizard.colors.user_selectable"}}+ </span>+ <span+ id="design-wizard-user-selectable-description"+ class="design-wizard__user-selectable-description"+ >+ {{i18n "design_wizard.colors.user_selectable_description"}}+ </span>+ </div>+ <DToggleSwitch+ @state={{@userSelectable}}+ aria-labelledby="design-wizard-user-selectable-title"+ aria-describedby="design-wizard-user-selectable-description"+ {{on "click" @onToggleUserSelectable}}+ />+ </div>+</template>;++export default DesignWizardColorsSection;diff --git a/frontend/discourse/app/components/design-wizard/controls.gjs b/frontend/discourse/app/components/design-wizard/controls.gjsnew file mode 100644index 00000000000..73f45e0f9fe--- /dev/null+++ b/frontend/discourse/app/components/design-wizard/controls.gjs@@ -0,0 +1,216 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { service } from "@ember/service";+import ColorsSection from "discourse/components/design-wizard/colors-section";+import FontsSection from "discourse/components/design-wizard/fonts-section";+import HomepageSection from "discourse/components/design-wizard/homepage-section";+import Section from "discourse/components/design-wizard/section";+import ThemeSection from "discourse/components/design-wizard/theme-section";+import { eq } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import { i18n } from "discourse-i18n";++const STEPS = ["theme", "colors", "homepage"];++export default class DesignWizardControls extends Component {+ @service designWizard;++ goToStepLabel(index) {+ return i18n("design_wizard.step_label", { index: index + 1 });+ }++ get currentStep() {+ return STEPS[this.designWizard.stepIndex] ?? STEPS[0];+ }++ get isFirstStep() {+ return this.designWizard.stepIndex <= 0;+ }++ get isLastStep() {+ return this.designWizard.stepIndex >= STEPS.length - 1;+ }++ // a site whose default theme is custom starts with no theme selected, and+ // the later steps are meaningless until one is chosen+ get needsThemeChoice() {+ return this.currentStep === "theme" && !this.designWizard.themeId;+ }++ @action+ async goToStep(index) {+ if (index === this.designWizard.stepIndex) {+ return;+ }++ if (index > this.designWizard.stepIndex && this.needsThemeChoice) {+ return;+ }++ if (+ index < this.designWizard.stepIndex ||+ (await this.designWizard.saveProgress())+ ) {+ this.designWizard.setStepIndex(index);+ }+ }++ @action+ back() {+ this.designWizard.setStepIndex(+ Math.max(this.designWizard.stepIndex - 1, 0)+ );+ }++ @action+ async next() {+ if (await this.designWizard.saveProgress()) {+ this.designWizard.setStepIndex(+ Math.min(this.designWizard.stepIndex + 1, STEPS.length - 1)+ );+ }+ }++ @action+ selectTheme(themeId) {+ this.designWizard.selectTheme(themeId);+ }++ @action+ selectPair(pairKey) {+ this.designWizard.selectPair(pairKey);+ }++ @action+ selectColorMode(mode) {+ this.designWizard.selectColorMode(mode);+ }++ @action+ toggleUserSelectable() {+ this.designWizard.toggleUserSelectable();+ }++ @action+ selectBodyFont(fontKey) {+ this.designWizard.selectBodyFont(fontKey);+ }++ @action+ selectHeadingFont(fontKey) {+ this.designWizard.selectHeadingFont(fontKey);+ }++ @action+ selectHomepage(homepage) {+ this.designWizard.selectHomepage(homepage);+ }++ @action+ selectCategoryPageStyle(value) {+ this.designWizard.selectCategoryPageStyle(value);+ }++ @action+ save() {+ this.designWizard.save();+ }++ <template>+ <div class="design-wizard__content">+ <header class="design-wizard__header">+ <h2 id="design-wizard-title">+ {{i18n "design_wizard.title"}}+ </h2>+ <span class="design-wizard__subtitle">+ {{i18n "design_wizard.subtitle"}}+ </span>+ </header>++ <div class="design-wizard__sections">+ {{#if (eq this.currentStep "theme")}}+ <Section @title={{i18n "design_wizard.sections.theme"}}>+ <ThemeSection+ @themes={{this.designWizard.data.themes}}+ @currentTheme={{this.designWizard.data.current_theme}}+ @selectedThemeId={{this.designWizard.themeId}}+ @onSelect={{this.selectTheme}}+ />+ </Section>+ {{else if (eq this.currentStep "colors")}}+ <Section @title={{i18n "design_wizard.sections.colors"}}>+ <ColorsSection+ @pairs={{this.designWizard.pairs}}+ @selectedPairKey={{this.designWizard.selectedPair.key}}+ @selectedPairName={{this.designWizard.selectedPair.name}}+ @colorMode={{this.designWizard.effectiveColorMode}}+ @darkOnly={{this.designWizard.selectedPair.dark_only}}+ @userSelectable={{this.designWizard.palettesUserSelectable}}+ @onSelectPair={{this.selectPair}}+ @onSelectMode={{this.selectColorMode}}+ @onToggleUserSelectable={{this.toggleUserSelectable}}+ />+ </Section>++ <Section @title={{i18n "design_wizard.sections.fonts"}}>+ <FontsSection+ @bodyFont={{this.designWizard.bodyFont}}+ @headingFont={{this.designWizard.headingFont}}+ @onSelectBodyFont={{this.selectBodyFont}}+ @onSelectHeadingFont={{this.selectHeadingFont}}+ />+ </Section>+ {{else}}+ <Section @title={{i18n "design_wizard.sections.homepage"}}>+ <HomepageSection+ @themeId={{this.designWizard.themeId}}+ @homepage={{this.designWizard.homepage}}+ @categoryPageStyle={{this.designWizard.categoryPageStyle}}+ @onSelectHomepage={{this.selectHomepage}}+ @onSelectCategoryPageStyle={{this.selectCategoryPageStyle}}+ />+ </Section>+ {{/if}}+ </div>++ <footer class="design-wizard__actions">+ <div class="design-wizard__step-dots">+ {{#each STEPS as |step index|}}+ <button+ type="button"+ class="design-wizard__step-dot+ {{if (eq step this.currentStep) '--active'}}"+ aria-label={{this.goToStepLabel index}}+ aria-current={{if (eq step this.currentStep) "true"}}+ {{on "click" (fn this.goToStep index)}}+ ></button>+ {{/each}}+ </div>+ <DButton+ @action={{this.back}}+ @label="design_wizard.back"+ @disabled={{this.isFirstStep}}+ class="btn-flat design-wizard__back"+ />+ {{#if this.isLastStep}}+ <DButton+ @action={{this.save}}+ @label="design_wizard.save"+ @isLoading={{this.designWizard.saving}}+ class="btn-primary design-wizard__save"+ />+ {{else}}+ <DButton+ @action={{this.next}}+ @label="design_wizard.next"+ @isLoading={{this.designWizard.saving}}+ @disabled={{this.needsThemeChoice}}+ class="btn-primary design-wizard__next"+ />+ {{/if}}+ </footer>+ </div>+ </template>+}diff --git a/frontend/discourse/app/components/design-wizard/fonts-section.gjs b/frontend/discourse/app/components/design-wizard/fonts-section.gjsnew file mode 100644index 00000000000..416d8f2921d--- /dev/null+++ b/frontend/discourse/app/components/design-wizard/fonts-section.gjs@@ -0,0 +1,120 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { MAIN_FONTS, MORE_FONTS } from "discourse/admin/lib/constants";+import DMenu from "discourse/float-kit/components/d-menu";+import { fontClass } from "discourse/lib/design-wizard-preview";+import { eq } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";++const ALL_FONTS = [...MAIN_FONTS, ...MORE_FONTS];++const FontTrigger = <template>+ <button class="btn btn-default btn-icon-text" type="button" ...attributes>+ <span class="d-button-label {{fontClass @fontKey}}">{{@label}}</span>+ {{dIcon "angle-down" class="design-wizard__font-select-caret"}}+ </button>+</template>;++export default class DesignWizardFontsSection extends Component {+ get baseFontLabel() {+ return this.#fontName(this.args.bodyFont);+ }++ get headingFontLabel() {+ return this.#fontName(this.args.headingFont);+ }++ #fontName(selectedKey) {+ return (+ ALL_FONTS.find((font) => font.key === selectedKey)?.name ?? selectedKey+ );+ }++ @action+ async selectFont(onSelect, fontKey, dMenu) {+ await dMenu.close();+ onSelect(fontKey);+ }++ <template>+ <div class="design-wizard__font-group">+ <span class="design-wizard__label">+ {{i18n "design_wizard.fonts.base_font"}}+ </span>+ <DMenu+ @identifier="design-wizard-base-font"+ @triggerClass="design-wizard__font-select"+ @contentClass="design-wizard__font-select-content"+ @modalForMobile={{true}}+ @triggerComponent={{component+ FontTrigger+ label=this.baseFontLabel+ fontKey=@bodyFont+ }}+ >+ <:content as |dMenu|>+ <DDropdownMenu class="design-wizard__font-list" as |dropdown|>+ {{#each ALL_FONTS as |font|}}+ <dropdown.item>+ <DButton+ @action={{fn+ this.selectFont+ @onSelectBodyFont+ font.key+ dMenu+ }}+ @translatedLabel={{font.name}}+ class="btn-flat+ {{fontClass font.key}}+ {{if (eq font.key @bodyFont) '-selected'}}"+ />+ </dropdown.item>+ {{/each}}+ </DDropdownMenu>+ </:content>+ </DMenu>+ </div>++ <div class="design-wizard__font-group">+ <span class="design-wizard__label">+ {{i18n "design_wizard.fonts.heading_font"}}+ </span>+ <DMenu+ @identifier="design-wizard-heading-font"+ @triggerClass="design-wizard__font-select"+ @contentClass="design-wizard__font-select-content"+ @modalForMobile={{true}}+ @triggerComponent={{component+ FontTrigger+ label=this.headingFontLabel+ fontKey=@headingFont+ }}+ >+ <:content as |dMenu|>+ <DDropdownMenu class="design-wizard__font-list" as |dropdown|>+ {{#each ALL_FONTS as |font|}}+ <dropdown.item>+ <DButton+ @action={{fn+ this.selectFont+ @onSelectHeadingFont+ font.key+ dMenu+ }}+ @translatedLabel={{font.name}}+ class="btn-flat+ {{fontClass font.key}}+ {{if (eq font.key @headingFont) '-selected'}}"+ />+ </dropdown.item>+ {{/each}}+ </DDropdownMenu>+ </:content>+ </DMenu>+ </div>+ </template>+}diff --git a/frontend/discourse/app/components/design-wizard/homepage-section.gjs b/frontend/discourse/app/components/design-wizard/homepage-section.gjsnew file mode 100644index 00000000000..cd6a5c60579--- /dev/null+++ b/frontend/discourse/app/components/design-wizard/homepage-section.gjs@@ -0,0 +1,198 @@+import { array, fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { HORIZON_THEME_ID } from "discourse/lib/theme-selector";+import { eq } from "discourse/truth-helpers";+import { i18n } from "discourse-i18n";++const TOPIC_PAGES = ["latest", "new", "hot"];++function topicPageLabel(page) {+ return i18n(`filters.${page}.title`);+}++function topicPageDescription(page) {+ return i18n(`design_wizard.homepage.topic_pages.${page}`);+}++function isHorizon(themeId) {+ return themeId === HORIZON_THEME_ID;+}++const TopicsMock = <template>+ {{#if (isHorizon @themeId)}}+ {{#each (array 1 2)}}+ <span class="design-wizard__mock-card">+ <span class="design-wizard__mock-avatar"></span>+ <span class="design-wizard__mock-line --title"></span>+ <span class="design-wizard__mock-line --text"></span>+ <span class="design-wizard__mock-badge"></span>+ </span>+ {{/each}}+ {{else}}+ {{#each (array 1 2 3 4)}}+ <span class="design-wizard__mock-row">+ <span class="design-wizard__mock-line --title"></span>+ <span class="design-wizard__mock-avatar"></span>+ <span class="design-wizard__mock-line --count"></span>+ </span>+ {{/each}}+ {{/if}}+</template>;++const CATEGORY_STYLE_OPTIONS = [+ { value: "categories_boxes", kind: "boxes" },+ { value: "categories_and_latest_topics", kind: "with-topics" },+ { value: "categories_only", kind: "only" },+];++function categoryStyleLabel(kind) {+ return i18n(`design_wizard.homepage.styles.${kind.replaceAll("-", "_")}`);+}++function categoryStyleKind(style) {+ if (style === "categories_only") {+ return "only";+ }++ if (style?.startsWith("categories_boxes")) {+ return "boxes";+ }++ return "with-topics";+}++const CategoriesMock = <template>+ {{#each (array "c1" "c2" "c3" "c4") as |box|}}+ <span class="design-wizard__mock-box --{{box}}">+ <span class="design-wizard__mock-line --title"></span>+ <span class="design-wizard__mock-line --text"></span>+ <span class="design-wizard__mock-line --text"></span>+ </span>+ {{/each}}+</template>;++const CategoryStyleMock = <template>+ {{#if (eq @kind "boxes")}}+ <CategoriesMock />+ {{else if (eq @kind "only")}}+ {{#each (array "c1" "c2" "c3" "c4") as |row|}}+ <span class="design-wizard__mock-row">+ <span class="design-wizard__mock-cat-badge --{{row}}"></span>+ <span class="design-wizard__mock-line --title"></span>+ <span class="design-wizard__mock-line --count"></span>+ </span>+ {{/each}}+ {{else}}+ <span class="design-wizard__mock-columns">+ <span class="design-wizard__mock-column">+ {{#each (array "c1" "c2" "c3") as |row|}}+ <span class="design-wizard__mock-row">+ <span class="design-wizard__mock-cat-badge --{{row}}"></span>+ <span class="design-wizard__mock-line --title"></span>+ </span>+ {{/each}}+ </span>+ <span class="design-wizard__mock-column">+ {{#each (array 1 2 3)}}+ <span class="design-wizard__mock-row">+ <span class="design-wizard__mock-avatar"></span>+ <span class="design-wizard__mock-line --title"></span>+ </span>+ {{/each}}+ </span>+ </span>+ {{/if}}+</template>;++const DesignWizardHomepageSection = <template>+ <div class="design-wizard__homepage-cards">+ <button+ type="button"+ class="design-wizard__homepage-card+ {{unless (eq @homepage 'categories') '--selected'}}"+ aria-pressed={{if (eq @homepage "categories") "false" "true"}}+ data-homepage="topics"+ {{on "click" (fn @onSelectHomepage "latest")}}+ >+ <span+ class="design-wizard__homepage-thumbnail --topics+ {{if (isHorizon @themeId) '--horizon'}}"+ >+ <TopicsMock @themeId={{@themeId}} />+ </span>+ {{i18n "design_wizard.homepage.topics"}}+ </button>+ <button+ type="button"+ class="design-wizard__homepage-card+ {{if (eq @homepage 'categories') '--selected'}}"+ aria-pressed={{if (eq @homepage "categories") "true" "false"}}+ data-homepage="categories"+ {{on "click" (fn @onSelectHomepage "categories")}}+ >+ <span class="design-wizard__homepage-thumbnail --categories">+ <CategoriesMock />+ </span>+ {{i18n "design_wizard.homepage.categories"}}+ </button>+ </div>++ {{#if (eq @homepage "categories")}}+ <div class="design-wizard__homepage-detail">+ <span class="design-wizard__label">+ {{i18n "design_wizard.homepage.category_page_style"}}+ </span>+ <div class="design-wizard__style-blocks">+ {{#let (categoryStyleKind @categoryPageStyle) as |selectedKind|}}+ {{#each CATEGORY_STYLE_OPTIONS as |option|}}+ <button+ type="button"+ class="design-wizard__style-block+ {{if (eq selectedKind option.kind) '--selected'}}"+ aria-pressed={{if (eq selectedKind option.kind) "true" "false"}}+ data-style={{option.value}}+ {{on "click" (fn @onSelectCategoryPageStyle option.value)}}+ >+ <span+ class="design-wizard__homepage-style-preview+ {{if (eq option.kind 'boxes') '--boxes'}}"+ >+ <CategoryStyleMock @kind={{option.kind}} />+ </span>+ {{categoryStyleLabel option.kind}}+ </button>+ {{/each}}+ {{/let}}+ </div>+ </div>+ {{else}}+ <div class="design-wizard__homepage-detail">+ <span class="design-wizard__label">+ {{i18n "design_wizard.homepage.topic_page_type"}}+ </span>+ <div class="design-wizard__topic-page-options">+ {{#each TOPIC_PAGES as |page|}}+ <button+ type="button"+ class="design-wizard__topic-page-option+ {{if (eq page @homepage) '--selected'}}"+ aria-pressed={{if (eq page @homepage) "true" "false"}}+ data-topic-page={{page}}+ {{on "click" (fn @onSelectHomepage page)}}+ >+ <span class="design-wizard__topic-page-option-texts">+ <span class="design-wizard__topic-page-option-label">+ {{topicPageLabel page}}+ </span>+ <span class="design-wizard__topic-page-option-description">+ {{topicPageDescription page}}+ </span>+ </span>+ </button>+ {{/each}}+ </div>+ </div>+ {{/if}}+</template>;++export default DesignWizardHomepageSection;diff --git a/frontend/discourse/app/components/design-wizard/section.gjs b/frontend/discourse/app/components/design-wizard/section.gjsnew file mode 100644index 00000000000..a6ba8250d94--- /dev/null+++ b/frontend/discourse/app/components/design-wizard/section.gjs@@ -0,0 +1,10 @@+const DesignWizardSection = <template>+ <section class="design-wizard__section" ...attributes>+ <h3 class="design-wizard__section-title">{{@title}}</h3>+ <div class="design-wizard__section-body">+ {{yield}}+ </div>+ </section>+</template>;++export default DesignWizardSection;diff --git a/frontend/discourse/app/components/design-wizard/theme-section.gjs b/frontend/discourse/app/components/design-wizard/theme-section.gjsnew file mode 100644index 00000000000..52c715d1084--- /dev/null+++ b/frontend/discourse/app/components/design-wizard/theme-section.gjs@@ -0,0 +1,87 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { service } from "@ember/service";+import { eq } from "discourse/truth-helpers";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";++class ThemeCard extends Component {+ @service interfaceColor;+ @service session;++ get currentScreenshotUrl() {+ const { screenshot_dark_url, screenshot_light_url } = this.args.theme;+ return this.#showDarkScreenshot+ ? screenshot_dark_url || screenshot_light_url+ : screenshot_light_url || screenshot_dark_url;+ }++ get #showDarkScreenshot() {+ return (+ this.interfaceColor?.colorModeIsDark ||+ window.matchMedia("(prefers-color-scheme: dark)").matches ||+ this.session?.defaultColorSchemeIsDark+ );+ }++ <template>+ <div class="design-wizard__theme-card-wrapper">+ <label+ class="design-wizard__theme-card+ {{if (eq @theme.id @selectedThemeId) '--selected'}}"+ data-theme-id={{@theme.id}}+ >+ <input+ type="radio"+ name="design-wizard-theme"+ value={{@theme.id}}+ checked={{eq @theme.id @selectedThemeId}}+ class="sr-only"+ {{on "change" (fn @onSelect @theme.id)}}+ />+ {{#if (eq @theme.id @selectedThemeId)}}+ <span class="design-wizard__theme-enabled-badge">+ {{dIcon "check"}}+ {{i18n "design_wizard.theme.selected"}}+ </span>+ {{/if}}+ <span class="design-wizard__theme-screenshot">+ {{#if this.currentScreenshotUrl}}+ <img+ class="design-wizard__theme-screenshot-image"+ src={{this.currentScreenshotUrl}}+ alt=""+ />+ {{/if}}+ </span>+ <span class="design-wizard__theme-name">{{@theme.name}}</span>+ <span class="design-wizard__theme-description">+ {{@theme.description}}+ </span>+ </label>+ </div>+ </template>+}++const DesignWizardThemeSection = <template>+ {{#if @currentTheme}}+ <p class="design-wizard__custom-theme-notice">+ {{i18n "design_wizard.theme.custom_theme_notice" [email protected]}}+ </p>+ {{/if}}+ <fieldset class="design-wizard__theme-cards">+ <legend class="sr-only">+ {{i18n "design_wizard.sections.theme"}}+ </legend>+ {{#each @themes as |theme|}}+ <ThemeCard+ @theme={{theme}}+ @selectedThemeId={{@selectedThemeId}}+ @onSelect={{@onSelect}}+ />+ {{/each}}+ </fieldset>+</template>;++export default DesignWizardThemeSection;diff --git a/frontend/discourse/app/lib/design-wizard-preview.js b/frontend/discourse/app/lib/design-wizard-preview.jsnew file mode 100644index 00000000000..94faa8261d2--- /dev/null+++ b/frontend/discourse/app/lib/design-wizard-preview.js@@ -0,0 +1,123 @@+import { trustHTML } from "@ember/template";++function hex(colors, name, fallback) {+ const value = colors?.[name] ?? fallback;+ return `#${`${value}`.replace(/[^0-9a-f]/gi, "")}`;+}++/**+ * Builds the inline style for a palette swatch in the design wizard rail.+ *+ * @param {Object} palette - serialized palette with a `colors` map+ * @returns {ReturnType<typeof trustHTML>} inline style string+ */+export function swatchStyle(palette) {+ const bg = hex(palette?.colors, "secondary", "ffffff");+ const accent = hex(palette?.colors, "tertiary", "0088cc");++ return trustHTML(+ `background: linear-gradient(135deg, ${accent} 50%, color-mix(in srgb, ${accent} 18%, ${bg}) 50%)`+ );+}++/**+ * CSS class applying a font's real typeface, defined by the wizard+ * stylesheet target which is always loaded for admins.+ *+ * @param {string} fontKey - font key, e.g. `open_sans`+ * @param {"body" | "heading"} scope+ * @returns {string} class name+ */+export function fontClass(fontKey, scope = "body") {+ return `${scope}-font-${fontKey.replaceAll("_", "-")}`;+}++const fontStacks = new Map();++function probeFontStack(fontKey) {+ const probe = document.createElement("span");+ probe.className = fontClass(fontKey);+ probe.hidden = true;+ document.body.appendChild(probe);++ try {+ const probed = getComputedStyle(probe).fontFamily;+ // the stylesheet defining the font classes may not have loaded yet+ const inherited = getComputedStyle(document.body).fontFamily;+ return probed === inherited ? null : probed;+ } finally {+ probe.remove();+ }+}++/**+ * Resolves a font key to its full font-family stack by probing the computed+ * style of the wizard stylesheet's font classes.+ *+ * Memoized only once the defining stylesheet has loaded, so an early probe+ * can't pin a wrong stack for the page's lifetime.+ *+ * @param {string} fontKey - font key, e.g. `open_sans`+ * @returns {?string} CSS font-family value, or null if not yet resolvable+ */+export function fontStack(fontKey) {+ if (!fontStacks.has(fontKey)) {+ const probed = probeFontStack(fontKey);+ if (probed === null) {+ return null;+ }++ fontStacks.set(fontKey, probed);+ }++ return fontStacks.get(fontKey);+}++/**+ * Previews fonts in the given document by overriding the font custom+ * properties every stylesheet resolves against.+ *+ * Only the family is overridden, not the per-font letter spacing and feature+ * settings the stylesheet importer emits, so fonts defining those preview+ * slightly differently than they save.+ *+ * @param {Document} doc - target document+ * @param {Object} options+ * @param {string} options.bodyFont - font key+ * @param {string} options.headingFont - font key+ */+export function applyPreviewFonts(doc, { bodyFont, headingFont }) {+ const root = doc?.documentElement;+ if (!root) {+ return;+ }++ const families = {+ "--font-family": fontStack(bodyFont),+ "--heading-font-family": fontStack(headingFont),+ };++ for (const [property, family] of Object.entries(families)) {+ if (family) {+ root.style.setProperty(property, family);+ } else {+ // leave the saved font in place rather than fall back to the browser's+ root.style.removeProperty(property);+ }+ }+}++/**+ * Removes font previews applied to the given document.+ *+ * @param {Document} doc - target document+ */+export function clearPreview(doc) {+ const root = doc?.documentElement;+ if (!root) {+ return;+ }++ root.style.removeProperty("--font-family");+ root.style.removeProperty("--heading-font-family");+}diff --git a/frontend/discourse/app/services/design-wizard.js b/frontend/discourse/app/services/design-wizard.jsnew file mode 100644index 00000000000..5431c32e0ef--- /dev/null+++ b/frontend/discourse/app/services/design-wizard.js@@ -0,0 +1,446 @@+import { tracked } from "@glimmer/tracking";+import Service, { service } from "@ember/service";+import {+ applyColorScheme,+ captureColorSchemeLinks,+ renderedColorMode,+ restoreColorSchemeLinks,+ showColorMode,+} from "discourse/admin/lib/color-scheme-manager";+import { logOnboardingEvent } from "discourse/lib/admin-onboarding";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import {+ applyPreviewFonts,+ clearPreview,+} from "discourse/lib/design-wizard-preview";+import { isTesting } from "discourse/lib/environment";+import getURL from "discourse/lib/get-url";+import discourseLater from "discourse/lib/later";+import { HORIZON_THEME_ID, setLocalTheme } from "discourse/lib/theme-selector";++const STATE_KEY = "design_wizard_panel_state";+const SELECT_THEME_STEP = "select_theme";+// mirrors the onboarding step's own completion key so a wizard finished+// after its caller was torn down still marks the step complete+const STEP_COMPLETED_KEY = `onboarding_step_${SELECT_THEME_STEP}`;++/**+ * Drives the design wizard panel while the current page acts as the live+ * preview. Each completed step is persisted so the flow can survive the theme+ * preview reloads required by a different asset build.+ */+export default class DesignWizardService extends Service {+ @service keyValueStore;+ @service router;+ @service siteSettings;++ @tracked active = false;+ @tracked data;+ @tracked themeId;+ @tracked colorMode = "light";+ @tracked palettesUserSelectable = false;+ @tracked bodyFont;+ @tracked headingFont;+ @tracked homepage;+ @tracked categoryPageStyle;+ @tracked saving = false;+ @tracked selectedPairKeys = new Map();+ @tracked stepIndex = 0;+ // resuming an in-progress wizard (e.g. after a theme-preview reload)+ // should not replay the sheet's entrance animation+ @tracked animateEntrance = true;++ #onComplete;+ #originalCategoryPageStyle;+ #originalColorSchemeLinks;++ async start({ onComplete } = {}) {+ this.#onComplete = onComplete;+ this.#originalCategoryPageStyle ??=+ this.siteSettings.desktop_category_page_style;++ // always fetch fresh: progress saves change the settings this payload+ // reflects, so a cached copy would preview stale selections+ try {+ this.data = await ajax("/admin/config/design-wizard.json");+ } catch (error) {+ popupAjaxError(error);+ return;+ }++ const stored = this.#storedState;+ if (stored) {+ this.#restore(stored);+ } else {+ this.#initFromData();+ }++ this.animateEntrance = !stored;+ this.active = true;+ this.#originalColorSchemeLinks = captureColorSchemeLinks();++ if (stored && this.homepage === "categories") {+ this.siteSettings.desktop_category_page_style = this.categoryPageStyle;+ }++ await this.#previewSelections();+ }++ // lets `save` fall back to the store instead of reaching into a caller that+ // was torn down while the sheet stayed open+ clearCompletionCallback(callback) {+ if (callback === undefined || this.#onComplete === callback) {+ this.#onComplete = undefined;+ }+ }++ resumeAfterThemePreview({ onComplete } = {}) {+ // the caller can remount while the sheet is open (the onboarding banner+ // renders per-route); an active wizard has nothing to resume, only the+ // completion callback needs to point at the fresh caller+ if (this.active) {+ this.#onComplete = onComplete;+ return;+ }++ const previewThemeId = new URLSearchParams(window.location.search).get(+ "preview_theme_id"+ );+ if (!this.#storedState || previewThemeId === null) {+ return;+ }++ this.start({ onComplete });+ }++ get selectedTheme() {+ return this.data?.themes.find((theme) => theme.id === this.themeId);+ }++ get pairs() {+ return this.selectedTheme?.palette_pairs ?? [];+ }++ get selectedPair() {+ const key = this.selectedPairKeys.get(this.themeId);+ return this.pairs.find((pair) => pair.key === key) ?? this.pairs[0];+ }++ get effectiveColorMode() {+ return this.selectedPair?.dark_only ? "dark" : this.colorMode;+ }++ get previewPalette() {+ const pair = this.selectedPair;+ if (!pair) {+ return;+ }+ return this.effectiveColorMode === "dark"+ ? (pair.dark ?? pair.light)+ : (pair.light ?? pair.dark);+ }++ selectTheme(themeId) {+ if (themeId === this.themeId) {+ return;+ }++ this.themeId = themeId;+ this.#persistState();++ // a different theme is a different asset build, so previewing it means+ // reloading the page; state is restored from the store afterwards+ this.#navigateToThemePreview(themeId);+ }++ async selectPair(pairKey) {+ this.selectedPairKeys = new Map(this.selectedPairKeys).set(+ this.themeId,+ pairKey+ );+ this.#persistState();+ await this.#previewSelections();+ }++ async selectColorMode(mode) {+ this.colorMode = mode;+ this.#persistState();+ await this.#previewSelections();+ }++ toggleUserSelectable() {+ this.palettesUserSelectable = !this.palettesUserSelectable;+ this.#persistState();+ }++ setStepIndex(stepIndex) {+ this.stepIndex = stepIndex;+ this.#persistState();+ }++ selectBodyFont(fontKey) {+ this.bodyFont = fontKey;+ this.#persistState();+ applyPreviewFonts(document, {+ bodyFont: this.bodyFont,+ headingFont: this.headingFont,+ });+ }++ selectHeadingFont(fontKey) {+ this.headingFont = fontKey;+ this.#persistState();+ applyPreviewFonts(document, {+ bodyFont: this.bodyFont,+ headingFont: this.headingFont,+ });+ }++ selectHomepage(homepage) {+ this.homepage = homepage;+ if (homepage === "categories") {+ this.categoryPageStyle = "categories_boxes";+ this.siteSettings.desktop_category_page_style = this.categoryPageStyle;+ }+ this.#persistState();++ // the page behind the sheet is the preview: show the chosen homepage.+ // Explicit routes, because "/" resolves to the currently saved default+ // homepage, and a router transition (unlike DiscourseURL.routeTo) can+ // never escalate to a full page load, which would dismiss the sheet+ this.router.transitionTo(`discovery.${homepage}`);+ }++ selectCategoryPageStyle(value) {+ this.categoryPageStyle = value;+ this.#persistState();++ // the client copy of the setting drives how the categories page renders,+ // so mutating it and re-rendering previews the style live+ this.siteSettings.desktop_category_page_style = value;+ this.#refreshCategoriesPage();+ }++ stop() {+ this.active = false;+ this.#onComplete = undefined;+ this.keyValueStore.remove(STATE_KEY);+ clearPreview(document);++ if (this.#originalCategoryPageStyle) {+ this.siteSettings.desktop_category_page_style =+ this.#originalCategoryPageStyle;+ this.#refreshCategoriesPage();+ }+ restoreColorSchemeLinks(this.#originalColorSchemeLinks);++ if (this.#currentPreviewThemeId !== null) {+ window.location.assign(getURL("/"));+ }+ }++ async save() {+ this.saving = true;++ try {+ await ajax("/admin/config/design-wizard.json", {+ type: "PUT",+ data: this.#selectionsPayload,+ });++ this.keyValueStore.remove(STATE_KEY);+ setLocalTheme([], 0);++ if (this.#onComplete) {+ await this.#onComplete();+ } else {+ await this.#completeStepWithoutCaller();+ }++ window.location.assign(getURL("/"));+ } catch (error) {+ this.saving = false;+ popupAjaxError(error);+ }+ }++ // persists the selections made so far without finishing the wizard, so+ // closing mid-flow only discards the step being worked on+ async saveProgress() {+ this.saving = true;++ try {+ await ajax("/admin/config/design-wizard.json", {+ type: "PUT",+ data: this.#selectionsPayload,+ });++ // saving recompiles stylesheets and the live reloader swaps them in,+ // which can momentarily replace the previewed palette with the saved+ // theme's default; re-assert the preview now and once more after the+ // late-arriving swap+ await this.#previewSelections();+ if (!isTesting()) {+ discourseLater(() => {+ if (this.active) {+ this.#previewSelections();+ }+ }, 1000);+ }+ return true;+ } catch (error) {+ popupAjaxError(error);+ return false;+ } finally {+ this.saving = false;+ }+ }++ // the durable half of the step's own markAsCompleted, for when the caller is+ // gone; awaited so the reload can't cancel the audit write in flight+ async #completeStepWithoutCaller() {+ const alreadyCompleted = !!this.keyValueStore.get(STEP_COMPLETED_KEY);+ this.keyValueStore.set({ key: STEP_COMPLETED_KEY, value: true });++ if (!alreadyCompleted) {+ await logOnboardingEvent("step_completed", SELECT_THEME_STEP);+ }+ }++ get #selectionsPayload() {+ return {+ theme_id: this.themeId,+ light_palette_id: this.selectedPair?.light?.id,+ dark_palette_id: this.selectedPair?.dark?.id,+ palettes_user_selectable: this.palettesUserSelectable,+ base_font: this.bodyFont,+ heading_font: this.headingFont,+ homepage: this.homepage,+ category_page_style:+ this.homepage === "categories" ? this.categoryPageStyle : null,+ };+ }++ get #storedState() {+ const raw = this.keyValueStore.get(STATE_KEY);+ if (!raw) {+ return;+ }++ try {+ return JSON.parse(raw);+ } catch {+ this.keyValueStore.remove(STATE_KEY);+ }+ }++ get #currentPreviewThemeId() {+ return new URLSearchParams(window.location.search).get("preview_theme_id");+ }++ #initFromData() {+ // a custom default theme isn't offered by the wizard, so nothing is+ // preselected and the page keeps rendering it until a theme is chosen+ const preselectedTheme =+ this.data.themes.find((theme) => theme.default) ??+ (this.data.current_theme+ ? null+ : this.data.themes.find((theme) => theme.id === HORIZON_THEME_ID));+ this.themeId = preselectedTheme?.id ?? null;+ this.selectedPairKeys = new Map(+ this.data.themes.map((theme) => [theme.id, this.#currentPairKey(theme)])+ );+ this.palettesUserSelectable = this.data.palettes_user_selectable;+ this.bodyFont = this.data.base_font;+ this.headingFont = this.data.heading_font;+ this.colorMode = renderedColorMode();+ this.homepage = this.#supportedHomepage(this.data.homepage);+ this.categoryPageStyle = this.siteSettings.desktop_category_page_style;+ this.stepIndex = 0;+ }++ #restore(stored) {+ this.themeId = stored.themeId;+ this.selectedPairKeys = new Map(stored.selectedPairKeys);+ this.colorMode = stored.colorMode ?? renderedColorMode();+ this.palettesUserSelectable = stored.palettesUserSelectable;+ this.bodyFont = stored.bodyFont;+ this.headingFont = stored.headingFont;+ this.homepage =+ stored.homepage ?? this.#supportedHomepage(this.data.homepage);+ this.categoryPageStyle =+ stored.categoryPageStyle ?? this.siteSettings.desktop_category_page_style;+ // selections are restored but the flow always restarts from the first+ // step, so a resumed wizard walks the same path as a fresh one+ this.stepIndex = 0;+ }++ #persistState() {+ this.keyValueStore.set({+ key: STATE_KEY,+ value: JSON.stringify({+ themeId: this.themeId,+ selectedPairKeys: [...this.selectedPairKeys.entries()],+ colorMode: this.colorMode,+ palettesUserSelectable: this.palettesUserSelectable,+ bodyFont: this.bodyFont,+ headingFont: this.headingFont,+ homepage: this.homepage,+ categoryPageStyle: this.categoryPageStyle,+ }),+ });+ }++ #refreshCategoriesPage() {+ if (this.router.currentRouteName?.startsWith("discovery.categories")) {+ this.router.refresh();+ }+ }++ #navigateToThemePreview(themeId) {+ window.location.assign(+ getURL(`/?preview_theme_id=${encodeURIComponent(themeId)}`)+ );+ }++ #supportedHomepage(homepage) {+ return ["latest", "new", "hot", "categories"].includes(homepage)+ ? homepage+ : "latest";+ }++ #currentPairKey(theme) {+ const pair = theme.palette_pairs.find(+ (candidate) =>+ (theme.color_scheme_id &&+ candidate.light?.id === theme.color_scheme_id) ||+ (theme.dark_color_scheme_id &&+ candidate.dark?.id === theme.dark_color_scheme_id)+ );+ return (pair ?? theme.palette_pairs[0])?.key;+ }++ async #previewSelections() {+ applyPreviewFonts(document, {+ bodyFont: this.bodyFont,+ headingFont: this.headingFont,+ });++ const mode = this.effectiveColorMode;+ const paletteId = this.previewPalette?.id;+ if (paletteId) {+ try {+ await applyColorScheme(+ { id: paletteId },+ { replace: true, themeId: this.themeId, mode }+ );+ } catch {+ // the manager already reports failures; a failed preview should not+ // break the wizard+ }+ }++ showColorMode(mode);+ }+}diff --git a/frontend/discourse/app/templates/application.gjs b/frontend/discourse/app/templates/application.gjsindex d77457cbad3..063d42c38a6 100644--- a/frontend/discourse/app/templates/application.gjs+++ b/frontend/discourse/app/templates/application.gjs@@ -8,6 +8,7 @@ import ComposerContainer from "discourse/components/composer-container";import DDocument from "discourse/components/d-document";import DStyles from "discourse/components/d-styles";import DVirtualHeight from "discourse/components/d-virtual-height";+import DesignWizardPanel from "discourse/components/design-wizard-panel";import DiscourseRoot from "discourse/components/discourse-root";import FooterNav from "discourse/components/footer-nav";import GlimmerSiteHeader from "discourse/components/glimmer-site-header";@@ -174,6 +175,7 @@ export default <template>/><ModalContainer />+ <DesignWizardPanel /><DialogHolder /><ComposerContainer /><RenderGlimmerContainer />diff --git a/frontend/discourse/tests/acceptance/admin-onboarding-banner-test.gjs b/frontend/discourse/tests/acceptance/admin-onboarding-banner-test.gjsindex 4d4fc909fde..4745ce7d36c 100644--- a/frontend/discourse/tests/acceptance/admin-onboarding-banner-test.gjs+++ b/frontend/discourse/tests/acceptance/admin-onboarding-banner-test.gjs@@ -5,8 +5,110 @@ import { test } from "qunit";import StartPostingOption from "discourse/components/admin-onboarding/start-posting-option";import { AUTO_GROUPS } from "discourse/lib/constants";import { withPluginApi } from "discourse/lib/plugin-api";+import pretender, { response } from "discourse/tests/helpers/create-pretender";import { acceptance } from "discourse/tests/helpers/qunit-helpers";+const designWizardData = () => ({+ themes: [+ {+ id: -1,+ name: "Foundation",+ default: true,+ color_scheme_id: null,+ dark_color_scheme_id: null,+ screenshot_light_url: null,+ screenshot_dark_url: null,+ palette_pairs: [+ {+ key: "default",+ name: "Default",+ dark_only: false,+ light: {+ id: -1,+ name: "Light",+ colors: {+ primary: "222222",+ secondary: "ffffff",+ tertiary: "0088cc",+ },+ },+ dark: {+ id: -2,+ name: "Dark",+ colors: {+ primary: "dddddd",+ secondary: "222222",+ tertiary: "099dd7",+ },+ },+ },+ ],+ },+ {+ id: -2,+ name: "Horizon",+ default: false,+ color_scheme_id: 23,+ dark_color_scheme_id: 24,+ screenshot_light_url: null,+ screenshot_dark_url: null,+ palette_pairs: [+ {+ key: "horizon",+ name: "Horizon",+ dark_only: false,+ light: {+ id: 23,+ name: "Horizon",+ colors: {+ primary: "222222",+ secondary: "ffffff",+ tertiary: "563fe3",+ },+ },+ dark: {+ id: 24,+ name: "Horizon Dark",+ colors: {+ primary: "e7e5f2",+ secondary: "1b1533",+ tertiary: "7965f0",+ },+ },+ },+ {+ key: "marigold",+ name: "Marigold",+ dark_only: false,+ light: {+ id: 25,+ name: "Marigold",+ colors: {+ primary: "222222",+ secondary: "ffffff",+ tertiary: "b78d12",+ },+ },+ dark: {+ id: 26,+ name: "Marigold Dark",+ colors: {+ primary: "efe7d4",+ secondary: "201808",+ tertiary: "d9a616",+ },+ },+ },+ ],+ },+ ],+ current_theme: null,+ base_font: "inter",+ heading_font: "inter",+ homepage: "latest",+ palettes_user_selectable: false,+});+const withStep = (id, assert) => {return {checkbox() {@@ -16,11 +118,11 @@ const withStep = (id, assert) => {return click(`div#${id} .onboarding-step__action .btn`);},isChecked() {- return this.checkbox().hasClass("checked", `${id} step is completed`);+ return this.checkbox().hasClass("--completed", `${id} step is completed`);},isNotChecked() {return this.checkbox().doesNotHaveClass(- "checked",+ "--completed",`${id} step is not completed`);},@@ -42,7 +144,26 @@ acceptance("Admin - Onboarding Banner", function (needs) {default_composer_category: 1,});- needs.hooks.beforeEach(() => (loggedEvents = []));+ needs.hooks.beforeEach(function () {+ loggedEvents = [];+ this.schemeLinks = [];++ // registered so afterEach tears them down even when an assertion throws+ this.addSchemeLink = (className, href, media) => {+ const element = document.createElement("link");+ element.rel = "stylesheet";+ element.className = className;+ element.href = href;+ element.media = media;+ document.head.prepend(element);+ this.schemeLinks.push(element);+ return element;+ };+ });++ needs.hooks.afterEach(function () {+ this.schemeLinks.forEach((link) => link.remove());+ });needs.pretender((server, helper) => {server.put("/admin/site_settings/enable_site_owner_onboarding", () => {@@ -62,33 +183,27 @@ acceptance("Admin - Onboarding Banner", function (needs) {});});- server.get("/admin/themes.json", () => {- return helper.response(200, {- themes: [- {- id: -1,- name: "Foundation",- default: true,- screenshot_light_url: null,- screenshot_dark_url: null,- },- {- id: -2,- name: "Horizon",- default: false,- screenshot_light_url: null,- screenshot_dark_url: null,- },- ],- extras: { color_schemes: [] },- });- });+ server.put("/admin/config/design-wizard.json", () =>+ helper.response(200, { success: "OK" })+ );- server.put("/admin/themes/-2.json", () => {- return helper.response(200, {- theme: { id: -2, name: "Horizon", default: true },- });- });+ server.get("/color-scheme-stylesheet/:id", () =>+ helper.response(200, {+ color_scheme_id: -1,+ new_href: "/stylesheets/color_definitions_preview.css",+ })+ );++ server.get("/color-scheme-stylesheet/:id/:themeId", () =>+ helper.response(200, {+ color_scheme_id: -1,+ new_href: "/stylesheets/color_definitions_preview.css",+ })+ );++ server.get("/admin/config/design-wizard.json", () =>+ helper.response(200, designWizardData())+ );});test("it shows onboarding banner", async function (assert) {@@ -96,6 +211,31 @@ acceptance("Admin - Onboarding Banner", function (needs) {assert.dom(".admin-onboarding-banner").exists("shows onboarding banner");});+ test("the header controls have accessible labels", async function (assert) {+ await visit("/");++ assert+ .dom(".admin-onboarding-banner .btn-minimize")+ .hasAttribute(+ "aria-label",+ "Collapse setup steps",+ "labels the collapse action"+ );+ assert+ .dom(".admin-onboarding-banner .btn-close")+ .hasAttribute("aria-label", "Dismiss setup", "labels the dismiss action");++ await click(".admin-onboarding-banner .btn-minimize");++ assert+ .dom(".admin-onboarding-banner .btn-minimize")+ .hasAttribute(+ "aria-label",+ "Expand setup steps",+ "updates the label for the expand action"+ );+ });+test("it can end onboarding prematurely", async function (assert) {await visit("/");assert.dom(".admin-onboarding-banner").exists();@@ -244,7 +384,7 @@ acceptance("Admin - Onboarding Banner", function (needs) {);});- test("it can open `select_theme` step", async function (assert) {+ test("it can walk the design wizard from the `select_theme` step", async function (assert) {const step = withStep("select_theme", assert);await visit("/");@@ -253,10 +393,183 @@ acceptance("Admin - Onboarding Banner", function (needs) {await step.clickAction();await settled();- assert.dom(".theme-picker-modal").exists("theme picker modal is shown");assert- .dom(".theme-picker-modal__card")- .exists({ count: 2 }, "shows Foundation and Horizon");+ .dom(".design-wizard")+ .exists("the design wizard slides in as a sheet");+ assert+ .dom(".design-wizard__theme-card")+ .exists({ count: 2 }, "the theme step shows Foundation and Horizon");+ assert+ .dom(".design-wizard__theme-card.--selected")+ .hasAttribute("data-theme-id", "-1", "preselects the default theme");+ assert+ .dom(".design-wizard__back")+ .isDisabled("cannot go back from the first step");++ await click(".design-wizard__next");+ assert+ .dom(".design-wizard__theme-card")+ .doesNotExist("theme cards are left behind on the colors step");+ assert+ .dom(".design-wizard__swatch")+ .exists({ count: 1 }, "the colors step shows the theme's palette pairs");++ await click(".design-wizard__swatch[data-pair-key='default']");+ assert+ .dom("link[data-scheme-id]", document.documentElement)+ .exists("the page's color scheme stylesheet is swapped for the preview");++ assert+ .dom(".design-wizard__font-select")+ .exists({ count: 2 }, "the colors step offers the font dropdowns");++ await click(".design-wizard__next");+ assert+ .dom(".design-wizard__homepage-card")+ .exists({ count: 2 }, "the homepage step offers topics and categories");+ assert+ .dom(".design-wizard__homepage-card.--selected")+ .hasAttribute("data-homepage", "topics", "defaults to a topics homepage");+ assert+ .dom(".design-wizard__topic-page-option")+ .exists({ count: 3 }, "a topics homepage offers the topic page types");+ assert+ .dom(".design-wizard__topic-page-option.--selected")+ .hasAttribute("data-topic-page", "latest", "defaults to latest");++ await click(".design-wizard__homepage-card[data-homepage='categories']");+ assert+ .dom(".design-wizard__style-block")+ .exists({ count: 3 }, "a categories homepage offers the page styles");+ assert+ .dom(".design-wizard__style-block.--selected")+ .hasAttribute(+ "data-style",+ "categories_boxes",+ "defaults to boxes with subcategories"+ );+ assert+ .dom(".design-wizard__topic-page-option")+ .doesNotExist("the topic page types are hidden for categories");++ assert.dom(".design-wizard__next").doesNotExist("no next on the last step");+ assert.dom(".design-wizard__save").exists("the last step offers save");++ await click(".design-wizard__back");+ assert+ .dom(".design-wizard__swatch")+ .exists({ count: 1 }, "back returns to the colors step");++ await click(".design-wizard__close");+ assert.dom(".design-wizard").doesNotExist("closing removes the sheet");+ assert+ .dom("link[data-scheme-id]", document.documentElement)+ .doesNotExist("the palette preview is reverted");++ // previewing a categories homepage routed away from the banner's page+ await visit("/");+ step.isNotChecked();+ });++ test("the design wizard activates the stylesheet for the selected color mode", async function (assert) {+ const darkLink = this.addSchemeLink(+ "dark-scheme",+ "data:text/css,design-wizard-dark",+ "none"+ );+ const lightLink = this.addSchemeLink(+ "light-scheme",+ "data:text/css,design-wizard-light",+ "all"+ );++ await visit("/");+ await withStep("select_theme", assert).clickAction();+ await click(".design-wizard__next");+ await click(".design-wizard__color-mode:not(.--active)");++ assert+ .dom(lightLink)+ .hasAttribute("media", "none", "deactivates the light stylesheet");+ assert+ .dom(darkLink)+ .hasAttribute("media", "all", "activates the dark stylesheet");++ await click(".design-wizard__close");+ assert+ .dom(lightLink)+ .hasAttribute(+ "href",+ "data:text/css,design-wizard-light",+ "restores the original light stylesheet"+ )+ .hasAttribute("media", "all", "reactivates the light stylesheet");+ assert+ .dom(darkLink)+ .hasAttribute(+ "href",+ "data:text/css,design-wizard-dark",+ "restores the original dark stylesheet"+ )+ .hasAttribute("media", "none", "deactivates the dark stylesheet");+ });++ test("the design wizard keeps a custom default theme until another theme is chosen", async function (assert) {+ const data = designWizardData();+ data.themes.forEach((theme) => (theme.default = false));+ data.current_theme = { id: 42, name: "Air" };+ pretender.get("/admin/config/design-wizard.json", () => response(data));++ await visit("/");+ await withStep("select_theme", assert).clickAction();+ await settled();++ assert+ .dom(".design-wizard")+ .exists("the wizard opens without reloading into a theme preview");+ assert+ .dom(".design-wizard__theme-card.--selected")+ .doesNotExist("no theme is preselected");+ assert+ .dom(".design-wizard__custom-theme-notice")+ .includesText("Air", "the notice names the current custom theme");+ assert+ .dom(".design-wizard__next")+ .isDisabled("cannot continue until a theme is chosen");++ await click(".design-wizard__close");+ assert+ .dom("link[data-scheme-id]", document.documentElement)+ .doesNotExist("closing leaves the current theme's palette untouched");+ });++ test("the design wizard stays on the step when saving progress fails", async function (assert) {+ pretender.put("/admin/config/design-wizard.json", () =>+ response(422, { errors: ["Something went wrong"] })+ );++ await visit("/");+ await withStep("select_theme", assert).clickAction();++ assert+ .dom(".design-wizard__theme-card")+ .exists({ count: 2 }, "starts on the theme step");++ await click(".design-wizard__next");++ assert+ .dom(".design-wizard__theme-card")+ .exists({ count: 2 }, "a failed progress save does not advance the step");+ assert+ .dom(".design-wizard__swatch")+ .doesNotExist("the colors step is not reached");+ assert+ .dom(".design-wizard__next")+ .isNotDisabled("the next button is usable again after the failure");++ await click(".dialog-footer .btn-primary");+ // close the sheet so the palette preview does not leak into other tests+ await click(".design-wizard__close");});});diff --git a/frontend/discourse/tests/integration/components/design-wizard-sections-test.gjs b/frontend/discourse/tests/integration/components/design-wizard-sections-test.gjsnew file mode 100644index 00000000000..89be042faa7--- /dev/null+++ b/frontend/discourse/tests/integration/components/design-wizard-sections-test.gjs@@ -0,0 +1,211 @@+import { tracked } from "@glimmer/tracking";+import { click, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import ColorsSection from "discourse/components/design-wizard/colors-section";+import HomepageSection from "discourse/components/design-wizard/homepage-section";+import ThemeSection from "discourse/components/design-wizard/theme-section";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++const SCREENSHOT = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";++const noop = () => {};++const PAIRS = [+ {+ key: "default",+ name: "Default",+ dark_only: false,+ light: { colors: { secondary: "ffffff", tertiary: "0088cc" } },+ },+ {+ key: "alternate",+ name: "Alternate",+ dark_only: false,+ light: { colors: { secondary: "eeeeee", tertiary: "ff0000" } },+ },+];++module(+ "Integration | Component | DesignWizard | ThemeSection",+ function (hooks) {+ setupRenderingTest(hooks);++ test("theme choices are native radios", async function (assert) {+ const themes = [+ {+ id: -1,+ name: "Foundation",+ screenshot_light_url: SCREENSHOT,+ screenshot_dark_url: SCREENSHOT,+ },+ {+ id: -2,+ name: "Horizon",+ screenshot_light_url: null,+ screenshot_dark_url: null,+ },+ ];++ await render(+ <template>+ <ThemeSection+ @themes={{themes}}+ @selectedThemeId={{-1}}+ @onSelect={{noop}}+ />+ </template>+ );++ assert+ .dom(+ ".design-wizard__theme-card input[type='radio'][name='design-wizard-theme']"+ )+ .exists({ count: 2 }, "renders one native radio per theme");+ assert+ .dom(+ ".design-wizard__theme-card[data-theme-id='-1'] input[type='radio']"+ )+ .isChecked("checks the selected theme");+ assert+ .dom(+ ".design-wizard__theme-card[data-theme-id='-2'] input[type='radio']"+ )+ .isNotChecked("leaves the other theme unchecked");+ });+ }+);++module(+ "Integration | Component | DesignWizard | ColorsSection",+ function (hooks) {+ setupRenderingTest(hooks);++ test("color controls expose their selected state and switch labels", async function (assert) {+ await render(+ <template>+ <ColorsSection+ @pairs={{PAIRS}}+ @selectedPairKey="default"+ @selectedPairName="Default"+ @colorMode="light"+ @darkOnly={{false}}+ @userSelectable={{false}}+ @onSelectMode={{noop}}+ @onSelectPair={{noop}}+ @onToggleUserSelectable={{noop}}+ />+ </template>+ );++ assert+ .dom(".design-wizard__color-mode.--active")+ .hasAria("pressed", "true", "exposes the selected color mode");+ assert+ .dom(".design-wizard__swatch[data-pair-key='default']")+ .hasAria("pressed", "true", "exposes the selected palette");+ assert+ .dom(".design-wizard__swatch[data-pair-key='alternate']")+ .hasAria("pressed", "false", "exposes the unselected palette");+ assert+ .dom(".design-wizard__user-selectable [role='switch']")+ .hasAria("checked", "false", "exposes the switch state")+ .hasAria(+ "labelledby",+ "design-wizard-user-selectable-title",+ "associates the switch title"+ )+ .hasAria(+ "describedby",+ "design-wizard-user-selectable-description",+ "associates the switch description"+ );+ });++ test("the user selectable switch reflects and toggles its state", async function (assert) {+ const state = new (class {+ @tracked userSelectable = false;+ })();+ const toggle = () => (state.userSelectable = !state.userSelectable);++ await render(+ <template>+ <ColorsSection+ @pairs={{PAIRS}}+ @selectedPairKey="default"+ @selectedPairName="Default"+ @colorMode="light"+ @darkOnly={{false}}+ @userSelectable={{state.userSelectable}}+ @onSelectMode={{noop}}+ @onSelectPair={{noop}}+ @onToggleUserSelectable={{toggle}}+ />+ </template>+ );++ const SWITCH = ".design-wizard__user-selectable [role='switch']";+ assert.dom(SWITCH).hasAria("checked", "false", "starts off");++ await click(SWITCH);+ assert.true(+ state.userSelectable,+ "clicking the switch notifies the caller"+ );+ assert.dom(SWITCH).hasAria("checked", "true", "renders the new state");++ await click(SWITCH);+ assert.false(state.userSelectable, "clicking again toggles back off");+ assert+ .dom(SWITCH)+ .hasAria("checked", "false", "renders the reverted state");+ });+ }+);++module(+ "Integration | Component | DesignWizard | HomepageSection",+ function (hooks) {+ setupRenderingTest(hooks);++ test("homepage controls expose their selected state", async function (assert) {+ const state = new (class {+ @tracked homepage = "latest";+ })();++ await render(+ <template>+ <HomepageSection+ @themeId={{-1}}+ @homepage={{state.homepage}}+ @categoryPageStyle="categories_boxes"+ @onSelectHomepage={{noop}}+ @onSelectCategoryPageStyle={{noop}}+ />+ </template>+ );++ assert+ .dom(".design-wizard__homepage-card[data-homepage='topics']")+ .hasAria("pressed", "true", "exposes the selected homepage type");+ assert+ .dom(".design-wizard__topic-page-option[data-topic-page='latest']")+ .hasAria("pressed", "true", "exposes the selected topic page");+ assert+ .dom(".design-wizard__topic-page-option[data-topic-page='new']")+ .hasAria("pressed", "false", "exposes an unselected topic page");++ state.homepage = "categories";+ await settled();++ assert+ .dom(".design-wizard__homepage-card[data-homepage='categories']")+ .hasAria("pressed", "true", "exposes the categories homepage");+ assert+ .dom(".design-wizard__style-block[data-style='categories_boxes']")+ .hasAria("pressed", "true", "exposes the selected category style");+ assert+ .dom(".design-wizard__topic-page-option")+ .doesNotExist("hides the topic page types for a categories homepage");+ });+ }+);diff --git a/frontend/discourse/tests/unit/admin/lib/color-scheme-manager-test.js b/frontend/discourse/tests/unit/admin/lib/color-scheme-manager-test.jsnew file mode 100644index 00000000000..262ee922424--- /dev/null+++ b/frontend/discourse/tests/unit/admin/lib/color-scheme-manager-test.js@@ -0,0 +1,124 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import {+ applyColorScheme,+ setDefaultColorScheme,+} from "discourse/admin/lib/color-scheme-manager";+import pretender, { response } from "discourse/tests/helpers/create-pretender";++const ORIGINAL_LIGHT_HREF = "data:text/css,original-light";+const ORIGINAL_DARK_HREF = "data:text/css,original-dark";++function stylesheetLink(className, href) {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.className = className;+ link.href = href;+ return link;+}++function previewResponse(request) {+ const [, id] = request.url.match(/color-scheme-stylesheet\/(-?\d+)/);+ return response({+ color_scheme_id: Number(id),+ new_href: `data:text/css,preview-${id}`,+ });+}++module("Unit | Admin | Lib | color-scheme-manager", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.lightLink = stylesheetLink("light-scheme", ORIGINAL_LIGHT_HREF);+ this.darkLink = stylesheetLink("dark-scheme", ORIGINAL_DARK_HREF);+ document.head.prepend(this.darkLink);+ document.head.prepend(this.lightLink);++ pretender.get("/color-scheme-stylesheet/:id", previewResponse);+ pretender.get("/color-scheme-stylesheet/:id/:themeId", previewResponse);+ });++ hooks.afterEach(function () {+ this.lightLink.remove();+ this.darkLink.remove();+ });++ test("applyColorScheme replaces the light stylesheet in light mode", async function (assert) {+ await applyColorScheme(+ { id: 41 },+ { replace: true, themeId: -1, mode: "light" }+ );++ assert+ .dom(this.lightLink)+ .hasAttribute(+ "href",+ "data:text/css,preview-41",+ "updates the light link"+ );+ assert+ .dom(this.darkLink)+ .hasAttribute(+ "href",+ ORIGINAL_DARK_HREF,+ "leaves the dark link unchanged"+ );+ });++ test("applyColorScheme replaces the dark stylesheet in dark mode", async function (assert) {+ await applyColorScheme(+ { id: 42 },+ { replace: true, themeId: -1, mode: "dark" }+ );++ assert+ .dom(this.darkLink)+ .hasAttribute(+ "href",+ "data:text/css,preview-42",+ "updates the dark link"+ );+ assert+ .dom(this.lightLink)+ .hasAttribute(+ "href",+ ORIGINAL_LIGHT_HREF,+ "leaves the light link unchanged"+ );+ });++ test("setDefaultColorScheme previews and saves the selected mode", async function (assert) {+ const updateCalls = [];+ const scheme = {+ id: 43,+ is_base: false,+ updateDefaultOnTheme(...args) {+ updateCalls.push(args);+ },+ };+ const defaultTheme = {+ color_scheme_id: 1,+ dark_color_scheme_id: 2,+ };++ await setDefaultColorScheme(scheme, defaultTheme, { mode: "dark" });++ assert+ .dom(this.darkLink)+ .hasAttribute(+ "href",+ "data:text/css,preview-43",+ "previews on the dark link"+ );+ assert.deepEqual(+ updateCalls,+ [["default_dark_on_theme", true]],+ "marks the scheme as the dark default"+ );+ assert.strictEqual(+ defaultTheme.dark_color_scheme_id,+ 43,+ "updates the theme's dark scheme"+ );+ });+});diff --git a/lib/design_wizard/palette_pairs.rb b/lib/design_wizard/palette_pairs.rbnew file mode 100644index 00000000000..f8af7d69bac--- /dev/null+++ b/lib/design_wizard/palette_pairs.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++module DesignWizard+ # Builds the light/dark palette pairs the design wizard offers for a theme.+ # Themes shipping their own palettes (e.g. Horizon) get those, paired by the+ # "<name>"/"<name> Dark" convention; other themes get a curated set of+ # built-in palettes, which only exist in memory (negative ids) until an+ # admin picks one and it is materialized as a via_wizard color scheme.+ class PalettePairs+ DARK_NAME_SUFFIX = " Dark"++ BUILT_IN_PAIRS = [+ { key: "default", light: "Light", dark: "Dark" },+ { key: "wcag", light: "WCAG", dark: "WCAG Dark" },+ { key: "solarized", light: "Solarized Light", dark: "Solarized Dark" },+ { key: "dracula", light: nil, dark: "Dracula" },+ ].freeze++ def self.for_theme(theme)+ owned = ColorScheme.includes(:color_scheme_colors).where(theme_id: theme.id).order(:id).to_a+ owned.present? ? new(theme).theme_pairs(owned) : new(theme).built_in_pairs+ end++ def initialize(theme)+ @theme = theme+ end++ def theme_pairs(schemes)+ schemes+ .group_by { |scheme| scheme.name.delete_suffix(DARK_NAME_SUFFIX) }+ .map do |base_name, members|+ light = members.find { |scheme| !scheme.name.end_with?(DARK_NAME_SUFFIX) }+ dark = members.find { |scheme| scheme.name.end_with?(DARK_NAME_SUFFIX) }++ pair(key: base_name.parameterize.underscore, name: base_name, light: light, dark: dark)+ end+ end++ def built_in_pairs+ BUILT_IN_PAIRS.map do |definition|+ pair(+ key: definition[:key],+ name: I18n.t("design_wizard.palette_pairs.#{definition[:key]}"),+ light: built_in_scheme(definition[:light]),+ dark: built_in_scheme(definition[:dark]),+ )+ end+ end++ private++ def pair(key:, name:, light:, dark:)+ {+ key: key,+ name: name,+ dark_only: light.nil?,+ light: serialize_scheme(light),+ dark: serialize_scheme(dark),+ }+ end++ def serialize_scheme(scheme)+ return if scheme.nil?++ { id: scheme.id, name: scheme.name, colors: ColorScheme.sort_colors(scheme.resolved_colors) }+ end++ def built_in_scheme(name)+ return if name.nil?++ base_scheme_id = ColorScheme::NAMES_TO_ID_MAP[name]+ ColorScheme.find_by(base_scheme_id: base_scheme_id, via_wizard: true) ||+ ColorScheme.base_color_schemes.find { |scheme| scheme.base_scheme_id == base_scheme_id }+ end+ end+enddiff --git a/spec/integrity/admin_onboarding_locale_spec.rb b/spec/integrity/admin_onboarding_locale_spec.rbnew file mode 100644index 00000000000..e7ab580fd4f--- /dev/null+++ b/spec/integrity/admin_onboarding_locale_spec.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++RSpec.describe "Admin onboarding banner locale keys" do+ # OnboardingStep#buttonLabel switches between `action` and `completed`, so a+ # step missing either one renders the raw key in the banner.+ let(:steps) do+ File+ .read("frontend/discourse/app/components/admin-onboarding/banner.gjs")+ .scan(/static name = "(\w+)"/)+ .flatten+ end++ let(:banner) do+ YAML.load_file("config/locales/client.en.yml").dig("en", "js", "admin_onboarding_banner")+ end++ it "finds the steps defined by the banner" do+ expect(steps).to include("select_theme")+ end++ it "defines title, description, action and completed for every step" do+ missing =+ steps.each_with_object({}) do |step, hash|+ absent = %w[title description action completed] - (banner[step]&.keys || [])+ hash[step] = absent if absent.present?+ end++ expect(missing).to eq({})+ end+enddiff --git a/spec/lib/design_wizard/palette_pairs_spec.rb b/spec/lib/design_wizard/palette_pairs_spec.rbnew file mode 100644index 00000000000..47946d9f0da--- /dev/null+++ b/spec/lib/design_wizard/palette_pairs_spec.rb@@ -0,0 +1,105 @@+# frozen_string_literal: true++RSpec.describe DesignWizard::PalettePairs do+ describe ".for_theme" do+ context "when the theme ships no palettes of its own" do+ fab!(:theme)++ it "offers the curated built-in pairs" do+ pairs = described_class.for_theme(theme)++ expect(pairs.map { |pair| pair[:key] }).to eq(%w[default wcag solarized dracula])+ end++ it "names the pairs from the design wizard translations" do+ pairs = described_class.for_theme(theme)++ expect(pairs.map { |pair| pair[:name] }).to eq(+ %w[default wcag solarized dracula].map do |key|+ I18n.t("design_wizard.palette_pairs.#{key}")+ end,+ )+ end++ it "serializes not-yet-materialized built-ins with their negative ids" do+ ColorScheme.where(via_wizard: true).destroy_all++ default_pair = described_class.for_theme(theme).find { |pair| pair[:key] == "default" }++ expect(default_pair[:light][:id]).to eq(ColorScheme::NAMES_TO_ID_MAP["Light"])+ expect(default_pair[:dark][:id]).to eq(ColorScheme::NAMES_TO_ID_MAP["Dark"])+ expect(default_pair[:light][:colors].keys).to include("primary", "secondary", "tertiary")+ end++ it "marks a pair without a light palette as dark only" do+ dracula = described_class.for_theme(theme).find { |pair| pair[:key] == "dracula" }++ expect(dracula[:dark_only]).to eq(true)+ expect(dracula[:light]).to be_nil+ expect(dracula[:dark]).to be_present+ end++ it "prefers an already materialized copy over the in-memory built-in" do+ ColorScheme.where(via_wizard: true).destroy_all+ materialized =+ ColorScheme.create_from_base(+ name: "Dracula",+ base_scheme_id: ColorScheme::NAMES_TO_ID_MAP["Dracula"],+ via_wizard: true,+ )++ dracula = described_class.for_theme(theme).find { |pair| pair[:key] == "dracula" }++ expect(dracula[:dark][:id]).to eq(materialized.id)+ end+ end++ context "when the theme ships its own palettes" do+ fab!(:theme)++ it "pairs them by the '<name>' / '<name> Dark' convention" do+ light = Fabricate(:color_scheme, name: "Royal", theme_id: theme.id)+ dark = Fabricate(:color_scheme, name: "Royal Dark", theme_id: theme.id)++ pairs = described_class.for_theme(theme)++ expect(pairs.size).to eq(1)+ expect(pairs.first).to include(key: "royal", name: "Royal", dark_only: false)+ expect(pairs.first[:light][:id]).to eq(light.id)+ expect(pairs.first[:dark][:id]).to eq(dark.id)+ end++ it "parameterizes multi-word names into keys" do+ Fabricate(:color_scheme, name: "Shades of Blue", theme_id: theme.id)++ expect(described_class.for_theme(theme).map { |pair| pair[:key] }).to eq(%w[shades_of_blue])+ end++ it "leaves a light palette without a dark sibling unpaired" do+ Fabricate(:color_scheme, name: "Clover", theme_id: theme.id)++ pair = described_class.for_theme(theme).first++ expect(pair).to include(key: "clover", dark_only: false)+ expect(pair[:light]).to be_present+ expect(pair[:dark]).to be_nil+ end++ it "treats a dark palette without a light sibling as dark only" do+ Fabricate(:color_scheme, name: "Midnight Dark", theme_id: theme.id)++ pair = described_class.for_theme(theme).first++ expect(pair).to include(key: "midnight", name: "Midnight", dark_only: true)+ expect(pair[:light]).to be_nil+ expect(pair[:dark]).to be_present+ end++ it "does not fall back to the built-in pairs" do+ Fabricate(:color_scheme, name: "Royal", theme_id: theme.id)++ expect(described_class.for_theme(theme).map { |pair| pair[:key] }).not_to include("wcag")+ end+ end+ end+enddiff --git a/spec/models/theme_spec.rb b/spec/models/theme_spec.rbindex cf99b16bcfc..3947cbe02d9 100644--- a/spec/models/theme_spec.rb+++ b/spec/models/theme_spec.rb@@ -663,6 +663,24 @@ RSpec.describe Theme doexpect(translations.map(&:value)).to contain_exactly("Description of my theme")end+ it "exposes the theme_metadata.description translation as the description" do+ expect(theme.description).to be_nil++ ThemeField.create!(+ theme_id: theme.id,+ name: "en",+ type_id: ThemeField.types[:yaml],+ target_id: Theme.targets[:translations],+ value: <<~YAML,+ en:+ theme_metadata:+ description: "Description of my theme"+ YAML+ )++ expect(Theme.find(theme.id).description).to eq("Description of my theme")+ end+it "can create a hash of overridden values" doen_translation =ThemeField.create!(diff --git a/spec/requests/admin/config/design_wizard_controller_spec.rb b/spec/requests/admin/config/design_wizard_controller_spec.rbnew file mode 100644index 00000000000..300ae87aabf--- /dev/null+++ b/spec/requests/admin/config/design_wizard_controller_spec.rb@@ -0,0 +1,225 @@+# frozen_string_literal: true++RSpec.describe Admin::Config::DesignWizardController do+ fab!(:admin)+ fab!(:moderator)+ fab!(:user)++ describe "#index" do+ context "when signed in as an admin" do+ before { sign_in(admin) }++ it "returns the core themes with their palette pairs" do+ ThemeField.create!(+ theme_id: Theme::CORE_THEMES["horizon"],+ name: "en",+ type_id: ThemeField.types[:yaml],+ target_id: Theme.targets[:translations],+ value: <<~YAML,+ en:+ theme_metadata:+ description: "A simple, beautiful theme"+ YAML+ )++ get "/admin/config/design-wizard.json"++ expect(response.status).to eq(200)++ themes = response.parsed_body["themes"]+ expect(themes.map { |theme| theme["id"] }).to contain_exactly(+ Theme::CORE_THEMES["foundation"],+ Theme::CORE_THEMES["horizon"],+ )++ horizon = themes.find { |theme| theme["id"] == Theme::CORE_THEMES["horizon"] }+ expect(horizon["description"]).to eq("A simple, beautiful theme")+ expect(horizon["palette_pairs"].map { |pair| pair["key"] }).to include(+ "horizon",+ "royal",+ "clover",+ "lily",+ "violet",+ "marigold",+ )+ horizon_pair = horizon["palette_pairs"].find { |pair| pair["key"] == "horizon" }+ expect(horizon_pair["light"]["colors"]).to include("primary", "secondary", "tertiary")+ expect(horizon_pair["dark"]["name"]).to eq("Horizon Dark")++ foundation = themes.find { |theme| theme["id"] == Theme::CORE_THEMES["foundation"] }+ expect(foundation["palette_pairs"].map { |pair| pair["key"] }).to eq(+ %w[default wcag solarized dracula],+ )+ dracula = foundation["palette_pairs"].find { |pair| pair["key"] == "dracula" }+ expect(dracula["dark_only"]).to eq(true)+ expect(dracula["light"]).to be_nil+ end++ it "returns the current fonts and homepage" do+ SiteSetting.base_font = "lato"+ SiteSetting.heading_font = "merriweather"+ SiteSetting.default_homepage = "categories"++ get "/admin/config/design-wizard.json"++ expect(response.parsed_body["base_font"]).to eq("lato")+ expect(response.parsed_body["heading_font"]).to eq("merriweather")+ expect(response.parsed_body["homepage"]).to eq("categories")+ end++ it "does not include current_theme when the default theme is a core theme" do+ get "/admin/config/design-wizard.json"++ expect(response.parsed_body["current_theme"]).to be_nil+ end++ it "includes current_theme when the default theme is a custom theme" do+ theme = Fabricate(:theme)+ theme.set_default!++ get "/admin/config/design-wizard.json"++ expect(response.parsed_body["current_theme"]).to include(+ "id" => theme.id,+ "name" => theme.name,+ )+ end++ it "reports palettes as not user selectable when only a custom default theme's palettes are selectable" do+ theme = Fabricate(:theme)+ Fabricate(:color_scheme, theme_id: theme.id, user_selectable: true)+ theme.set_default!++ get "/admin/config/design-wizard.json"++ expect(response.parsed_body["palettes_user_selectable"]).to eq(false)+ end++ it "reports palettes as not user selectable when there are none to offer" do+ ColorScheme.where(theme_id: Theme::CORE_THEMES.values).destroy_all+ ColorScheme.where(via_wizard: true).destroy_all++ get "/admin/config/design-wizard.json"++ expect(response.parsed_body["palettes_user_selectable"]).to eq(false)+ end++ it "reports palettes as user selectable when horizon's palettes are selectable and the default theme is custom" do+ ColorScheme.where(theme_id: Theme::CORE_THEMES["horizon"]).update_all(user_selectable: true)+ theme = Fabricate(:theme)+ Fabricate(:color_scheme, theme_id: theme.id, user_selectable: false)+ theme.set_default!++ get "/admin/config/design-wizard.json"++ expect(response.parsed_body["palettes_user_selectable"]).to eq(true)+ end+ end++ it "is not accessible to moderators" do+ sign_in(moderator)++ get "/admin/config/design-wizard.json"++ expect(response.status).to eq(403)+ end++ it "is not accessible to regular users" do+ sign_in(user)++ get "/admin/config/design-wizard.json"++ expect(response.status).to eq(404)+ end++ it "is not accessible to anonymous users" do+ get "/admin/config/design-wizard.json"++ expect(response.status).to eq(404)+ end+ end++ describe "#update" do+ context "when signed in as an admin" do+ before { sign_in(admin) }++ it "applies the design choices" do+ horizon = Theme.horizon_theme+ light = ColorScheme.find_by(theme_id: horizon.id, name: "Royal")+ dark = ColorScheme.find_by(theme_id: horizon.id, name: "Royal Dark")++ put "/admin/config/design-wizard.json",+ params: {+ theme_id: horizon.id,+ light_palette_id: light.id,+ dark_palette_id: dark.id,+ palettes_user_selectable: true,+ base_font: "lato",+ heading_font: "merriweather",+ homepage: "categories",+ category_page_style: "categories_boxes",+ }++ expect(response.status).to eq(200)+ expect(SiteSetting.default_theme_id).to eq(horizon.id)+ expect(horizon.reload.color_scheme_id).to eq(light.id)+ expect(horizon.dark_color_scheme_id).to eq(dark.id)+ expect(SiteSetting.base_font).to eq("lato")+ expect(SiteSetting.heading_font).to eq("merriweather")+ expect(SiteSetting.default_homepage).to eq("categories")+ expect(SiteSetting.desktop_category_page_style).to eq("categories_boxes")+ expect(light.reload.user_selectable).to eq(true)+ end++ it "returns a 400 with errors for an invalid contract" do+ put "/admin/config/design-wizard.json",+ params: {+ theme_id: Theme::CORE_THEMES["foundation"],+ base_font: "not_a_font",+ }++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "returns a 422 when a palette is not available for the theme" do+ horizon_palette = ColorScheme.find_by(theme_id: Theme::CORE_THEMES["horizon"])++ put "/admin/config/design-wizard.json",+ params: {+ theme_id: Theme::CORE_THEMES["foundation"],+ light_palette_id: horizon_palette.id,+ }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "returns a 422 when the site settings cannot be updated" do+ SiteSetting.stubs(:shadowed_settings).returns(Set.new(%i[default_theme_id]))++ put "/admin/config/design-wizard.json", params: { theme_id: Theme::CORE_THEMES["horizon"] }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to eq(+ [I18n.t("design_wizard.errors.site_settings_update_failed")],+ )+ end+ end++ it "is not accessible to moderators" do+ sign_in(moderator)++ put "/admin/config/design-wizard.json", params: { theme_id: Theme::CORE_THEMES["horizon"] }++ expect(response.status).to eq(403)+ expect(SiteSetting.default_theme_id).not_to eq(Theme::CORE_THEMES["horizon"])+ end++ it "is not accessible to anonymous users" do+ put "/admin/config/design-wizard.json", params: { theme_id: Theme::CORE_THEMES["foundation"] }++ expect(response.status).to eq(404)+ end+ end+enddiff --git a/spec/requests/stylesheets_controller_spec.rb b/spec/requests/stylesheets_controller_spec.rbindex dd21ee822ce..e39d2f57577 100644--- a/spec/requests/stylesheets_controller_spec.rb+++ b/spec/requests/stylesheets_controller_spec.rb@@ -220,6 +220,19 @@ RSpec.describe StylesheetsController doexpect(json["color_scheme_id"]).not_to eq(scheme.id)end+ it "uses a non-user-selectable theme_id for staff, like theme previews do" do+ scheme = ColorScheme.create_from_base(name: "hidden scheme", colors: [])+ non_selectable_theme = Fabricate(:theme, user_selectable: false, color_scheme_id: scheme.id)+ admin = Fabricate(:admin)+ sign_in(admin)++ get "/color-scheme-stylesheet/-1/#{non_selectable_theme.id}.json"++ expect(response.status).to eq(200)+ json = JSON.parse(response.body)+ expect(json["color_scheme_id"]).to eq(scheme.id)+ end+it "works as expected" doscheme = ColorScheme.lastget "/color-scheme-stylesheet/#{scheme.id}.json"diff --git a/spec/services/design_wizard/action/resolve_palette_spec.rb b/spec/services/design_wizard/action/resolve_palette_spec.rbnew file mode 100644index 00000000000..55cd3f493c1--- /dev/null+++ b/spec/services/design_wizard/action/resolve_palette_spec.rb@@ -0,0 +1,85 @@+# frozen_string_literal: true++RSpec.describe DesignWizard::Action::ResolvePalette do+ subject(:result) { described_class.call(palette_id:) }++ context "when no palette is given" do+ let(:palette_id) { nil }++ it { is_expected.to be_nil }++ it "does not materialize anything" do+ expect { result }.not_to change { ColorScheme.count }+ end+ end++ context "when the palette id refers to an existing record" do+ fab!(:palette, :color_scheme)++ let(:palette_id) { palette.id }++ it { is_expected.to eq(palette) }+ end++ context "when the palette id refers to a record that no longer exists" do+ let(:palette_id) { 999_999 }++ it { is_expected.to be_nil }++ it "does not materialize anything" do+ expect { result }.not_to change { ColorScheme.count }+ end+ end++ context "when the palette id refers to a built-in palette" do+ let(:palette_id) { ColorScheme::NAMES_TO_ID_MAP["Dracula"] }++ before { ColorScheme.where(via_wizard: true).destroy_all }++ it "materializes a via_wizard copy named after the built-in palette" do+ expect { result }.to change { ColorScheme.where(via_wizard: true).count }.by(1)++ expect(result).to have_attributes(+ base_scheme_id: palette_id,+ via_wizard: true,+ name: I18n.t("color_schemes.dracula_theme_name"),+ )+ end++ it "reuses the materialized copy on subsequent calls" do+ first = result++ expect { expect(described_class.call(palette_id:)).to eq(first) }.not_to change {+ ColorScheme.where(via_wizard: true).count+ }+ end++ it "copies the built-in colors" do+ expect(result.colors.map(&:name)).to include("primary", "secondary", "tertiary")+ end+ end++ describe "every built-in palette the wizard can offer" do+ let(:palette_id) { nil }++ it "has a translated name" do+ names =+ DesignWizard::PalettePairs::BUILT_IN_PAIRS.flat_map { |pair| pair.values_at(:light, :dark) }++ names.compact.each do |name|+ key = "color_schemes.#{name.downcase.tr(" ", "_")}_theme_name"+ expect(I18n.exists?(key)).to eq(true), "missing translation for #{key}"+ end+ end++ it "can be resolved" do+ DesignWizard::PalettePairs::BUILT_IN_PAIRS+ .flat_map { |pair| pair.values_at(:light, :dark) }+ .compact+ .each do |name|+ resolved = described_class.call(palette_id: ColorScheme::NAMES_TO_ID_MAP[name])+ expect(resolved).to be_present, "could not resolve #{name}"+ end+ end+ end+enddiff --git a/spec/services/design_wizard/action/update_palette_selectability_spec.rb b/spec/services/design_wizard/action/update_palette_selectability_spec.rbnew file mode 100644index 00000000000..80d59325562--- /dev/null+++ b/spec/services/design_wizard/action/update_palette_selectability_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++RSpec.describe DesignWizard::Action::UpdatePaletteSelectability do+ subject(:result) { described_class.call(theme:, selectable:) }++ fab!(:theme) { Theme.horizon_theme }++ let(:selectable) { true }++ context "when the theme ships its own palettes" do+ fab!(:theme_palette) { Fabricate(:color_scheme, theme_id: Theme::CORE_THEMES["horizon"]) }+ fab!(:wizard_palette) { Fabricate(:color_scheme, via_wizard: true, user_selectable: true) }++ it "offers the theme palettes" do+ result++ expect(theme_palette.reload.user_selectable).to eq(true)+ end++ it "revokes palettes that are no longer offered" do+ result++ expect(wizard_palette.reload.user_selectable).to eq(false)+ end++ context "without user selectable palettes" do+ let(:selectable) { false }++ it "revokes the theme palettes too" do+ result++ expect(theme_palette.reload.user_selectable).to eq(false)+ end+ end+ end++ context "when the theme ships no palettes of its own" do+ fab!(:theme) { Theme.foundation_theme }+ fab!(:wizard_palette) { Fabricate(:color_scheme, via_wizard: true) }++ before { ColorScheme.where(theme_id: Theme::CORE_THEMES["foundation"]).delete_all }++ it "falls back to offering the wizard palettes" do+ result++ expect(wizard_palette.reload.user_selectable).to eq(true)+ end+ end++ context "when a palette is unrelated to the wizard" do+ fab!(:unrelated_palette) { Fabricate(:color_scheme, user_selectable: true) }+ fab!(:theme_palette) { Fabricate(:color_scheme, theme_id: Theme::CORE_THEMES["horizon"]) }++ it "leaves it untouched" do+ expect { result }.not_to change { unrelated_palette.reload.user_selectable }+ end+ end+enddiff --git a/spec/services/design_wizard/apply_spec.rb b/spec/services/design_wizard/apply_spec.rbnew file mode 100644index 00000000000..1cfb6b9ab32--- /dev/null+++ b/spec/services/design_wizard/apply_spec.rb@@ -0,0 +1,328 @@+# frozen_string_literal: true++RSpec.describe DesignWizard::Apply do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:theme_id) }+ it { is_expected.to validate_inclusion_of(:theme_id).in_array(Theme::CORE_THEMES.values) }+ it do+ is_expected.to validate_inclusion_of(:base_font).in_array(+ BaseFontSetting.values.map { |font| font[:value] },+ ).allow_nil+ end+ it do+ is_expected.to validate_inclusion_of(:heading_font).in_array(+ BaseFontSetting.values.map { |font| font[:value] },+ ).allow_nil+ end+ it do+ is_expected.to validate_inclusion_of(:homepage).in_array(+ %w[latest new hot categories],+ ).allow_nil+ end+ it do+ is_expected.to validate_inclusion_of(:category_page_style).in_array(+ CategoryPageStyle.values.map { |style| style[:value] },+ ).allow_nil+ end++ it "normalizes the base light palette id to nil" do+ contract =+ described_class.new(+ theme_id: Theme::CORE_THEMES["foundation"],+ light_palette_id: DesignWizard::Apply::BASE_LIGHT_PALETTE_ID,+ )++ expect(contract).to be_valid+ expect(contract.light_palette_id).to be_nil+ end++ it "rejects negative palette ids that are not built-in palettes" do+ contract =+ described_class.new(theme_id: Theme::CORE_THEMES["foundation"], light_palette_id: -99)++ expect(contract).to be_invalid+ expect(contract.errors.of_kind?(:light_palette_id, :inclusion)).to eq(true)+ end++ it "accepts negative palette ids matching built-in palettes" do+ contract =+ described_class.new(+ theme_id: Theme::CORE_THEMES["foundation"],+ dark_palette_id: ColorScheme::NAMES_TO_ID_MAP["Dracula"],+ )++ expect(contract).to be_valid+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:foundation_theme) { Theme.foundation_theme }+ fab!(:horizon_theme) { Theme.horizon_theme }++ let(:guardian) { admin.guardian }+ let(:dependencies) { { guardian: } }+ let(:theme_id) { Theme::CORE_THEMES["foundation"] }+ let(:params) { { theme_id: } }++ context "when the contract isn't valid" do+ let(:params) { { theme_id:, base_font: "not_a_font" } }++ it { is_expected.to fail_a_contract }++ it "does not change the design state" do+ expect { result }.not_to change {+ [+ SiteSetting.default_theme_id,+ SiteSetting.base_font,+ ColorScheme.where(via_wizard: true).count,+ ]+ }+ end+ end++ context "when a palette id isn't a valid built-in palette" do+ let(:params) do+ { theme_id:, dark_palette_id: -99, palettes_user_selectable: true, base_font: "arial" }+ end++ it { is_expected.to fail_a_contract }++ it "does not materialize palettes or change the design state" do+ expect { result }.not_to change {+ [+ foundation_theme.reload.dark_color_scheme_id,+ SiteSetting.default_theme_id,+ SiteSetting.base_font,+ ColorScheme.where(via_wizard: true).count,+ ]+ }+ end+ end++ context "when the current user is not an admin" do+ fab!(:moderator)++ let(:guardian) { moderator.guardian }++ it { is_expected.to fail_a_policy(:current_user_is_admin) }+ end++ context "when the core theme row is missing from the database" do+ before { Theme.where(id: theme_id).delete_all }++ it { is_expected.to fail_to_find_a_model(:theme) }+ end++ context "when a provided palette belongs to another theme" do+ fab!(:horizon_palette) { Fabricate(:color_scheme, theme_id: Theme::CORE_THEMES["horizon"]) }++ let(:params) do+ {+ theme_id:,+ light_palette_id: horizon_palette.id,+ palettes_user_selectable: true,+ base_font: "arial",+ }+ end++ it { is_expected.to fail_a_policy(:palettes_available_to_theme) }++ it "does not resolve palettes or change the design state" do+ expect { result }.not_to change {+ [+ foundation_theme.reload.color_scheme_id,+ SiteSetting.default_theme_id,+ SiteSetting.base_font,+ ColorScheme.where(via_wizard: true).count,+ ]+ }+ end+ end++ context "when a provided palette does not exist" do+ let(:params) do+ { theme_id:, dark_palette_id: 999_999, palettes_user_selectable: true, base_font: "arial" }+ end++ it { is_expected.to fail_a_policy(:palettes_available_to_theme) }++ it "does not materialize palettes or change the design state" do+ expect { result }.not_to change {+ [+ foundation_theme.reload.dark_color_scheme_id,+ SiteSetting.default_theme_id,+ SiteSetting.base_font,+ ColorScheme.where(via_wizard: true).count,+ ]+ }+ end+ end++ context "when applying a theme with fonts, homepage and category page style" do+ let(:params) do+ {+ theme_id: Theme::CORE_THEMES["horizon"],+ base_font: "arial",+ heading_font: "oxanium",+ homepage: "categories",+ category_page_style: "categories_boxes",+ }+ end++ it { is_expected.to run_successfully }++ it "sets the default theme" do+ expect { result }.to change { SiteSetting.default_theme_id }.to(horizon_theme.id)+ end++ it "updates the font settings and logs the changes" do+ expect { result }.to change { SiteSetting.base_font }.to("arial").and change {+ SiteSetting.heading_font+ }.to("oxanium").and change {+ UserHistory.where(+ action: UserHistory.actions[:change_site_setting],+ subject: %w[base_font heading_font],+ ).count+ }.by(2)+ end++ it "updates the homepage and category page style" do+ expect { result }.to change { SiteSetting.default_homepage }.to("categories").and change {+ SiteSetting.desktop_category_page_style+ }.to("categories_boxes")+ end+ end++ context "when a site setting is shadowed by a global setting" do+ let(:params) { { theme_id: Theme::CORE_THEMES["horizon"], base_font: "arial" } }++ before { SiteSetting.stubs(:shadowed_settings).returns(Set.new(%i[default_theme_id])) }++ it { is_expected.to fail_a_step(:update_site_settings) }++ it "does not change any site setting" do+ expect { result }.not_to change { [SiteSetting.default_theme_id, SiteSetting.base_font] }+ end+ end++ context "when light and dark palettes are provided" do+ fab!(:light_scheme, :color_scheme)+ fab!(:dark_scheme, :color_scheme)++ let(:params) do+ { theme_id:, light_palette_id: light_scheme.id, dark_palette_id: dark_scheme.id }+ end++ it { is_expected.to run_successfully }++ it "assigns the palettes to the theme" do+ result++ expect(foundation_theme.reload).to have_attributes(+ color_scheme_id: light_scheme.id,+ dark_color_scheme_id: dark_scheme.id,+ )+ end+ end++ context "when no palettes are provided" do+ fab!(:existing_scheme, :color_scheme)++ before do+ foundation_theme.update!(+ color_scheme_id: existing_scheme.id,+ dark_color_scheme_id: existing_scheme.id,+ )+ end++ it { is_expected.to run_successfully }++ it "clears the theme palettes" do+ result++ expect(foundation_theme.reload).to have_attributes(+ color_scheme_id: nil,+ dark_color_scheme_id: nil,+ )+ end+ end++ context "when a dark-only built-in palette is selected" do+ let(:params) do+ {+ theme_id:,+ light_palette_id: DesignWizard::Apply::BASE_LIGHT_PALETTE_ID,+ dark_palette_id: ColorScheme::NAMES_TO_ID_MAP["Dracula"],+ }+ end++ before { ColorScheme.where(via_wizard: true).destroy_all }++ it { is_expected.to run_successfully }++ it "materializes a copy of the built-in palette and assigns it as the dark palette" do+ expect { result }.to change { ColorScheme.where(via_wizard: true).count }.by(1)++ materialized =+ ColorScheme.find_by(+ base_scheme_id: ColorScheme::NAMES_TO_ID_MAP["Dracula"],+ via_wizard: true,+ )+ expect(foundation_theme.reload).to have_attributes(+ color_scheme_id: nil,+ dark_color_scheme_id: materialized.id,+ )+ end++ it "reuses the materialized palette on subsequent runs" do+ result++ expect { described_class.call(params:, **dependencies) }.not_to change {+ ColorScheme.where(via_wizard: true).count+ }+ end+ end++ context "when offering the palettes of a theme that ships its own" do+ fab!(:wizard_scheme) { Fabricate(:color_scheme, via_wizard: true, user_selectable: true) }++ let(:theme_id) { Theme::CORE_THEMES["horizon"] }+ let(:params) { { theme_id:, palettes_user_selectable: true } }++ it { is_expected.to run_successfully }++ it "makes the theme palettes user selectable and disables the others" do+ result++ theme_schemes = ColorScheme.where(theme_id: horizon_theme.id)+ expect(theme_schemes).to be_present+ expect(theme_schemes.pluck(:user_selectable)).to all(eq(true))+ expect(wizard_scheme.reload.user_selectable).to eq(false)+ end+ end++ context "when offering built-in palettes on a theme without its own" do+ let(:params) { { theme_id:, palettes_user_selectable: true } }++ before { ColorScheme.where(via_wizard: true).destroy_all }++ it { is_expected.to run_successfully }++ it "materializes all built-in palettes as user selectable" do+ expect { result }.to change { ColorScheme.where(via_wizard: true).count }.by(7)+ expect(ColorScheme.where(via_wizard: true).pluck(:user_selectable)).to all(eq(true))+ end++ it "disables them all when reapplied without user selectable palettes" do+ result+ described_class.call(params: params.merge(palettes_user_selectable: false), **dependencies)++ expect(ColorScheme.where(via_wizard: true).count).to eq(7)+ expect(ColorScheme.where(via_wizard: true).pluck(:user_selectable)).to all(eq(false))+ end+ end+ end+enddiff --git a/spec/system/admin_onboarding_banner_spec.rb b/spec/system/admin_onboarding_banner_spec.rbindex 71c15a71c91..7e56bc4cd74 100644--- a/spec/system/admin_onboarding_banner_spec.rb+++ b/spec/system/admin_onboarding_banner_spec.rb@@ -5,7 +5,7 @@ describe "Admin Onboarding Banner" dolet(:banner) { PageObjects::Components::AdminOnboardingBanner.new }let(:predefined_topics_modal) { PageObjects::Modals::AdminOnboardingPredefinedTopics.new }- let(:theme_picker_modal) { PageObjects::Modals::AdminOnboardingThemePicker.new }+ let(:design_wizard_panel) { PageObjects::Components::DesignWizardPanel.new }let(:create_invite_modal) { PageObjects::Modals::CreateInvite.new }let(:composer) { PageObjects::Components::Composer.new }let(:toasts) { PageObjects::Components::Toasts.new }@@ -112,28 +112,128 @@ describe "Admin Onboarding Banner" doenddescribe "select theme step" do- it "opens the theme picker modal" do+ it "opens the design wizard as a sheet" dovisit("/")expect(banner.step_not_completed?("select_theme")).to eq(true)banner.click_step_action("select_theme")- expect(theme_picker_modal).to be_open- expect(theme_picker_modal).to have_theme_cards(minimum: 1)+ expect(design_wizard_panel).to be_visible+ expect(design_wizard_panel).to have_site_sidebarend- it "sets a theme as default and marks step complete" do+ it "docks to the bottom edge on a narrow viewport, leaving the preview visible" do+ admin.update!(uploaded_avatar: Fabricate(:image_upload, width: 100, height: 100))+ visit("/")++ banner.click_step_action("select_theme")+ expect(design_wizard_panel).to be_visible++ page.current_window.resize_to(320, 740)++ dimensions = design_wizard_panel.layout_dimensions++ expect(dimensions[:panel_width]).to be <= dimensions[:viewport_width]+ expect(dimensions[:document_scroll_width]).to be <= dimensions[:viewport_width]++ # a full-height rail would hide the page it previews+ expect(dimensions[:panel_bottom]).to be_within(1).of(dimensions[:viewport_height])+ expect(dimensions[:panel_top]).to be > dimensions[:viewport_height] * 0.25+ end++ it "keeps a custom default theme rendered until another theme is chosen" do+ custom_theme = Fabricate(:theme)+ custom_theme.set_default!++ visit("/")+ banner.click_step_action("select_theme")++ expect(design_wizard_panel).to be_visible+ expect(page).to have_current_path("/")+ expect(design_wizard_panel).to have_no_selected_theme+ expect(design_wizard_panel).to have_disabled_next++ design_wizard_panel.select_theme(Theme.horizon_theme.id)++ expect(page).to have_current_path("/?preview_theme_id=#{Theme.horizon_theme.id}")+ expect(design_wizard_panel).to be_visible+ expect(design_wizard_panel).to have_selected_theme(Theme.horizon_theme)+ end++ it "does not mark the step complete when closed without saving" do+ visit("/")+ banner.click_step_action("select_theme")++ expect(design_wizard_panel).to be_visible++ design_wizard_panel.next_step+ design_wizard_panel.select_palette("default")+ expect(design_wizard_panel).to have_palette_preview++ design_wizard_panel.close++ expect(design_wizard_panel).to be_hidden+ expect(design_wizard_panel).to have_no_palette_preview+ expect(banner.step_not_completed?("select_theme")).to eq(true)+ end++ it "reflects and turns off palettes members can switch between" do+ horizon = Theme.horizon_theme+ horizon.set_default!+ ColorScheme.where(theme_id: horizon.id).update_all(user_selectable: true)+visit("/")banner.click_step_action("select_theme")+ design_wizard_panel.next_step- expect(theme_picker_modal).to be_open+ expect(design_wizard_panel).to have_user_selectable_palettes- selected_name = theme_picker_modal.select_first_selectable_theme+ design_wizard_panel.toggle_user_selectable_palettes++ expect(design_wizard_panel).to have_no_user_selectable_palettes++ design_wizard_panel.next_step+ design_wizard_panel.save++ expect(banner).to be_visible+ expect(ColorScheme.where(theme_id: horizon.id).pluck(:user_selectable)).to all(eq(false))+ end- # Page reloads after theme selection; wait for it to complete- expect(page).to have_css(".admin-onboarding-banner")+ it "previews and applies the design choices and marks step complete" do+ visit("/")+ banner.click_step_action("select_theme")++ expect(design_wizard_panel).to be_visible++ # picking another theme reloads the page with a theme preview and the+ # wizard resumes in the sheet+ design_wizard_panel.select_theme(Theme.horizon_theme.id)+ expect(page).to have_current_path("/?preview_theme_id=#{Theme.horizon_theme.id}")+ expect(design_wizard_panel).to be_visible++ design_wizard_panel.next_step+ design_wizard_panel.select_palette("royal")+ expect(design_wizard_panel).to have_palette_preview+ design_wizard_panel.toggle_user_selectable_palettes+ design_wizard_panel.select_body_font("lato")++ design_wizard_panel.next_step+ design_wizard_panel.select_homepage("categories")++ design_wizard_panel.save++ # Page reloads after saving; wait for it to complete+ expect(banner).to be_visible+ expect(design_wizard_panel).to be_hiddenexpect(banner.step_completed?("select_theme")).to eq(true)- expect(Theme.find(SiteSetting.default_theme_id).name).to eq(selected_name)++ expect(SiteSetting.default_theme_id).to eq(Theme.horizon_theme.id)+ horizon = Theme.horizon_theme+ expect(horizon.color_scheme.name).to eq("Royal")+ expect(horizon.color_scheme.user_selectable).to eq(true)+ expect(SiteSetting.base_font).to eq("lato")+ expect(SiteSetting.default_homepage).to eq("categories")+ expect(SiteSetting.desktop_category_page_style).to eq("categories_boxes")# the reload must not cancel the in-flight audit writeexpect(@@ -164,10 +264,12 @@ describe "Admin Onboarding Banner" doexpect(banner.step_completed?("invite_collaborators")).to eq(true)banner.click_step_action("select_theme")- expect(theme_picker_modal).to be_open- theme_picker_modal.select_first_selectable_theme+ expect(design_wizard_panel).to be_visible+ design_wizard_panel.next_step+ design_wizard_panel.next_step+ design_wizard_panel.save- # Page reloads after theme selection; banner disappears when all steps complete+ # Page reloads after saving; banner disappears when all steps completeexpect(banner).to be_not_visibleexpect(SiteSetting.enable_site_owner_onboarding).to eq(false)diff --git a/spec/system/page_objects/components/admin_onboarding_banner.rb b/spec/system/page_objects/components/admin_onboarding_banner.rbindex 918c370caf3..275b4fa0062 100644--- a/spec/system/page_objects/components/admin_onboarding_banner.rb+++ b/spec/system/page_objects/components/admin_onboarding_banner.rb@@ -19,16 +19,12 @@ module PageObjectsfind("div##{step_id}")end- def step_checkbox(step_id)- find("div##{step_id} .onboarding-step__checkbox > svg")- end-def step_completed?(step_id)- step_checkbox(step_id)[:class].include?("checked")+ has_css?("div##{step_id} .onboarding-step__checkbox > svg.--completed")enddef step_not_completed?(step_id)- !step_completed?(step_id)+ has_no_css?("div##{step_id} .onboarding-step__checkbox > svg.--completed")enddef click_step_action(step_id)diff --git a/spec/system/page_objects/components/design_wizard_panel.rb b/spec/system/page_objects/components/design_wizard_panel.rbnew file mode 100644index 00000000000..f0107061245--- /dev/null+++ b/spec/system/page_objects/components/design_wizard_panel.rb@@ -0,0 +1,113 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class DesignWizardPanel < PageObjects::Components::Base+ WIZARD_SELECTOR = ".design-wizard"++ def visible?+ has_css?(WIZARD_SELECTOR)+ end++ def hidden?+ has_no_css?(WIZARD_SELECTOR)+ end++ def has_site_sidebar?+ has_css?(".sidebar-sections")+ end++ def select_theme(theme_id)+ find("#{WIZARD_SELECTOR}__theme-card[data-theme-id='#{theme_id}']").click+ end++ def has_selected_theme?(theme)+ has_css?(+ "#{WIZARD_SELECTOR}__theme-card[data-theme-id='#{theme.id}'] input[type='radio']:checked",+ )+ end++ def has_no_selected_theme?+ has_no_css?("#{WIZARD_SELECTOR}__theme-card input[type='radio']:checked")+ end++ def has_disabled_next?+ has_css?("#{WIZARD_SELECTOR}__next[disabled]")+ end++ def select_palette(pair_key)+ find("#{WIZARD_SELECTOR}__swatch[data-pair-key='#{pair_key}']").click+ end++ def toggle_user_selectable_palettes+ user_selectable_switch.toggle+ end++ def has_user_selectable_palettes?+ user_selectable_switch.checked?+ end++ def has_no_user_selectable_palettes?+ user_selectable_switch.unchecked?+ end++ def select_homepage(key)+ find("#{WIZARD_SELECTOR}__homepage-card[data-homepage='#{key}']").click+ end++ def select_body_font(font_key)+ groups = all("#{WIZARD_SELECTOR}__font-group")+ groups[0].find("#{WIZARD_SELECTOR}__font-select").click+ find(+ "[data-identifier='design-wizard-base-font'] .btn.body-font-#{font_key.tr("_", "-")}",+ ).click+ end++ def has_palette_preview?+ has_css?("link[data-scheme-id]", visible: :all)+ end++ def has_no_palette_preview?+ has_no_css?("link[data-scheme-id]", visible: :all)+ end++ def layout_dimensions+ rect = find(WIZARD_SELECTOR).evaluate_script(<<~JS)+ (() => {+ const { width, top, bottom } = this.getBoundingClientRect();+ return { width, top, bottom };+ })()+ JS++ {+ panel_width: rect["width"],+ panel_top: rect["top"],+ panel_bottom: rect["bottom"],+ viewport_width: page.evaluate_script("window.innerWidth"),+ viewport_height: page.evaluate_script("window.innerHeight"),+ document_scroll_width: page.evaluate_script("document.documentElement.scrollWidth"),+ }+ end++ def next_step+ find("#{WIZARD_SELECTOR}__next").click+ end++ def save+ find("#{WIZARD_SELECTOR}__save").click+ end++ def close+ find("#{WIZARD_SELECTOR}__close").click+ end++ private++ def user_selectable_switch+ PageObjects::Components::DToggleSwitch.new(+ "#{WIZARD_SELECTOR}__user-selectable [role='switch']",+ )+ end+ end+ end+enddiff --git a/spec/system/page_objects/modals/admin_onboarding_theme_picker.rb b/spec/system/page_objects/modals/admin_onboarding_theme_picker.rbdeleted file mode 100644index 023a9b2ee2c..00000000000--- a/spec/system/page_objects/modals/admin_onboarding_theme_picker.rb+++ /dev/null@@ -1,32 +0,0 @@-# frozen_string_literal: true--module PageObjects- module Modals- class AdminOnboardingThemePicker < PageObjects::Modals::Base- MODAL_SELECTOR = ".theme-picker-modal"- CARD_SELECTOR = ".theme-picker-modal__card"- NAME_SELECTOR = ".theme-card-preview__name"-- def open?- has_css?(MODAL_SELECTOR)- end-- def has_theme_cards?(**options)- has_css?(CARD_SELECTOR, **options)- end-- def first_selectable_theme_name- find("#{CARD_SELECTOR}:not(.--selected) #{NAME_SELECTOR}", match: :first).text- end-- def select_theme(name)- find(CARD_SELECTOR, text: name).click- find(".theme-picker-modal__footer .btn-primary").click- end-- def select_first_selectable_theme- first_selectable_theme_name.tap { |name| select_theme(name) }- end- end- end-end