A platform for community discussion. Free, open, simple.
DEV: Move discourse-blog into core as blog (#45227)
David Battersby2f8831f45054
diff --git a/.github/labeler.yml b/.github/labeler.ymlindex 94378bba654..fa765116d6f 100644--- a/.github/labeler.yml+++ b/.github/labeler.yml@@ -1,3 +1,7 @@+blog:+ - changed-files:+ - any-glob-to-any-file: plugins/blog/**/*+boards:- changed-files:- any-glob-to-any-file: plugins/boards/**/*diff --git a/.gitignore b/.gitignoreindex 66258c53118..57f02d9971d 100644--- a/.gitignore+++ b/.gitignore@@ -36,6 +36,7 @@!/plugins/discourse-lazy-videos!/plugins/automation/plugins/automation/gems+!/plugins/blog!/plugins/boards!/plugins/chat!/plugins/polldiff --git a/config/official_plugins.json b/config/official_plugins.jsonindex 0e90ffe04c2..426d4615159 100644--- a/config/official_plugins.json+++ b/config/official_plugins.json@@ -73,6 +73,7 @@"discourse-zoom","discourse-rewind","automation",+ "blog","boards","chat","checklist",diff --git a/db/structure.sql b/db/structure.sqlindex e6cb0e6891d..6590c9f7b91 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -2166,6 +2166,196 @@ CREATE SEQUENCE public.badges_id_seqALTER SEQUENCE public.badges_id_seq OWNED BY public.badges.id;+--+-- Name: blog_paths; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.blog_paths (+ id bigint NOT NULL,+ publication_id bigint NOT NULL,+ path character varying NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: blog_paths_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.blog_paths_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: blog_paths_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.blog_paths_id_seq OWNED BY public.blog_paths.id;+++--+-- Name: blog_publications; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.blog_publications (+ id bigint NOT NULL,+ topic_id bigint NOT NULL,+ publisher_id bigint,+ path character varying NOT NULL,+ excerpt character varying DEFAULT ''::character varying NOT NULL,+ featured boolean DEFAULT false NOT NULL,+ published boolean DEFAULT false NOT NULL,+ published_at timestamp(6) without time zone,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL,+ draft_topic_id bigint,+ discussion_topic_id bigint,+ published_revision_id bigint,+ submitted_revision_id bigint,+ approved_revision_id bigint,+ scheduled_revision_id bigint,+ scheduler_id bigint,+ scheduled_at timestamp(6) without time zone,+ last_published_at timestamp(6) without time zone,+ schedule_token character varying,+ schedule_error text DEFAULT ''::text NOT NULL,+ draft_metadata jsonb DEFAULT '{}'::jsonb NOT NULL+);+++--+-- Name: blog_publications_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.blog_publications_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: blog_publications_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.blog_publications_id_seq OWNED BY public.blog_publications.id;+++--+-- Name: blog_review_feedback; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.blog_review_feedback (+ id bigint NOT NULL,+ review_id bigint NOT NULL,+ name character varying(100) DEFAULT ''::character varying NOT NULL,+ email character varying(254) DEFAULT ''::character varying NOT NULL,+ message text NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: blog_review_feedback_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.blog_review_feedback_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: blog_review_feedback_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.blog_review_feedback_id_seq OWNED BY public.blog_review_feedback.id;+++--+-- Name: blog_reviews; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.blog_reviews (+ id bigint NOT NULL,+ topic_id bigint NOT NULL,+ creator_id bigint NOT NULL,+ label character varying(100) DEFAULT ''::character varying NOT NULL,+ title character varying NOT NULL,+ cooked text NOT NULL,+ post_version integer NOT NULL,+ expires_at timestamp(6) without time zone NOT NULL,+ revoked_at timestamp(6) without time zone,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL,+ token character varying(64)+);+++--+-- Name: blog_reviews_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.blog_reviews_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: blog_reviews_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.blog_reviews_id_seq OWNED BY public.blog_reviews.id;+++--+-- Name: blog_revisions; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.blog_revisions (+ id bigint NOT NULL,+ publication_id bigint NOT NULL,+ source_topic_id bigint NOT NULL,+ creator_id bigint NOT NULL,+ data jsonb DEFAULT '{}'::jsonb NOT NULL,+ approver_id bigint,+ approved_at timestamp(6) without time zone,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: blog_revisions_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.blog_revisions_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: blog_revisions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.blog_revisions_id_seq OWNED BY public.blog_revisions.id;++---- Name: bookmarks; Type: TABLE; Schema: public; Owner: ---@@ -14392,6 +14582,41 @@ ALTER TABLE ONLY public.badge_types ALTER COLUMN id SET DEFAULT nextval('public.ALTER TABLE ONLY public.badges ALTER COLUMN id SET DEFAULT nextval('public.badges_id_seq'::regclass);+--+-- Name: blog_paths id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_paths ALTER COLUMN id SET DEFAULT nextval('public.blog_paths_id_seq'::regclass);+++--+-- Name: blog_publications id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_publications ALTER COLUMN id SET DEFAULT nextval('public.blog_publications_id_seq'::regclass);+++--+-- Name: blog_review_feedback id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_review_feedback ALTER COLUMN id SET DEFAULT nextval('public.blog_review_feedback_id_seq'::regclass);+++--+-- Name: blog_reviews id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_reviews ALTER COLUMN id SET DEFAULT nextval('public.blog_reviews_id_seq'::regclass);+++--+-- Name: blog_revisions id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_revisions ALTER COLUMN id SET DEFAULT nextval('public.blog_revisions_id_seq'::regclass);++---- Name: bookmarks id; Type: DEFAULT; Schema: public; Owner: ---@@ -16969,6 +17194,46 @@ ALTER TABLE ONLY public.badgesADD CONSTRAINT badges_pkey PRIMARY KEY (id);+--+-- Name: blog_paths blog_paths_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_paths+ ADD CONSTRAINT blog_paths_pkey PRIMARY KEY (id);+++--+-- Name: blog_publications blog_publications_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_publications+ ADD CONSTRAINT blog_publications_pkey PRIMARY KEY (id);+++--+-- Name: blog_review_feedback blog_review_feedback_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_review_feedback+ ADD CONSTRAINT blog_review_feedback_pkey PRIMARY KEY (id);+++--+-- Name: blog_reviews blog_reviews_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_reviews+ ADD CONSTRAINT blog_reviews_pkey PRIMARY KEY (id);+++--+-- Name: blog_revisions blog_revisions_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.blog_revisions+ ADD CONSTRAINT blog_revisions_pkey PRIMARY KEY (id);++---- Name: bookmarks bookmarks_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -19785,6 +20050,20 @@ CREATE INDEX idx_ai_post_image_captions_reuse ON public.ai_post_image_captions UCREATE UNIQUE INDEX idx_ai_summaries_on_target_type_and_locale ON public.ai_summaries USING btree (target_id, target_type, summary_type, locale) NULLS NOT DISTINCT;+--+-- Name: idx_blog_publications_scheduled_at; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX idx_blog_publications_scheduled_at ON public.blog_publications USING btree (scheduled_at) WHERE (scheduled_at IS NOT NULL);+++--+-- Name: idx_blog_review_feedback_review_created; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX idx_blog_review_feedback_review_created ON public.blog_review_feedback USING btree (review_id, created_at);++---- Name: idx_bookmarks_user_polymorphic_unique; Type: INDEX; Schema: public; Owner: ---@@ -21395,6 +21674,69 @@ CREATE INDEX index_badges_on_badge_type_id ON public.badges USING btree (badge_tCREATE UNIQUE INDEX index_badges_on_name ON public.badges USING btree (name);+--+-- Name: index_blog_paths_on_path; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_blog_paths_on_path ON public.blog_paths USING btree (path);+++--+-- Name: index_blog_paths_on_publication_id; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX index_blog_paths_on_publication_id ON public.blog_paths USING btree (publication_id);+++--+-- Name: index_blog_publications_on_discussion_topic_id; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_blog_publications_on_discussion_topic_id ON public.blog_publications USING btree (discussion_topic_id);+++--+-- Name: index_blog_publications_on_draft_topic_id; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_blog_publications_on_draft_topic_id ON public.blog_publications USING btree (draft_topic_id);+++--+-- Name: index_blog_publications_on_published_and_published_at; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX index_blog_publications_on_published_and_published_at ON public.blog_publications USING btree (published, published_at);+++--+-- Name: index_blog_publications_on_topic_id; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_blog_publications_on_topic_id ON public.blog_publications USING btree (topic_id);+++--+-- Name: index_blog_reviews_on_token; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_blog_reviews_on_token ON public.blog_reviews USING btree (token);+++--+-- Name: index_blog_reviews_on_topic_id_and_created_at; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX index_blog_reviews_on_topic_id_and_created_at ON public.blog_reviews USING btree (topic_id, created_at);+++--+-- Name: index_blog_revisions_on_publication_id_and_id; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX index_blog_revisions_on_publication_id_and_id ON public.blog_revisions USING btree (publication_id, id);++---- Name: index_bookmarks_on_reminder_at; Type: INDEX; Schema: public; Owner: ---@@ -26167,6 +26509,8 @@ SET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES('20261029021723'),+('20261028093149'),+('20261028093146'),('20261021180718'),('20261021180714'),('20261021063131'),@@ -26202,6 +26546,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20261009130230'),('20261009121104'),('20261009113440'),+('20261008205400'),('20261008184751'),('20261008173326'),('20261008005940'),@@ -26233,10 +26578,15 @@ INSERT INTO "schema_migrations" (version) VALUES('20260916113806'),('20260915204557'),('20260915191328'),+('20260915075802'),+('20260915075800'),+('20260915045302'),('20260914213908'),('20260914172801'),('20260914172757'),('20260914140746'),+('20260914051629'),+('20260914042438'),('20260914032737'),('20260913105655'),('20260910110851'),@@ -26246,9 +26596,12 @@ INSERT INTO "schema_migrations" (version) VALUES('20260910030345'),('20260909181443'),('20260909132955'),+('20260909033948'),+('20260909022122'),('20260908160656'),('20260908153158'),('20260908112615'),+('20260908063229'),('20260904171256'),('20260904065041'),('20260904063128'),diff --git a/eslint.config.mjs b/eslint.config.mjsindex 1f03d76ec7e..5f9278cc621 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -11,6 +11,7 @@ export default [{ignores: ["plugins/**/lib/javascripts/locale",+ "plugins/blog/vendor/","plugins/discourse-math/public","public/","vendor/",diff --git a/migrations/core/config/intermediate_db.yml b/migrations/core/config/intermediate_db.ymlindex e9ab393430a..a4adc9b1402 100644--- a/migrations/core/config/intermediate_db.yml+++ b/migrations/core/config/intermediate_db.yml@@ -581,6 +581,7 @@ schema:plugins:- "automation"+ - "blog"- "boards"- "chat"- "checklist"diff --git a/migrations/tooling/config/schema/intermediate_db/ignored.rb b/migrations/tooling/config/schema/intermediate_db/ignored.rbindex d5e69d07a68..6eb8e173dee 100644--- a/migrations/tooling/config/schema/intermediate_db/ignored.rb+++ b/migrations/tooling/config/schema/intermediate_db/ignored.rb@@ -3,6 +3,7 @@Migrations::Tooling::Schema.ignored do# Plugins — all their tables and columns on core tables are auto-ignored via manifestplugin :automation, "Not migrated yet"+ plugin :blog, "Not migrated yet"plugin :boards, "Not migrated yet"plugin :chat, "Not migrated yet"plugin :discourse_adplugin, "Not migrated yet"diff --git a/migrations/tooling/config/schema/plugin_manifest.yml b/migrations/tooling/config/schema/plugin_manifest.ymlindex db5adcba1ce..1195096d80d 100644--- a/migrations/tooling/config/schema/plugin_manifest.yml+++ b/migrations/tooling/config/schema/plugin_manifest.yml@@ -8,6 +8,14 @@ plugins:- discourse_automation_stats- discourse_automation_user_global_noticescolumns: {}+ blog:+ tables:+ - blog_paths+ - blog_publications+ - blog_review_feedback+ - blog_reviews+ - blog_revisions+ columns: {}boards:tables:- discourse_kanban_board_histories@@ -267,6 +275,7 @@ plugins:plugin_checksums:automation: d168107063ed75d7e568f1c1250866f8boards: b1410e9ce903ab8c722282afd4cf5b9f+ blog: 'f6e06ba7d5ee1897dc70e295096cd65b'chat: dfdf8b56a5fcd06326c693011990c36adiscourse-adplugin: 9e52419decf1099c5bc301a90e6cc91adiscourse-affiliate: '08c6e1a851441a082e9be9ddddc63910'diff --git a/plugins/blog/README.md b/plugins/blog/README.mdnew file mode 100644index 00000000000..77e4c3797d6--- /dev/null+++ b/plugins/blog/README.md@@ -0,0 +1,484 @@+# Discourse Blog++A lightweight, server-rendered blog backed by Discourse topics. Write and revise in+the community; read articles at `/blog` on the community or on a dedicated blog hostname; reply in+a deferred, interactive Discourse discussion below each article.++## Features++- Exactly one configured public Blog category; subcategories are not included.+- Separate editorial-only drafts category and native Discourse composer autosave.+- Editorial dashboard with server-side status filtering, title/path search, and+ explicit 30-item Load more pagination.+- An editor-only publication panel on the article's own topic: state, one-click+ publish or correction, an inline summary and diff of pending changes, inline+ article settings, and scheduling, approval, and withdrawal behind a menu.+ Public discussion topics show a thin banner pointing at the private working copy.+- Authenticated blog-layout preview.+- Explicit revision submission, approval, publication, scheduling, and withdrawal.+- Revocable seven-day draft review links with frozen article revisions and private,+ account-free FormKit feedback. Feedback is never published as topic replies; it+ is counted and readable inline in the working copy's publication panel.+- Private working topics, frozen approved revisions, and preserved public discussions.+- Durable paths, including historical date-based paths; automatic 301 aliases when+ changing an article path. Topic title edits never change the published path.+ Imported paths retain case, plus signs, underscores, dots, commas, and encoded+ plus/comma characters. Dated `/blog/archive/YYYY/MM/DD/...` paths are supported;+ other editorial and asset paths remain reserved. Paths cannot contain queries,+ fragments, traversal segments, or encoded separators.+- On a dedicated hostname, legacy `/posts` redirects permanently to `/`; `/posts.rss`+ and `/posts.atom` redirect permanently to the RSS feed at `/feed.xml`. Article discussions retain+ both the `#discussion` and `#comments` fragment targets.+- Excerpts, featured articles, author bylines, reading time, publication/updated+ dates, and card/social images from the topic's first image upload.+- Paginated homepage, searchable archive (titles/excerpts), public tag pages, and+ Markdown About page.+- RSS with stable item identifiers, sitemap, robots, social metadata, and+ `BlogPosting` structured data.+- Blog-primary canonical for the discussion landing page; later discussion pages+ keep their page-specific canonical.+- A configurable paper/ink/accent palette, graphic covers, and Liquid-based+ designs, with bundled Editorial-style and minimal-reference examples under+ `branding/`.+- Separate Settings, Themes, and Identity pages, with focused FormKit editors for named theme drafts, Git imports,+ syntax-highlighted CSS/JavaScript editors, expiring blog-origin previews, and explicit+ activation of immutable snapshots. Editing or pulling a draft never changes readers.+- Automatic light/dark mode, responsive layouts, and a custom-code safe mode.+- The article requires no Ember boot. Full-app discussion loads near the comments.++## Hosting modes++By default the blog is served under `/blog` on the community, for example+`https://forum.example.com/blog/my-article`. It needs no extra hostname, and admins+can pick it as the site homepage.++A blog can instead have its own hostname, such as `https://blog.example.com`, set+in `blog_url`. The hostname needs DNS, TLS and routing set up outside Discourse+first. A host that offers it only on some plans can hide `blog_url` elsewhere, since+site admins cannot change hidden settings. While a dedicated hostname is active,+`/blog` on the community redirects to it with a temporary (302) redirect, so+dropping the hostname later does not leave browsers stuck on the old one.++Enabling the blog claims `/blog` in both modes. A theme or plugin that already+serves its own page under `/blog` stops receiving those requests.++Editorial pages and endpoints live under `/blog-editor` in both modes, and draft+review links under `/blog/review`.++## Installation++The plugin is bundled with Discourse as `plugins/blog`. Until launch its enabled+setting is hidden, so it can only be turned on from the Rails console (step 5).++1. Make sure migrations have run; they create the plugin's tables on every site.+2. For a dedicated hostname only: route both HTTPS hostnames to the same Discourse installation/database. Keep+ the community as the primary/canonical Discourse hostname. On multisite deployments,+ register the blog hostname as an alias in the database connection's `host_names`+ configuration so the correct database is selected before the plugin runs. The+ plugin preserves its configured hostname after database selection; single-site+ deployments do not need a database hostname alias. DNS/TLS/proxy configuration+ must still preserve the original `Host` header. Do not disable hostname checking+ or forward arbitrary untrusted host headers.+3. Create one public **Blog** category. Suggested permissions: everyone can **See+ / Reply**, staff can **See / Reply / Create**. In Ruby these are `:create_post`+ and `:full`, respectively. Replies must be permitted for the audience you want+ to participate.+4. Create a separate **Blog editorial** category, granting access only to the staff,+ admins, and/or moderators automatic groups. A category open to any other group+ is rejected as the drafts category. Use a different category from core's shared+ drafts feature. Do not use the Blog category's description+ topic as an article.+5. Configure:+ - For a dedicated hostname only: `blog_url`, e.g. `https://blog.example.com`, no+ trailing slash/path.+ - `blog_category`: the single public category.+ - `blog_drafts_category`: the private editorial category.+ - `blog_title`, `blog_description`, `blog_about`.+ - `blog_enabled`: enable after configuration. The setting is hidden+ for now, so set it from the Rails console:+ `SiteSetting.blog_enabled = true`.+6. In **Admin → Customize → Embedding**, add an embedding host for the blog. Under+ `/blog`, that is the community's own hostname with the allowed paths `^/blog(/|$)`; on a+ dedicated hostname, it is that exact hostname. Enable `embed_full_app` and+ `embed_full_app_signin_flow`. Do not enable embedding from every origin merely+ to make this plugin work.+7. Visit `/blog-editor` on the community and create your first draft.++On a dedicated hostname, also make sure a proxy's existing `/robots.txt` or+`/sitemap.xml` handlers do not override the blog routes.++### Local hostnames++This only applies to a dedicated hostname; under `/blog` the blog needs no setup+beyond `bin/dev`. The blog and the community must be the same site: the same scheme and the same+registrable domain, such as `blog.example.com` and `forum.example.com`. Otherwise+the embedded discussion does not receive the community session cookie, and readers+appear signed out in the comments.++Locally, `*.localhost` names reach the Rails server without DNS or hosts-file+changes, and two of them are the same site when they share a parent, for example+`community.dev.localhost` and `blog.dev.localhost`. Environment overrides set the+hostnames for a single run without changing the database. While an override is+set, that setting is hidden in the admin UI.++The simplest setup uses plain HTTP on the Rails port:++```sh+DISCOURSE_FORCE_HOSTNAME=community.dev.localhost \+DISCOURSE_BLOG_URL=http://blog.dev.localhost:3000 \+DISCOURSE_CONTENT_SECURITY_POLICY_FRAME_ANCESTORS=false \+bin/dev+```++The environment override skips the setting's `https://` validation. Frame-ancestors+protection is turned off because core only allows `https://` embedding hosts to+frame the community, which would otherwise block the discussion. Add+`blog.dev.localhost:3000` as an embedding host, then sign in at+`http://community.dev.localhost:3000`.++To test closer to production, put a local TLS proxy such as Caddy in front of Rails+for both hostnames and run with `DISCOURSE_FORCE_HTTPS=1`, `DISCOURSE_PORT` set to+the proxy's HTTPS port, and an `https://` blog URL on that port. On macOS, use a+port above 1024 (for example 8443) if the proxy only listens on `127.0.0.1`;+unprivileged processes cannot bind ports below 1024 to a single interface. The+embedding host then includes that port, for example `blog.dev.localhost:8443`.++### Backups and hostname changes++Back up uploads as well as the database. Enable `include_thumbnails_in_backups`+when preserving published revisions: their frozen HTML can reference optimized+images that are not regenerated simply by rendering the article.++A backup carries blog settings, themes, publications, and revisions, but not plugin+source, DNS, TLS, or reverse-proxy configuration. Restore onto a compatible+Discourse build with this plugin installed. Before exposing a restored site, set+the correct blog origin and exact embedding host, and verify both reader and+editorial permissions.++For a hostname-changing restore, also remap absolute URLs inside+`blog_revisions.data`. These snapshots use JSONB; core's text-column+hostname remapping does not update them. Perform this as an explicit, backed-up+restore operation, not by republishing or rebaking live articles. Verify canonicals,+feeds, sitemap, article images, and embedded discussions before reopening traffic.++### Local demo provisioning++```sh+bin/rake blog:demo+```++Development only. Configures the local origin, categories, and embedding, then+adds three sample articles, a private draft, and labeled sample conversations from+the first admin and two random existing users. Articles and replies that already+exist are skipped, so it is safe to re-run; re-running resets the demo site+settings but does not replace existing article bodies. It never runs automatically+during plugin installation or migration.++## Appearance and custom code++Open **Admin → Plugins → Blog**. **Themes** lists the saved designs and the one+currently shown to readers; **Identity** holds the blog name, tagline, and About+content. A design owns its whole look: palette, CSS, JavaScript, and Liquid+templates. Design and color changes are blog-only; they do not restyle the community.++Theme cards use a shared typographic specimen and the saved draft's paper, ink,+and accent colors. These covers are palette samples, not screenshots: they do not+load a draft's CSS, fonts, JavaScript, or templates into the admin page. Use the+card's **Preview** action to see the complete rendered design.++The template editor uses FormKit's custom-control slot with Ace bound directly to+`field.value` and `field.set`. Variable insertion changes the field programmatically;+the stock code control captures only its initial value. Keep this binding local to+the template editor rather than patching core or remounting Ace after insertion.+CSS and JavaScript fields use the stock code control.++Reader pages always load one built-in stylesheet, `blog.css`, which is a plain+reading layout, followed by the active design's CSS. The bundled design under+`branding/discourse-blog` shows a richer layout built on that base.++Each theme draft carries its palette, Liquid templates, and two+syntax-highlighted code editors:++- **Custom CSS** loads after the built-in theme. It applies to reader pages and+ authenticated blog-layout previews. Use plain CSS, not SCSS or style tags.+ It cannot cross the discussion iframe boundary; that surface is tinted with the+ design's palette instead. Further discussion styling belongs in a forum theme,+ scoped to `html.discourse-blog-discussion body.embed-mode`.+- **Custom JavaScript** runs deferred, after the document is parsed, on blog+ pages. Under `/blog` those pages share the community's origin, so the code has the same+ reach as forum theme JavaScript. It is served as a JavaScript file, so `<script>` markup would be a syntax+ error. To load another script, append the element instead:++ ```js+ const script = document.createElement("script");+ script.src = "https://example.com/widget.js";+ document.head.append(script);+ ```++ The file loads with a CSP nonce and the blog's policy uses `strict-dynamic`, so a+ script it appends runs without allowlisting that origin. The code deliberately does+ **not** run in authenticated previews, in normal community pages, or inside the+ discussion iframe.++Both are administrator-only and publicly downloadable. They are executable/trusted+customizations, not a place for secrets. Saves go through the theme editor and then+through explicit activation, and are audited in staff action logs.+Each code field is limited to 65,536 characters. Invalid CSS/JavaScript is not+silently repaired: test your code before deploying it to readers.++**Recovery:** open a blog URL with `?blog_safe_mode=1` to skip both custom snippets+for that view. The Identity page links to the blog and to that recovery view, and+stays usable even if a customization breaks the blog.+Clear the relevant code field in the theme editor, save the draft, and activate it+to remove a customization. The built-in theme still loads in safe mode. CSS and+JavaScript assets are uncached so a reload picks up saved changes.++Stable styling hooks include `.blog`, `.blog__header`, `.blog__brand`,+`.blog__intro`, `.blog-card`, `.blog-article`, `.blog-article__body`, and+`.blog-discussion`. The body exposes `data-blog-page`.+The palette exposes `--blog-accent-color`, `--blog-paper-color`, and+`--blog-ink-color`. Both themes also expose `--blog-canvas`,+`--blog-foreground`, `--blog-muted`, `--blog-rule`, and `--blog-link-color`.++```css+.blog-article__body {+ font-size: 1.2rem;+}+```++```js+const brand = document.querySelector(".blog__brand");+brand?.setAttribute("title", "Written in our community");+```++The unbranded demo setup includes small, editable CSS/JS examples to demonstrate that the+customization pipeline is active. Article cover uploads take precedence over a+design's decorative graphic covers.++## Reader templates++Reader pages use Liquid templates with optional per-theme overrides. Switch themes+through the normal preview/activation interface; no articles or editorial data need+to change.++## Editorial workflow++1. **New draft** opens the native composer in the private drafts category. Saving+ the topic does not publish it. Internal replies stay on this private topic.+2. Every draft topic shows an editor-only **publication panel** above the first+ post. It states whether the article is a draft, live, live with pending+ changes, scheduled, or unpublished, and offers one primary action.+3. For an existing public article, the public discussion topic shows a banner+ with **Edit privately**, which creates a private working copy and links to it.+ The existing public discussion and its replies keep their IDs.+4. **Article settings** (path, excerpt, date, featured) are edited inline in the+ panel. **Save settings** stages metadata without changing the live article.+5. **Publish** (or **Publish correction** once live) requires confirmation and+ freezes the current draft and settings as a revision, approves it, and copies+ only that frozen article into a separate public discussion (or updates its+ existing first post). It never moves an editorial topic or copies its replies.+ Contributors and editors see **Submit for approval** instead; a publisher then+ previews the submitted revision and chooses **Approve and publish**.+ Publishers may approve their own work.+6. When a live article's working copy drifts, the panel lists which fields+ changed and can show an inline diff against the live revision. While the+ working copy matches the live article there is nothing to publish, so the+ panel offers only **Options → Unpublish**.+7. The panel menu holds the rarer paths: **Schedule…** freezes the draft as it is+ now and releases it at a local date/time; later edits do not change that+ scheduled release unless it is cancelled and rescheduled. The article's optional+ backdated publication date is separate from its scheduled release time.+ **Submit for approval** is also available to publishers who want a second+ sign-off.+8. **Unpublish** withdraws the blog page and cancels scheduling but leaves the+ public discussion accessible. The legacy return-to-drafts endpoint now has the+ same withdrawal semantics and prepares a private working copy; it never moves+ an existing public discussion.++Old paths become redirects only when their replacement revision is published.+Configure the contributor, editor, and publisher group settings alongside native+category permissions: every group with access to the drafts category must also be+in one of the three group settings, or the drafts category is rejected.++## Privacy and security++- Editorial role, ownership where applicable, and topic visibility are checked server-side.+ Personal messages and topics outside the two configured categories cannot be+ published with this interface.+- The public blog always evaluates **anonymous** visibility, even when an editor+ is signed in. Publication alone cannot expose a restricted, unlisted, deleted,+ or hidden source. The first post must also be visible and regular.+- Articles, listings, feed, sitemap, redirects, and topic canonicals use the same+ publication visibility query. A topic moved out of the Blog category disappears+ from the blog; it can become available again if restored while still published.+- Public responses use `private, no-store` in v1 so visibility revocation takes+ effect on the next request. Do not add a CDN cache without a purge/revocation+ design. Already delivered pages, feeds, screenshots, and search copies cannot+ be recalled.+- Preview is authenticated on the community, `noindex` and `no-store`; it does not change+ Guardian permissions or enable anonymous share tokens.+- **Secure uploads, login-required sites, and sites that prohibit anonymous file+ downloads are unsupported in this version.**+ Draft text is private, but upload URLs are not access-controlled when secure+ uploads are disabled. Do not put confidential attachments into these drafts.+ Supporting private draft media needs an explicit media-publication design.+- Discourse authentication remains on the community. No API key is exposed to the blog+ browser and cookies are not broadened to the parent domain.++## Rendering and discussion scope++Ordinary cooked Markdown/HTML, images, links, tables, quotes, code blocks, native+`details`, and normal media are server rendered. Internal links and media URLs are+made absolute. The stylesheet intentionally does not import the entire Discourse+theme or application bundle.++Onebox layout lives in the shared `public/blog.css`, not in individual designs.+Keep avatars small, ordinary thumbnails beside the text, and explicitly full-size+media on their own row. When changing these rules, check bare `.thumbnail` images,+`.onebox-avatar`, `.aspect-image` wrappers, and `.aspect-image-full-size` wrappers+at narrow and desktop widths in both color modes. Article images outside oneboxes+must retain their normal sizing. Code oneboxes normalize whitespace around their+line lists, preserving it only inside each line. Check line numbering, indentation,+empty lines, and horizontal scrolling without applying article-list spacing.++Syntax highlighting is progressive enhancement in the shared reader. Only articles+with eligible code blocks load the minified core module and the site's existing+language bundle, asynchronously during an idle period (with a timer fallback).+The core module is served locally from the installed frontend assets at a+content-addressed URL; no third-party CDN or Ember application is loaded.+`highlighted_languages` controls available grammars, and `autohighlight_all_code`+controls unlabelled blocks. Explicit `lang-auto` blocks use bounded detection.+Plain-text, opted-out, already highlighted, unknown-language, and oversized+blocks remain readable without decoration. Numbered code oneboxes retain their+line lists, blank lines, and multiline token context. Syntax colors reuse the+site's light/dark palette. Network failures leave the original code intact.++Run the standalone reader checks from the repository root with+`node --test plugins/blog/test/browser/*.test.mjs`. The highlighting+checks use the repository's Playwright Chromium installation and exercise actual+minified modules, CSP, cross-origin language loading, and DOM preservation.++Complex cooked-content widgets (poll interaction, client-side math, galleries,+and arbitrary plugin decorators) are not a complete match+for the full topic renderer yet. The article links to the community for that experience.+The full discussion does use the existing Discourse application and its features.++The embed is deferred, not weightless: interaction loads Discourse. It currently+waits for a trusted, post-render readiness message before revealing the iframe,+so the initial unstyled document does not flash against the blog. Script failures+or a 30-second readiness timeout show an accessible fallback instead of leaving+a blank frame. It uses a plugin-managed content-resizing iframe (280px minimum, no maximum height). The iframe expands with its content, including live changes, rather than+creating a second scrolling region. The embedded conversation uses the configured+paper, ink, and accent colors of the active design, which the blog sends to the+frame, with dark-mode support. Styles are scoped+to `html.discourse-blog-discussion body.embed-mode`; ordinary forum pages and+other embeds are unchanged. Historical small-action rows, the topic map, progress counters, redundant topic+footer actions, and development overlays are hidden in this reading view; the full history remains in the community.++Existing login, composer, live+updates, moderation, and closed-topic behavior are reused. An **Open in the community**+link always remains available. Same-site HTTPS subdomains are the intended v1+setup; unrelated domains and browser storage restrictions need separate testing.++The sitemap currently contains at most 50,000 article entries; very large archives+need a paginated sitemap index before deployment. There is no WordPress importer,+newsletter, subscription system, page builder, or multilingual publishing in this+iteration.++## Development and tests++```sh+bin/rake db:migrate+LOAD_PLUGINS=1 RAILS_ENV=test bin/rake db:migrate+bin/rspec plugins/blog/spec/+bin/qunit --target blog+pnpm exec playwright install chromium --only-shell+node --test plugins/blog/test/browser/*.test.mjs+```++The browser tests require the Chromium headless shell matching the installed+Playwright version. Re-run the install command after updating Playwright.+The reader's syntax-highlighting module and its license are packaged in+`vendor/highlightjs/` inside the plugin, so production does not require+`node_modules` or a modified core asset-copy script. The browser tests exercise+that packaged module against core's language registrations. See+[`vendor/highlightjs/README.md`](vendor/highlightjs/README.md) when updating it.++Core's linters cover the plugin (`bin/lint --fix plugins/blog`), with `vendor/`+excluded from ESLint. As a bundled plugin, its tables are part of core's+`db/structure.sql` and model annotations, so regenerate those after adding a+migration (`bin/rake db:dump_structure`, `bin/rake annotate:clean`).++### Runtime lifecycle safeguards++The plugin packages its reader highlighter independently of core runtime assets.+Regression request tests run without core's vendored asset directory, and browser+tests use the packaged module rather than a development dependency copy.++Review snapshots retain upload references independently of the working draft.+Revocation and hard deletion release those references immediately; an hourly job+releases references for expired reviews, even when the blog is disabled. The+upgrade migration backfills original, optimized, and short-URL upload references for+existing active snapshots. Run migrations before enabling upload cleanup after an upgrade.+Already-deleted uploads cannot be recovered by the migration.++Sites with `prevent_anons_from_downloading_files` enabled are unsupported, alongside+login-required sites and secure uploads. Public blog and review requests fail+closed, publication/review creation is blocked, and the editorial dashboard shows+an actionable configuration error. The plugin never bypasses upload permissions.++## Compact articles in the forum++Published articles of at least 250 words receive a compact first-post presentation+when viewed as forum topics: the editorial excerpt, a link to the blog, and an+**Expand article here** button. The same button can collapse the article again.+Expansion yields the original cooked-content renderer, preserving code, images,+links, decorators, and normal quoting behavior. Expansion state is retained in the+post's decorator state while its component lives.++The complete raw/cooked post is never replaced or truncated. Short announcements,+unpublished topics, private drafts, blog-layout previews, and embedded discussion+rendering are unchanged. Search/context URLs and article-heading fragment links+show the complete post directly. The existing blog-primary canonical is unchanged.+The presentation uses the `post-content-cooked-html` wrapper outlet; themes can+style `.blog-post-summary` without reaching into cooked article content.++## Finding articles in the editor++`/blog-editor` does not infinitely scroll or download the whole library. It fetches+up to 30 results and offers **Load more** only while another page exists.++The All articles, Drafts, Published, and Not on the blog filters run on the server+before pagination. Not on the blog means discussions in the public publication+category which are not currently live articles; private drafts have their own+filter. Search matches titles, slugs, and stored article paths case-insensitively,+across the entire authorized editorial collection, not just downloaded entries.+Search and status remain active for Load more and Refresh; changing either starts+at the first page. Search input is bounded to 100 characters and SQL wildcards are+escaped. Ordering uses update time and ID, with duplicate rows suppressed when+appending pages if entries move between requests.++The publication panel's settings and schedule forms, theme editor, identity form, and editor search use FormKit. Article+path and excerpt use `@format="full"`, rather than custom input-width CSS. The+public archive's lightweight GET search remains semantic server-rendered HTML;+booting Ember/FormKit there would defeat the no-application-required reader page.++### Theme import and export++The Themes page supports importing a public HTTPS Git repository or a blog theme ZIP+(up to 2 MB and 1,000 archive entries). Both create a new, inactive draft. Export in+the theme editor downloads the **last saved draft**, not unsaved edits or the active+snapshot. Save changes before exporting.++Exports use the same version-2 source layout as Git imports:++- `blog-theme.json`: `version`, `name`, `accent_color`, `paper_color`, `ink_color`+- `blog.css` and `blog.js`+- `templates/{layout,index,article,about,not_found}.liquid`++Empty template files retain the built-in fallback. Archives may contain these files+at the root or inside one enclosing directory. Import applies the same per-file size+and template validation as Git imports; archive contents are never extracted to disk.+Theme IDs, revisions, Git source metadata, activation state, and site identity settings+are not exported. An imported ZIP is an independent draft with no Git connection.+Core Discourse forum theme ZIPs use a different format and cannot be imported here.diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/blog-identity.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/blog-identity.gjsnew file mode 100644index 00000000000..dd4fc646eec--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/blog-identity.gjs@@ -0,0 +1,116 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { service } from "@ember/service";+import AdminConfigAreaCard from "discourse/admin/components/admin-config-area-card";+import SiteSetting from "discourse/admin/models/site-setting";+import Form from "discourse/components/form";+import { popupAjaxError } from "discourse/lib/ajax-error";+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";+import DPageSubheader from "discourse/ui-kit/d-page-subheader";+import { i18n } from "discourse-i18n";++export default class BlogIdentity extends Component {+ @service site;+ @service toasts;++ @tracked saving = false;++ get formData() {+ const settings = this.args.settings;+ return Object.fromEntries(+ ["blog_title", "blog_description", "blog_about"].map((key) => [+ key,+ settings[key] || "",+ ])+ );+ }++ get safeUrl() {+ return `${this.site.blog_base_url}/?blog_safe_mode=1`;+ }++ @action+ async save(data) {+ this.saving = true;+ try {+ await SiteSetting.bulkUpdate(+ Object.fromEntries(+ Object.entries(data).map(([key, value]) => [key, { value }])+ )+ );+ this.toasts.success({+ data: { message: i18n("blog.admin.saved") },+ });+ } catch (error) {+ popupAjaxError(error);+ throw error;+ } finally {+ this.saving = false;+ }+ }++ <template>+ <div class="blog-identity" ...attributes>+ <DBreadcrumbsItem+ @label={{i18n "blog.admin.identity"}}+ @path="/admin/plugins/blog/identity"+ />+ <DPageSubheader+ @descriptionLabel={{i18n "blog.admin.identity_description"}}+ @titleLabel={{i18n "blog.admin.identity"}}+ />+ <div class="blog-identity__links">+ <a+ href={{this.site.blog_base_url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.admin.open_blog"}} ↗</a>+ <a+ href={{this.safeUrl}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.admin.safe_mode"}} ↗</a>+ </div>+ <AdminConfigAreaCard @heading="blog.admin.identity">+ <:content>+ <Form+ class="blog-identity__form"+ @commitOnSubmit={{false}}+ @data={{this.formData}}+ @onSubmit={{this.save}}+ as |form|+ >+ <form.Field+ @format="full"+ @name="blog_title"+ @title={{i18n "blog.admin.blog_title"}}+ @type="input"+ @validation="required"+ as |field|+ ><field.Control /></form.Field>+ <form.Field+ @format="full"+ @name="blog_description"+ @title={{i18n "blog.admin.tagline"}}+ @type="textarea"+ as |field|+ ><field.Control @rows={{2}} /></form.Field>++ <form.Field+ @format="full"+ @name="blog_about"+ @title={{i18n "blog.admin.about"}}+ @type="composer"+ as |field|+ ><field.Control @height={{220}} /></form.Field>+ <form.Actions><form.Submit+ @disabled={{this.saving}}+ @label="blog.admin.save"+ /></form.Actions>+ </Form>+ </:content>+ </AdminConfigAreaCard>+ </div>+ </template>+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-card.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-card.gjsnew file mode 100644index 00000000000..2d600cdb272--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-card.gjs@@ -0,0 +1,152 @@+import Component from "@glimmer/component";+import { array, concat } from "@ember/helper";+import { action } from "@ember/object";+import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";+import AdminConfigAreaCard from "discourse/admin/components/admin-config-area-card";+import ThemeCardPreview from "discourse/components/theme-card-preview";+import DMenu from "discourse/float-kit/components/d-menu";+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";+import BlogThemeThumbnail from "./blog-theme-thumbnail.gjs";++export default class BlogThemeCard extends Component {+ @service blogThemeActions;+ @service router;++ get isActive() {+ return this.args.theme.id === this.args.activeThemeId;+ }++ @action+ activate() {+ this.blogThemeActions.activate(this.args.theme, {+ onActivated: () => this.router.refresh(),+ });+ }++ @action+ pull() {+ this.blogThemeActions.pull(this.args.theme, {+ onPulled: () => this.router.refresh(),+ });+ }++ @action+ remove() {+ this.blogThemeActions.remove(this.args.theme, {+ onRemoved: () => this.router.refresh(),+ });+ }++ <template>+ <AdminConfigAreaCard+ class="theme-card blog-theme-card"+ data-theme-id={{@theme.id}}+ >+ <:content>+ <ThemeCardPreview @theme={{@theme}}>+ <:placeholder>+ <BlogThemeThumbnail @theme={{@theme}} />+ </:placeholder>++ <:title>+ <LinkTo+ class="theme-card__title"+ @model={{@theme.id}}+ @route="adminPlugins.show.discourse-blog-themes.edit"+ >{{@theme.name}}</LinkTo>+ <p class="theme-card__description">{{i18n "blog.admin.revision"}}+ {{@theme.revision}}</p>+ {{#if (or this.isActive @theme.locally_modified)}}+ <div class="theme-card__badges">+ {{#if this.isActive}}+ <span class="theme-card__badge">{{dIcon "circle-check"}}+ {{i18n "blog.admin.active"}}</span>+ {{/if}}+ {{#if @theme.locally_modified}}+ <span class="theme-card__badge">{{dIcon "pencil"}}+ {{i18n "blog.admin.local_edits_badge"}}</span>+ {{/if}}+ </div>+ {{/if}}+ </:title>++ <:footer>+ <div class="theme-card__footer">+ <div class="theme-card__controls">+ <DButton+ class="btn-default theme-card__button edit"+ @preventFocus={{true}}+ @route="adminPlugins.show.discourse-blog-themes.edit"+ @routeModels={{array @theme.id}}+ @translatedLabel={{i18n "blog.admin.edit"}}+ />++ <div class="theme-card__footer-actions">+ <DMenu+ @icon="ellipsis"+ @identifier={{concat "blog-theme-actions-" @theme.id}}+ @modalForMobile={{true}}+ @title={{i18n "blog.admin.theme_actions"}}+ @triggerClass="theme-card__footer-menu btn-flat"+ >+ <:content>+ <DDropdownMenu as |dropdown|>+ <dropdown.item>+ <DButton+ class="theme-card__button btn-transparent"+ @action={{this.activate}}+ @disabled={{this.isActive}}+ @icon="play"+ @preventFocus={{true}}+ @translatedLabel={{i18n "blog.admin.activate"}}+ />+ </dropdown.item>++ {{#if @theme.source}}+ <dropdown.item>+ <DButton+ class="theme-card__button btn-transparent"+ @action={{this.pull}}+ @icon="cloud-arrow-down"+ @preventFocus={{true}}+ @translatedLabel={{i18n "blog.admin.pull_git"}}+ />+ </dropdown.item>+ {{/if}}++ <dropdown.item>+ <a+ class="btn btn-transparent theme-card__button preview"+ href={{@theme.preview_url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{dIcon "eye"}}+ {{i18n "blog.admin.preview"}}</a>+ </dropdown.item>++ <dropdown.item>+ <DButton+ class="theme-card__button btn-transparent --danger"+ @action={{this.remove}}+ @disabled={{this.isActive}}+ @icon="trash-can"+ @preventFocus={{true}}+ @translatedLabel={{i18n "blog.admin.delete_theme"}}+ />+ </dropdown.item>+ </DDropdownMenu>+ </:content>+ </DMenu>+ </div>+ </div>+ </div>+ </:footer>+ </ThemeCardPreview>+ </:content>+ </AdminConfigAreaCard>+ </template>+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-editor.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-editor.gjsnew file mode 100644index 00000000000..c642eb2e19d--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-editor.gjs@@ -0,0 +1,623 @@+import Component from "@glimmer/component";+import { cached, tracked } from "@glimmer/tracking";+import { array, fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { trackedObject } from "@ember/reactive/collections";+import { schedule } from "@ember/runloop";+import { service } from "@ember/service";+import AceEditor from "discourse/components/ace-editor";+import BackButton from "discourse/components/back-button";+import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import getURL from "discourse/lib/get-url";+import DButton from "discourse/ui-kit/d-button";+import DFlashMessage from "discourse/ui-kit/d-flash-message";+import DHighlightedCode from "discourse/ui-kit/d-highlighted-code";+import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";+import DPageSubheader from "discourse/ui-kit/d-page-subheader";+import { i18n } from "discourse-i18n";+import BlogThemeFields from "./blog-theme-fields.gjs";+import BlogThemePreview from "./modal/blog-theme-preview.gjs";+import BlogThemeVariables from "./modal/blog-theme-variables.gjs";++const TEMPLATE_NAMES = ["layout", "index", "article", "about", "not_found"];++const PAGE_FOR_TEMPLATE = {+ template_index: "index",+ template_article: "article",+ template_about: "about",+ template_not_found: "not_found",+};++export default class BlogThemeEditor extends Component {+ @service router;+ @service dialog;+ @service modal;+ @service toasts;+ @service blogThemeActions;++ @tracked busy = false;+ @tracked tab = "design";+ @tracked catalog;+ @tracked previewUrl;+ @tracked previewDevice = "desktop";+ @tracked selectedArticle;+ @tracked previewPage = "index";+ @tracked catalogError = false;+ @tracked variableQuery = "";+ // FormKit hands its API over after the first render, so this has to be tracked:+ // template state read before then would never re-evaluate.+ @tracked formApi;+ #catalogSequence = 0;+ #previewSequence = 0;++ @cached+ get state() {+ const { theme, active } = this.args.model;+ return trackedObject({+ activeTheme: active,+ draft: theme,+ });+ }++ get exportUrl() {+ return getURL(`/admin/plugins/blog/themes/${this.state.draft.id}/export`);+ }++ get hasUnsavedChanges() {+ return this.formApi?.isDirty;+ }++ get previewUnavailable() {+ return this.previewPage === "article" && !this.selectedArticle;+ }++ get actionsDisabled() {+ return this.busy || this.blogThemeActions.busy || this.hasUnsavedChanges;+ }++ get tabs() {+ return [+ {+ name: "design",+ label: i18n("blog.admin.authoring_design"),+ overridden: false,+ },+ ...this.templateChoices,+ ];+ }++ // Overridden state is read lazily so that tab markers stay live inside the tab nav.+ @cached+ get templateChoices() {+ const editor = this;++ return TEMPLATE_NAMES.map((name) => {+ const field = `template_${name}`;++ return {+ name: field,+ label: i18n(`blog.admin.template_${name}`),+ get overridden() {+ return editor.#overridden(field);+ },+ };+ });+ }++ get currentTemplate() {+ return this.templateChoices.find((item) => item.name === this.tab);+ }++ get effectiveTemplate() {+ if (!this.currentTemplate) {+ return "";+ }++ return (+ this.formApi?.get(this.currentTemplate.name) ||+ this.catalog?.templates[this.currentTemplate.name] ||+ ""+ );+ }++ get articleOptions() {+ return this.catalog?.articles ?? [];+ }++ get variables() {+ const rows = [];+ const visit = (object, prefix = "") => {+ for (const [key, value] of Object.entries(object || {})) {+ if (+ prefix === "labels" &&+ typeof value === "string" &&+ value.includes("%{")+ ) {+ continue;+ }+ const path = prefix ? `${prefix}.${key}` : key;+ if (Array.isArray(value)) {+ rows.push({+ path,+ type: i18n("blog.admin.array_value"),+ example: JSON.stringify(value).slice(0, 350),+ snippet: `{% for item in ${path} %}{{ item.${key === "tags" ? "name" : "title"} }}{% endfor %}`,+ });+ } else if (value && typeof value === "object") {+ visit(value, path);+ } else {+ rows.push({+ path,+ type: path.endsWith("_html")+ ? i18n("blog.admin.trusted_html")+ : i18n("blog.admin.escaped_text"),+ example: String(value ?? "").slice(0, 350),+ snippet: `{{ ${path} }}`,+ });+ }+ }+ };+ const sample = this.catalog?.variables || {};+ visit({+ site: sample.site,+ article: sample.article,+ articles: sample.articles,+ page: sample.page,+ labels: sample.labels,+ });+ rows.unshift({+ path: "content_html",+ type: i18n("blog.admin.trusted_html"),+ example: i18n("blog.admin.layout_content"),+ snippet: "{{ content_html }}",+ });+ return rows.filter((row) =>+ row.path.toLowerCase().includes(this.variableQuery.toLowerCase())+ );+ }++ @action+ filterVariables(event) {+ this.variableQuery = event.target.value;+ }++ @action+ preventSearchSubmit(event) {+ if (event.key === "Enter") {+ event.preventDefault();+ }+ }++ @action+ async selectTab(tab) {+ this.tab = tab;+ if (!this.catalog) {+ await this.loadCatalog();+ }+ }++ @action+ openVariables() {+ this.variableQuery = "";+ this.modal.show(BlogThemeVariables, { model: { editor: this } });+ }++ @action+ async openPreview() {+ const page = PAGE_FOR_TEMPLATE[this.tab];+ if (page) {+ this.previewPage = page;+ }++ if (this.previewUnavailable) {+ this.previewPage = "index";+ }++ if (await this.previewWorking()) {+ this.modal.show(BlogThemePreview, { model: { editor: this } });+ }+ }++ @action+ async selectArticle(value) {+ this.selectedArticle = value;+ await this.loadCatalog();+ }++ @action+ async selectPreviewArticle(value) {+ this.selectedArticle = value;+ await Promise.all([this.loadCatalog(), this.previewWorking()]);+ }++ @action+ async selectPreviewPage(value) {+ this.previewPage = value;+ await this.previewWorking();+ }++ @action+ selectDevice(value) {+ this.previewDevice = value;+ }++ @action+ async loadCatalog() {+ const sequence = ++this.#catalogSequence;+ this.catalogError = false;+ try {+ const catalog = await ajax("/admin/plugins/blog/theme-authoring.json", {+ data: { article_id: this.selectedArticle },+ });+ if (sequence !== this.#catalogSequence || this.isDestroying) {+ return;+ }+ this.catalog = catalog;+ this.selectedArticle ||= catalog.articles[0]?.id;+ } catch (error) {+ if (sequence !== this.#catalogSequence || this.isDestroying) {+ return;+ }+ this.catalogError = true;+ popupAjaxError(error);+ }+ }++ @action+ customize() {+ this.formApi.set(this.currentTemplate.name, this.effectiveTemplate);+ }++ @action+ restoreDefault() {+ this.dialog.confirm({+ message: i18n("blog.admin.restore_confirm"),+ didConfirm: () => {+ this.formApi.set(this.currentTemplate.name, "");+ },+ });+ }++ @action+ insertVariable(variable) {+ if (!this.currentTemplate) {+ return;+ }++ this.formApi.set(+ this.currentTemplate.name,+ `${this.effectiveTemplate}\n${variable.snippet}`+ );+ }++ @action+ async previewWorking() {+ if (this.previewUnavailable) {+ return null;+ }++ const sequence = ++this.#previewSequence;+ this.busy = true;++ try {+ const keys = [+ "name",+ "accent_color",+ "paper_color",+ "ink_color",+ "css",+ "javascript",+ ...this.templateChoices.map((item) => item.name),+ ];+ const theme = Object.fromEntries(+ keys.map((key) => [+ key,+ this.formApi.get(key) ?? this.state.draft[key] ?? "",+ ])+ );+ const result = await ajax(+ "/admin/plugins/blog/theme-authoring/preview.json",+ {+ type: "POST",+ data: {+ theme,+ page: this.previewPage,+ article_id: this.selectedArticle,+ },+ }+ );+ if (sequence === this.#previewSequence) {+ this.previewUrl = result.url;+ }+ return this.previewUrl;+ } catch (error) {+ if (sequence === this.#previewSequence) {+ popupAjaxError(error);+ }+ return null;+ } finally {+ if (sequence === this.#previewSequence) {+ this.busy = false;+ }+ }+ }++ @action+ registerApi(api) {+ // Assigning during the render that reads this field would back-track, so wait+ // for the render pass to finish.+ schedule("afterRender", () => {+ if (this.isDestroying) {+ return;+ }+ this.formApi = api;+ if (!this.catalog) {+ this.loadCatalog();+ }+ });+ }++ @action+ async saveDraft(data) {+ const id = this.state.draft.id;+ const theme = await this.#request(id ? `/${id}` : "", id ? "PUT" : "POST", {+ theme: data,+ revision: this.state.draft.revision,+ });+ if (theme) {+ this.formApi.commit();+ this.#update(theme);+ if (!id) {+ this.router.transitionTo(+ "adminPlugins.show.discourse-blog-themes.edit",+ theme.id+ );+ }+ this.toasts.success({+ data: { message: i18n("blog.admin.draft_saved") },+ });+ }+ }++ @action+ activate() {+ this.blogThemeActions.activate(this.state.draft, {+ onActivated: (active) => (this.state.activeTheme = active),+ });+ }++ @action+ pull() {+ this.blogThemeActions.pull(this.state.draft, {+ onPulled: (updated) => this.#update(updated),+ });+ }++ @action+ remove() {+ this.blogThemeActions.remove(this.state.draft, {+ onRemoved: () =>+ this.router.transitionTo("adminPlugins.show.discourse-blog-themes"),+ });+ }++ #overridden(field) {+ const source = this.formApi?.get(field) ?? this.state.draft[field] ?? "";+ return source.trim().length > 0;+ }++ #update(theme) {+ this.state.draft = theme;+ }++ async #request(path, type, data) {+ this.busy = true;+ try {+ return await ajax(`/admin/plugins/blog/themes${path}.json`, {+ type,+ data,+ });+ } catch (error) {+ popupAjaxError(error);+ return false;+ } finally {+ this.busy = false;+ }+ }++ <template>+ <section class="blog-theme-editor admin-detail" ...attributes>+ <BackButton+ @label="blog.admin.back_to_themes"+ @route="adminPlugins.show.discourse-blog-themes"+ />+ <DPageSubheader+ @descriptionLabel={{i18n "blog.admin.editor_description"}}+ @titleLabel={{this.state.draft.name}}+ >+ <:actions as |actions|>+ {{#if this.state.draft.id}}+ <actions.Wrapped>+ <a+ class="btn btn-default raw-link blog-theme-editor__export"+ download+ href={{this.exportUrl}}+ title={{i18n "blog.admin.export_description"}}+ >{{i18n "blog.admin.export"}}</a>+ </actions.Wrapped>+ {{/if}}+ </:actions>+ </DPageSubheader>++ <div class="admin-controls blog-theme-editor__tabs">+ <DHorizontalOverflowNav+ aria-label={{i18n "blog.admin.authoring_sections"}}+ >+ {{#each this.tabs as |tab|}}+ <li>+ <button+ aria-current={{if (eq this.tab tab.name) "true"}}+ class={{if (eq this.tab tab.name) "active" "blank"}}+ data-authoring-tab={{tab.name}}+ type="button"+ {{on "click" (fn this.selectTab tab.name)}}+ >+ {{tab.label}}+ {{#if tab.overridden}}+ <span+ aria-hidden="true"+ class="blog-theme-editor__marker"+ ></span>+ <span class="sr-only">{{i18n "blog.admin.overridden"}}</span>+ {{/if}}+ </button>+ </li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>++ {{#if this.catalogError}}<DButton+ @action={{this.loadCatalog}}+ @label="blog.admin.retry_reference"+ />{{/if}}+ {{#let this.state.draft as |draft|}}+ <Form+ class="blog-theme-editor__form"+ @commitOnSubmit={{false}}+ @data={{draft}}+ @onRegisterApi={{this.registerApi}}+ @onSubmit={{this.saveDraft}}+ as |form|+ >+ {{#if (eq this.tab "design")}}+ <BlogThemeFields @form={{form}} />+ {{else}}+ <div class="blog-theme-editor__state">+ <p class="blog-theme-editor__state-text">{{#if+ this.currentTemplate.overridden+ }}{{i18n "blog.admin.template_custom_state"}}{{else}}{{i18n+ "blog.admin.template_builtin_state"+ }}{{/if}}</p>+ <div class="blog-theme-editor__state-actions">+ <DButton+ class="blog-theme-editor__variables"+ @action={{this.openVariables}}+ @icon="circle-question"+ @label="blog.admin.variable_reference"+ />+ {{#if this.currentTemplate.overridden}}+ <DButton+ class="blog-theme-editor__restore-default"+ @action={{this.restoreDefault}}+ @label="blog.admin.restore_default"+ />+ {{else}}+ <DButton+ class="blog-theme-editor__customize"+ @action={{this.customize}}+ @disabled={{not this.catalog}}+ @label="blog.admin.customize_template"+ />+ {{/if}}+ </div>+ </div>++ {{#if this.currentTemplate.overridden}}+ {{! Keep the field name stable during teardown when switching tabs. }}+ {{#each (array this.currentTemplate) as |template|}}+ <form.Field+ class="blog-theme-editor__template-field"+ @format="full"+ @name={{template.name}}+ @showTitle={{false}}+ @title={{template.label}}+ @type="custom"+ as |field|+ >+ <field.Control>+ <AceEditor+ aria-describedby={{field.describedBy}}+ aria-invalid={{if field.error "true"}}+ class="blog-theme-editor__template-control"+ id={{field.id}}+ name={{field.name}}+ @content={{field.value}}+ @disabled={{field.disabled}}+ @editorId={{field.id}}+ @mode="html"+ @onChange={{field.set}}+ @resizable={{true}}+ />+ </field.Control>+ </form.Field>+ {{/each}}+ {{else}}+ <div class="blog-theme-editor__builtin">+ <DHighlightedCode+ @code={{this.effectiveTemplate}}+ @lang="html"+ />+ </div>+ {{/if}}+ {{/if}}++ <form.Actions>+ <form.Submit+ @disabled={{this.busy}}+ @label="blog.admin.save_draft"+ />+ <form.Button+ class="blog-theme-editor__preview-draft"+ @action={{this.openPreview}}+ @disabled={{this.busy}}+ @icon="eye"+ @label="blog.admin.preview_short"+ />+ {{#if draft.id}}+ <form.Button+ class="blog-theme-editor__activate"+ @action={{this.activate}}+ @disabled={{this.actionsDisabled}}+ @label="blog.admin.activate_theme"+ />+ <form.Button+ class="blog-theme-editor__delete"+ @action={{this.remove}}+ @disabled={{or+ this.actionsDisabled+ (eq draft.id this.state.activeTheme.id)+ }}+ @label="blog.admin.delete_theme"+ />+ {{/if}}+ </form.Actions>+ </Form>+ {{#if this.hasUnsavedChanges}}<p>{{i18n+ "blog.admin.save_before_activate"+ }}</p>{{/if}}+ {{#if draft.source}}+ <details class="blog-theme-editor__source">+ <summary>{{i18n "blog.admin.git_source"}}</summary>+ <p>{{draft.source.repository}}+ ·+ {{draft.source.branch}}+ ·+ <code>{{draft.source.commit}}</code></p>+ {{#if draft.locally_modified}}<DFlashMessage+ @flash={{i18n "blog.admin.local_edits"}}+ @type="info"+ />{{/if}}+ <DButton+ @action={{this.pull}}+ @disabled={{this.actionsDisabled}}+ @label="blog.admin.pull_git"+ />+ </details>+ {{/if}}+ {{/let}}+ </section>+ </template>+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-fields.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-fields.gjsnew file mode 100644index 00000000000..92833b54d56--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-fields.gjs@@ -0,0 +1,63 @@+import DFlashMessage from "discourse/ui-kit/d-flash-message";+import { i18n } from "discourse-i18n";++export default <template>+ <@form.Field+ @format="full"+ @name="name"+ @title={{i18n "blog.admin.theme_name"}}+ @type="input"+ @validation="required"+ as |field|+ ><field.Control @maxlength={{100}} /></@form.Field>+ <@form.Row as |row|>+ <row.Col @size={{4}}>+ <@form.Field+ @name="accent_color"+ @title={{i18n "blog.admin.accent"}}+ @type="color"+ @validation="required"+ as |field|+ ><field.Control /></@form.Field>+ </row.Col>+ <row.Col @size={{4}}>+ <@form.Field+ @name="paper_color"+ @title={{i18n "blog.admin.paper"}}+ @type="color"+ @validation="required"+ as |field|+ ><field.Control /></@form.Field>+ </row.Col>+ <row.Col @size={{4}}>+ <@form.Field+ @name="ink_color"+ @title={{i18n "blog.admin.ink"}}+ @type="color"+ @validation="required"+ as |field|+ ><field.Control /></@form.Field>+ </row.Col>+ </@form.Row>+ <@form.Field+ @description={{i18n "blog.admin.css_description"}}+ @format="full"+ @name="css"+ @title={{i18n "blog.admin.css"}}+ @type="code"+ as |field|+ ><field.Control @height={{280}} @lang="css" /></@form.Field>+ <details class="blog-theme-editor__javascript">+ <summary>{{i18n "blog.admin.js"}}</summary>+ <DFlashMessage @flash={{i18n "blog.admin.code_warning"}} @type="warning" />+ <@form.Field+ @description={{i18n "blog.admin.js_description"}}+ @format="full"+ @name="javascript"+ @showTitle={{false}}+ @title={{i18n "blog.admin.js"}}+ @type="code"+ as |field|+ ><field.Control @height={{280}} @lang="javascript" /></@form.Field>+ </details>+</template>diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-import.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-import.gjsnew file mode 100644index 00000000000..84ee9d6ad12--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-import.gjs@@ -0,0 +1,135 @@+import Component from "@glimmer/component";+import { fn, hash } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";+import DPageSubheader from "discourse/ui-kit/d-page-subheader";+import DPickFilesButton from "discourse/ui-kit/d-pick-files-button";+import { i18n } from "discourse-i18n";++export default class BlogThemeImport extends Component {+ @service router;++ #formApi;++ @action+ registerApi(api) {+ this.#formApi = api;+ }++ @action+ selectFile(field, files) {+ field.set(files[0]);+ }++ @action+ async importTheme(data) {+ let requestData;+ if (data.source === "file") {+ requestData = new FormData();+ requestData.append("file", data.file);+ } else {+ requestData = { repository: data.repository, branch: data.branch };+ }++ try {+ const theme = await ajax("/admin/plugins/blog/themes/import.json", {+ type: "POST",+ data: requestData,+ ...(data.source === "file"+ ? { processData: false, contentType: false }+ : {}),+ });+ this.#formApi.commit();+ this.router.transitionTo(+ "adminPlugins.show.discourse-blog-themes.edit",+ theme.id+ );+ } catch (error) {+ popupAjaxError(error);+ throw error;+ }+ }++ <template>+ <section class="blog-theme-import admin-detail" ...attributes>+ <DBreadcrumbsItem+ @label={{i18n "blog.admin.import"}}+ @path="/admin/plugins/blog/themes/import/new"+ />+ <DPageSubheader+ @descriptionLabel={{i18n "blog.admin.import_description"}}+ @titleLabel={{i18n "blog.admin.import"}}+ />+ <Form+ class="blog-theme-import__form"+ @data={{hash source="git"}}+ @onRegisterApi={{this.registerApi}}+ @onSubmit={{this.importTheme}}+ as |form data|+ >+ <form.Field+ @name="source"+ @title={{i18n "blog.admin.import_source"}}+ @type="radio-group"+ @validation="required"+ as |field|+ >+ <field.Control as |group|>+ <group.Radio @value="git">{{i18n+ "blog.admin.import_git"+ }}</group.Radio>+ <group.Radio @value="file">{{i18n+ "blog.admin.import_file"+ }}</group.Radio>+ </field.Control>+ </form.Field>+ {{#if (eq data.source "git")}}+ <form.Field+ @description={{i18n "blog.admin.git_description"}}+ @format="full"+ @name="repository"+ @title={{i18n "blog.admin.repository"}}+ @type="input"+ @validation="required"+ as |field|+ ><field.Control @maxlength={{1000}} /></form.Field>+ <form.Field+ @format="full"+ @name="branch"+ @title={{i18n "blog.admin.branch"}}+ @type="input"+ as |field|+ ><field.Control @maxlength={{200}} /></form.Field>+ {{else}}+ <form.Field+ @description={{i18n "blog.admin.import_file_description"}}+ @name="file"+ @title={{i18n "blog.admin.theme_file"}}+ @type="custom"+ @validation="required"+ as |field|+ >+ <field.Control>+ <DPickFilesButton+ @acceptedFormatsOverride=".zip"+ @fileInputDisabled={{field.disabled}}+ @fileInputId={{field.id}}+ @label="blog.admin.choose_theme_file"+ @onFilesPicked={{fn this.selectFile field}}+ @showButton={{true}}+ />+ {{#if field.value}}+ <p class="blog-theme-import__filename">{{field.value.name}}</p>+ {{/if}}+ </field.Control>+ </form.Field>+ {{/if}}+ <form.Actions><form.Submit @label="blog.admin.import" /></form.Actions>+ </Form>+ </section>+ </template>+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-thumbnail.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-thumbnail.gjsnew file mode 100644index 00000000000..8a5b87a193b--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/blog-theme-thumbnail.gjs@@ -0,0 +1,49 @@+import Component from "@glimmer/component";+import { trustHTML } from "@ember/template";+import { i18n } from "discourse-i18n";++export default class BlogThemeThumbnail extends Component {+ get style() {+ const theme = this.args.theme;+ return trustHTML(+ `--blog-theme-paper: ${this.#paint(theme.paper_color, "var(--secondary)")};` ++ `--blog-theme-ink: ${this.#paint(theme.ink_color, "var(--primary)")};` ++ `--blog-theme-accent: ${this.#paint(theme.accent_color, "var(--tertiary)")};`+ );+ }++ #paint(value, fallback) {+ return /^[0-9a-f]{6}$/i.test(value) ? `#${value}` : fallback;+ }++ <template>+ <div class="blog-theme-thumbnail" style={{this.style}} ...attributes>+ <div class="blog-theme-thumbnail__eyebrow">{{i18n+ "blog.admin.thumbnail.journal"+ }}</div>+ <div class="blog-theme-thumbnail__headline">{{i18n+ "blog.admin.thumbnail.headline"+ }}</div>+ <p class="blog-theme-thumbnail__excerpt">{{i18n+ "blog.admin.thumbnail.excerpt"+ }}</p>+ <div class="blog-theme-thumbnail__palette">+ <span+ aria-hidden="true"+ class="blog-theme-thumbnail__swatch --ink"+ ></span>+ <span+ aria-hidden="true"+ class="blog-theme-thumbnail__swatch --accent"+ ></span>+ <span+ aria-hidden="true"+ class="blog-theme-thumbnail__swatch --paper"+ ></span>+ <span class="blog-theme-thumbnail__caption">{{i18n+ "blog.admin.thumbnail.palette"+ }}</span>+ </div>+ </div>+ </template>+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/modal/blog-theme-preview.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/modal/blog-theme-preview.gjsnew file mode 100644index 00000000000..bc9bc57cbb9--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/modal/blog-theme-preview.gjs@@ -0,0 +1,95 @@+import DButton from "discourse/ui-kit/d-button";+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";+import DModal from "discourse/ui-kit/d-modal";+import DNativeSelect from "discourse/ui-kit/d-native-select";+import { i18n } from "discourse-i18n";++const BlogThemePreview = <template>+ {{#let @model.editor as |editor|}}+ <DModal+ class="--max blog-theme-preview"+ @closeModal={{@closeModal}}+ @title={{i18n "blog.admin.preview_short"}}+ >+ <:body>+ <p class="blog-theme-preview__hint">{{i18n+ "blog.admin.working_preview_hint"+ }}</p>+ <div class="blog-theme-preview__controls">+ <DNativeSelect+ aria-label={{i18n "blog.admin.preview_page"}}+ @includeNone={{false}}+ @onChange={{editor.selectPreviewPage}}+ @value={{editor.previewPage}}+ as |select|+ >+ <select.Option @value="index">{{i18n+ "blog.admin.preview_home"+ }}</select.Option>+ <select.Option @value="archive">{{i18n+ "blog.admin.preview_archive"+ }}</select.Option>+ <select.Option @value="article">{{i18n+ "blog.admin.preview_article"+ }}</select.Option>+ <select.Option @value="about">{{i18n+ "blog.admin.template_about"+ }}</select.Option>+ <select.Option @value="not_found">{{i18n+ "blog.admin.template_not_found"+ }}</select.Option>+ </DNativeSelect>+ <DNativeSelect+ aria-label={{i18n "blog.admin.sample_article"}}+ @includeNone={{false}}+ @onChange={{editor.selectPreviewArticle}}+ @value={{editor.selectedArticle}}+ as |select|+ >{{#each editor.articleOptions as |article|}}<select.Option+ @value={{article.id}}+ >{{article.title}}</select.Option>{{/each}}</DNativeSelect>+ <DNativeSelect+ aria-label={{i18n "blog.admin.preview_size"}}+ @includeNone={{false}}+ @onChange={{editor.selectDevice}}+ @value={{editor.previewDevice}}+ as |select|+ ><select.Option @value="desktop">{{i18n+ "blog.admin.desktop"+ }}</select.Option><select.Option @value="mobile">{{i18n+ "blog.admin.mobile"+ }}</select.Option></DNativeSelect>+ <DConditionalLoadingSpinner+ @condition={{editor.busy}}+ @size="small"+ />+ </div>+ {{#if editor.previewUnavailable}}+ <p class="blog-theme-preview__empty">{{i18n+ "blog.admin.preview_article_unavailable"+ }}</p>+ {{else}}+ {{#if editor.previewUrl}}+ <div class="blog-theme-preview__scroll"><iframe+ class="blog-theme-preview__frame"+ data-size={{editor.previewDevice}}+ sandbox="allow-scripts allow-same-origin allow-forms"+ src={{editor.previewUrl}}+ title={{i18n "blog.admin.preview_short"}}+ ></iframe></div>+ <p class="blog-theme-preview__link"><a+ href={{editor.previewUrl}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.admin.open_working_preview"}}</a></p>+ {{/if}}+ {{/if}}+ </:body>+ <:footer>+ <DButton @action={{@closeModal}} @label="close" />+ </:footer>+ </DModal>+ {{/let}}+</template>;++export default BlogThemePreview;diff --git a/plugins/blog/admin/assets/javascripts/discourse/components/modal/blog-theme-variables.gjs b/plugins/blog/admin/assets/javascripts/discourse/components/modal/blog-theme-variables.gjsnew file mode 100644index 00000000000..6875d330d83--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/components/modal/blog-theme-variables.gjs@@ -0,0 +1,85 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import DFilterInput from "discourse/ui-kit/d-filter-input";+import DModal from "discourse/ui-kit/d-modal";+import DNativeSelect from "discourse/ui-kit/d-native-select";+import { i18n } from "discourse-i18n";++export default class BlogThemeVariables extends Component {+ get editor() {+ return this.args.model.editor;+ }++ @action+ insert(variable) {+ this.editor.insertVariable(variable);+ this.args.closeModal();+ }++ <template>+ <DModal+ class="blog-theme-variables"+ @closeModal={{@closeModal}}+ @title={{i18n "blog.admin.variable_reference"}}+ >+ <:body>+ <p class="blog-theme-variables__hint">{{i18n+ "blog.admin.insert_hint"+ }}</p>+ <div class="blog-theme-variables__controls">+ <DFilterInput+ aria-label={{i18n "blog.admin.find_variable"}}+ placeholder={{i18n "blog.admin.find_variable"}}+ @filterAction={{this.editor.filterVariables}}+ @value={{this.editor.variableQuery}}+ {{on "keydown" this.editor.preventSearchSubmit}}+ />+ <DNativeSelect+ aria-label={{i18n "blog.admin.sample_article"}}+ @includeNone={{false}}+ @onChange={{this.editor.selectArticle}}+ @value={{this.editor.selectedArticle}}+ as |select|+ >{{#each this.editor.articleOptions as |article|}}<select.Option+ @value={{article.id}}+ >{{article.title}}</select.Option>{{/each}}</DNativeSelect>+ </div>+ <ul class="blog-theme-variables__list">+ {{#each this.editor.variables as |variable|}}+ <li+ class="blog-theme-variables__item"+ data-variable={{variable.path}}+ >+ <div class="blog-theme-variables__header">+ <code+ class="blog-theme-variables__path"+ >{{variable.path}}</code>+ <span+ class="blog-theme-variables__type"+ >{{variable.type}}</span>+ <DButton+ class="btn-default btn-small blog-theme-variables__insert"+ @action={{fn this.insert variable}}+ @label="blog.admin.insert"+ />+ </div>+ <pre+ class="blog-theme-variables__example"+ >{{variable.example}}</pre>+ </li>+ {{else}}+ <li class="blog-theme-variables__empty">{{i18n+ "blog.admin.no_variables"+ }}</li>+ {{/each}}+ </ul>+ </:body>+ <:footer>+ <DButton @action={{@closeModal}} @label="close" />+ </:footer>+ </DModal>+ </template>+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-appearance.js b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-appearance.jsnew file mode 100644index 00000000000..439f56d70eb--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-appearance.js@@ -0,0 +1,10 @@+import { service } from "@ember/service";+import DiscourseRoute from "discourse/routes/discourse";++export default class BlogAppearanceRoute extends DiscourseRoute {+ @service router;++ redirect() {+ this.router.replaceWith("adminPlugins.show.discourse-blog-themes");+ }+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-identity.js b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-identity.jsnew file mode 100644index 00000000000..f49a56c1e31--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-identity.js@@ -0,0 +1,15 @@+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";++export default class BlogIdentityRoute extends DiscourseRoute {+ async model() {+ const { site_settings } = await ajax("/admin/site_settings.json", {+ data: { plugin: "blog" },+ });+ return {+ ...Object.fromEntries(+ site_settings.map((setting) => [setting.setting, setting.value])+ ),+ };+ }+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/edit.js b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/edit.jsnew file mode 100644index 00000000000..f3fa65cc908--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/edit.js@@ -0,0 +1,8 @@+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";++export default class BlogThemesEditRoute extends DiscourseRoute {+ model({ id }) {+ return ajax(`/admin/plugins/blog/themes/${encodeURIComponent(id)}.json`);+ }+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/index.js b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/index.jsnew file mode 100644index 00000000000..188922fc39a--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/index.js@@ -0,0 +1,8 @@+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";++export default class BlogThemesIndexRoute extends DiscourseRoute {+ model() {+ return ajax("/admin/plugins/blog/themes.json");+ }+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/new.js b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/new.jsnew file mode 100644index 00000000000..34b94608866--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-blog-themes/new.js@@ -0,0 +1,20 @@+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";+import { i18n } from "discourse-i18n";++export default class BlogThemesNewRoute extends DiscourseRoute {+ async model() {+ const { active } = await ajax("/admin/plugins/blog/themes.json");+ return {+ active,+ theme: {+ ...active,+ id: null,+ revision: null,+ source: null,+ preview_url: null,+ name: i18n("blog.admin.new_theme_name"),+ },+ };+ }+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/services/blog-theme-actions.js b/plugins/blog/admin/assets/javascripts/discourse/services/blog-theme-actions.jsnew file mode 100644index 00000000000..d76b8fac3ce--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/services/blog-theme-actions.js@@ -0,0 +1,85 @@+import { tracked } from "@glimmer/tracking";+import Service, { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { i18n } from "discourse-i18n";++/**+ * Theme mutations shared by the themes list and the theme editor. Each action+ * confirms, requests, and reports its result through a callback so callers can+ * update their own state.+ */+export default class BlogThemeActions extends Service {+ @service dialog;+ @service toasts;++ @tracked busy = false;++ activate(theme, { onActivated } = {}) {+ this.dialog.confirm({+ message: i18n("blog.admin.activate_confirm", {+ name: theme.name,+ }),+ didConfirm: async () => {+ const active = await this.#request(`/${theme.id}/activate`, "POST", {+ revision: theme.revision,+ });++ if (active) {+ this.toasts.success({+ data: { message: i18n("blog.admin.activated") },+ });+ onActivated?.(active);+ }+ },+ });+ }++ pull(theme, { onPulled } = {}) {+ this.dialog.confirm({+ message: i18n("blog.admin.pull_confirm"),+ didConfirm: async () => {+ const updated = await this.#request(`/${theme.id}/pull`, "POST", {+ revision: theme.revision,+ });++ if (updated) {+ onPulled?.(updated);+ }+ },+ });+ }++ remove(theme, { onRemoved } = {}) {+ this.dialog.confirm({+ message: i18n("blog.admin.delete_confirm", {+ name: theme.name,+ }),+ didConfirm: async () => {+ const result = await this.#request(`/${theme.id}`, "DELETE", {+ revision: theme.revision,+ });++ if (result !== false) {+ onRemoved?.();+ }+ },+ });+ }++ async #request(path, type, data) {+ this.busy = true;++ try {+ return await ajax(`/admin/plugins/blog/themes${path}.json`, {+ type,+ data,+ });+ } catch (error) {+ popupAjaxError(error);+ return false;+ } finally {+ this.busy = false;+ }+ }+}diff --git a/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-identity.gjs b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-identity.gjsnew file mode 100644index 00000000000..cb13f232079--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-identity.gjs@@ -0,0 +1,3 @@+import BlogIdentity from "../../../components/blog-identity.gjs";++export default <template><BlogIdentity @settings={{@model}} /></template>diff --git a/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/edit.gjs b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/edit.gjsnew file mode 100644index 00000000000..93a2831783d--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/edit.gjs@@ -0,0 +1,3 @@+import BlogThemeEditor from "../../../../components/blog-theme-editor.gjs";++export default <template><BlogThemeEditor @model={{@model}} /></template>diff --git a/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/import.gjs b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/import.gjsnew file mode 100644index 00000000000..5cc91ecf22a--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/import.gjs@@ -0,0 +1,3 @@+import BlogThemeImport from "../../../../components/blog-theme-import.gjs";++export default <template><BlogThemeImport /></template>diff --git a/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/index.gjs b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/index.gjsnew file mode 100644index 00000000000..145304a139e--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/index.gjs@@ -0,0 +1,41 @@+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";+import DEmptyState from "discourse/ui-kit/d-empty-state";+import DPageSubheader from "discourse/ui-kit/d-page-subheader";+import { i18n } from "discourse-i18n";+import BlogThemeCard from "../../../../components/blog-theme-card.gjs";++export default <template>+ <section class="blog-themes">+ <DBreadcrumbsItem+ @label={{i18n "blog.admin.themes"}}+ @path="/admin/plugins/blog/themes"+ />+ <DPageSubheader+ @descriptionLabel={{i18n "blog.admin.themes_index_description"}}+ @titleLabel={{i18n "blog.admin.themes"}}+ >+ <:actions as |actions|>+ <actions.Default+ @label="blog.admin.import"+ @route="adminPlugins.show.discourse-blog-themes.import"+ />+ <actions.Primary+ @label="blog.admin.new_theme_short"+ @route="adminPlugins.show.discourse-blog-themes.new"+ />+ </:actions>+ </DPageSubheader>+ {{#if @model.themes.length}}+ <div class="themes-cards-container">+ {{#each @model.themes key="id" as |theme|}}+ <BlogThemeCard @activeThemeId={{@model.active.id}} @theme={{theme}} />+ {{/each}}+ </div>+ {{else}}+ <DEmptyState+ @body={{i18n "blog.admin.no_themes_description"}}+ @title={{i18n "blog.admin.no_themes"}}+ />+ {{/if}}+ </section>+</template>diff --git a/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/new.gjs b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/new.gjsnew file mode 100644index 00000000000..93a2831783d--- /dev/null+++ b/plugins/blog/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-blog-themes/new.gjs@@ -0,0 +1,3 @@+import BlogThemeEditor from "../../../../components/blog-theme-editor.gjs";++export default <template><BlogThemeEditor @model={{@model}} /></template>diff --git a/plugins/blog/app/controllers/blog/articles_controller.rb b/plugins/blog/app/controllers/blog/articles_controller.rbnew file mode 100644index 00000000000..88a70799fa6--- /dev/null+++ b/plugins/blog/app/controllers/blog/articles_controller.rb@@ -0,0 +1,178 @@+# frozen_string_literal: true++module ::Blog+ class ArticlesController < ::ApplicationController+ helper Blog::BlogHelper+ requires_plugin PLUGIN_NAME+ skip_before_action :check_xhr, :preload_json+ # These assets contain public code, never session data.+ skip_before_action :verify_authenticity_token, only: %i[theme_js highlight_js]+ before_action :ensure_public_blog+ before_action :load_blog_theme, except: :highlight_js+ layout "blog"+ rescue_from ActiveRecord::RecordNotFound, Discourse::NotFound do+ @page_title = I18n.t("blog.not_found_title")+ @description = I18n.t("blog.not_found_body")+ @canonical_url = "#{Configuration.base_url}#{blog_path}"+ response.headers["Cache-Control"] = "private, no-store"+ response.headers["X-Robots-Tag"] = "noindex"+ render "blog/articles/not_found", formats: [:html], status: :not_found+ end++ def index+ @page = [params[:page].to_i, 1].max+ @query = params[:q].to_s.strip.first(100)+ publications = Publication.publicly_visible+ if @query.present?+ term = "%#{ActiveRecord::Base.sanitize_sql_like(@query)}%"+ publications =+ publications.where(+ "blog_revisions.data->>'title' ILIKE ? OR blog_revisions.data->>'excerpt' ILIKE ?",+ term,+ term,+ )+ end+ if params[:tag].present?+ tag = Tag.visible(Guardian.new).find_by!(slug: params[:tag])+ publications =+ publications.where(discussion_topic_id: TopicTag.where(tag_id: tag.id).select(:topic_id))+ @tag = tag+ end+ @archive = params[:archive].present?+ publications = publications.order(featured: :desc) unless @archive || @query.present? || @tag+ limit = SiteSetting.blog_posts_per_page+ selected =+ publications+ .newest+ .offset((@page - 1) * limit)+ .limit(limit + 1)+ .includes(:published_revision, discussion_topic: %i[first_post user image_upload tags])+ .to_a+ @more = selected.size > limit+ @publications = selected.first(limit)+ @page_title =+ @tag&.name ||+ (+ if @archive+ I18n.t("blog.archive")+ else+ SiteSetting.blog_title+ end+ )+ @description = SiteSetting.blog_description+ @canonical_url = "#{Configuration.base_url}#{blog_path}"+ @canonical_url += "?page=#{@page}" if @page > 1+ response.headers["X-Robots-Tag"] = "noindex" if @query.present?+ end++ def show+ stored_path = Path.find_by!(path: blog_path)+ @publication =+ Publication+ .publicly_visible+ .includes(:published_revision, discussion_topic: %i[first_post user image_upload tags])+ .find(stored_path.publication_id)+ if @publication.path != blog_path+ return(redirect_to(@publication.url, status: :moved_permanently, allow_other_host: true))+ end+ @topic = @publication.discussion_topic+ @article = @publication.article+ @page_title = @article.title+ @description = @publication.display_excerpt+ @canonical_url = @publication.url+ end++ def about+ @page_title = I18n.t("blog.about")+ @description = SiteSetting.blog_description+ @canonical_url = "#{Configuration.base_url}/about"+ end++ def feed+ @publications =+ Publication+ .publicly_visible+ .newest+ .limit(30)+ .includes(:published_revision, discussion_topic: %i[first_post user])+ render formats: [:rss], layout: false+ end++ def sitemap+ @publications =+ Publication+ .publicly_visible+ .newest+ .limit(50_000)+ .includes(:published_revision, discussion_topic: :first_post)+ render formats: [:xml], layout: false+ end++ def theme_css+ colors = <<~CSS+ :root {+ --blog-accent-color: ##{@blog_theme["accent_color"]};+ --blog-paper-color: ##{@blog_theme["paper_color"]};+ --blog-ink-color: ##{@blog_theme["ink_color"]};+ }+ CSS+ colors += @blog_theme["css"] unless params[:blog_safe_mode] == "1"+ response.headers["X-Robots-Tag"] = "noindex"+ render plain: colors, content_type: "text/css"+ end++ def highlight_js+ raise Discourse::NotFound unless params[:version] == SyntaxHighlighter.version++ no_cookies+ apply_cdn_headers+ immutable_for 1.year+ render plain: SyntaxHighlighter.source, content_type: "application/javascript"+ end++ def theme_js+ response.headers["X-Robots-Tag"] = "noindex"+ code = params[:blog_safe_mode] == "1" ? "" : @blog_theme["javascript"]+ render plain: code, content_type: "application/javascript"+ end++ def robots+ render plain: "User-agent: *\nAllow: /\nSitemap: #{Configuration.base_url}/sitemap.xml\n"+ end++ private++ def blog_path+ @blog_path ||= Configuration.relative_path(request)+ end++ def load_blog_theme+ if params[:blog_theme_preview].present?+ @blog_theme = BlogTheme.from_preview(params[:blog_theme_preview])+ @theme_preview_token = params[:blog_theme_preview]+ response.headers.delete("X-Frame-Options")+ policy =+ ContentSecurityPolicy.policy(+ base_url: "#{request.base_url}#{Discourse.base_path}",+ path_info: request.path_info,+ )+ policy = policy.gsub(/frame-ancestors[^;]*(;|$)/, "")+ response.headers[+ "Content-Security-Policy"+ ] = "#{policy}; frame-ancestors #{Discourse.base_url_no_prefix}"+ response.headers["X-Robots-Tag"] = "noindex, nofollow"+ response.headers["Referrer-Policy"] = "no-referrer"+ elsif %w[theme_css theme_js].include?(action_name) && params[:blog_theme_snapshot].present?+ @blog_theme = BlogTheme.snapshot(params[:blog_theme_snapshot])+ else+ @blog_theme = BlogTheme.active+ end+ end++ def ensure_public_blog+ raise Discourse::NotFound unless Configuration.blog_request?(request)+ # Revoked visibility must take effect on the next request, including feeds and previews.+ response.headers["Cache-Control"] = "private, no-store"+ end+ end+enddiff --git a/plugins/blog/app/controllers/blog/editor_controller.rb b/plugins/blog/app/controllers/blog/editor_controller.rbnew file mode 100644index 00000000000..ce50ec3dc05--- /dev/null+++ b/plugins/blog/app/controllers/blog/editor_controller.rb@@ -0,0 +1,176 @@+# frozen_string_literal: true++module ::Blog+ class EditorController < ::ApplicationController+ helper Blog::BlogHelper+ requires_plugin PLUGIN_NAME+ requires_login except: [:index]+ before_action :ensure_blog_editor, except: :index+ before_action :ensure_discussion_host+ before_action :find_topic, except: :index+ skip_before_action :check_xhr, only: %i[index preview]++ def index+ ensure_blog_editor unless request.format.html? && !current_user+ respond_to do |format|+ format.html { render "default/empty" }+ format.json do+ topics =+ EditorQuery.call(+ guardian,+ filter: params[:filter].presence || "all",+ query: params[:q] || "",+ )+ @page = [params[:page].to_i, 0].max+ selected = topics.offset(@page * 30).limit(31).includes(:first_post, :category).to_a+ publications =+ Publication+ .where(topic_id: selected.map(&:id))+ .includes(+ :discussion_topic,+ :submitted_revision,+ :approved_revision,+ :published_revision,+ topic: :first_post,+ draft_topic: :first_post,+ )+ .index_by(&:topic_id)+ live_topic_ids =+ Publication.publicly_visible.where(topic_id: selected.map(&:id)).pluck(:topic_id).to_set+ render json: {+ error: Configuration.error,+ blog_url: Configuration.base_url,+ more: selected.size > 30,+ topics:+ selected+ .first(30)+ .map { |topic|+ entry(+ topic,+ publications[topic.id],+ live: live_topic_ids.include?(topic.id),+ )+ },+ }+ end+ end+ end++ def show+ render json: entry(@topic, @publication)+ end++ def update+ @publication.save_metadata!(+ current_user,+ params.require(:publication).permit(:path, :excerpt, :featured, :published_at),+ )+ render json: entry(@topic, @publication)+ end++ def publish+ # Without a revision, publishers release their current draft in one step.+ revision_id = params[:revision_id].presence&.to_i+ @publication.publish!(current_user, revision_id: revision_id)+ render json: entry(@topic.reload, @publication)+ end++ def changes+ source = @publication.editorial_topic+ live = @publication.published_revision+ raise Discourse::NotFound unless live && source&.first_post++ title_diff =+ if source.title != live.title+ DiscourseDiff.new(+ "<div>#{CGI.escapeHTML(live.title.to_s)}</div>",+ "<div>#{CGI.escapeHTML(source.title)}</div>",+ ).inline_html+ end+ render json: {+ title_diff_html: title_diff,+ diff_html: DiscourseDiff.new(live.cooked.to_s, source.first_post.cooked).inline_html,+ }+ rescue ONPDiff::DiffLimitExceeded+ render json: { title_diff_html: nil, diff_html: nil, diff_error: true }+ end++ def prepare+ @publication.prepare_draft!(current_user)+ render json: entry(@publication.topic, @publication)+ end++ def submit+ @publication.submit!(current_user)+ render json: entry(@publication.topic, @publication)+ end++ def approve+ @publication.approve!(current_user, params.require(:revision_id).to_i)+ render json: entry(@publication.topic, @publication)+ end++ def schedule+ @publication.schedule!(+ current_user,+ revision_id: params.require(:revision_id).to_i,+ at: params.require(:scheduled_at),+ )+ render json: entry(@publication.topic, @publication)+ end++ def cancel_schedule+ @publication.cancel_schedule!(current_user)+ head :no_content+ end++ def destroy+ @publication.unpublish!(current_user)+ head :no_content+ end++ def return_to_drafts+ @publication.return_to_drafts!(current_user)+ head :no_content+ end++ def preview+ @preview = true+ @canonical_url = @publication.url+ source = @publication.editorial_topic || @topic+ @article =+ if params[:revision_id].present?+ @publication.revisions.find(params[:revision_id])+ else+ Revision.new(data: Revision.capture(@publication, source))+ end+ @page_title = @article.title+ @description = @article.data["excerpt"]+ response.headers["X-Robots-Tag"] = "noindex, nofollow"+ response.headers["Cache-Control"] = "private, no-store"+ render "blog/articles/show", layout: "blog"+ end++ private++ def ensure_blog_editor+ raise Discourse::InvalidAccess unless Configuration.contributor?(current_user)+ end++ def ensure_discussion_host+ raise Discourse::NotFound if Configuration.blog_host?(request)+ end++ def find_topic+ requested = Topic.find(params[:topic_id])+ @publication = Publication.for_topic(requested)+ @topic = @publication.topic+ Configuration.ensure_editor!(current_user, @publication.editorial_topic || @topic)+ end++ def entry(topic, publication, live: nil)+ publication ||= Publication.new(topic: topic, path: "/#{topic.slug.presence || topic.id}")+ PublicationEntry.new(publication, user: current_user, topic: topic, live: live).to_h+ end+ end+enddiff --git a/plugins/blog/app/controllers/blog/review_reader_controller.rb b/plugins/blog/app/controllers/blog/review_reader_controller.rbnew file mode 100644index 00000000000..4e7dd2b7366--- /dev/null+++ b/plugins/blog/app/controllers/blog/review_reader_controller.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++module ::Blog+ class ReviewReaderController < ::ApplicationController+ requires_plugin PLUGIN_NAME+ skip_before_action :handle_theme,+ :check_xhr,+ :redirect_to_login_if_required,+ :redirect_to_profile_if_required+ prepend_before_action :prepare_review_request+ before_action :find_review, except: :csrf+ layout "blog_review"++ rescue_from Discourse::NotFound, ActiveRecord::RecordNotFound do+ render plain: I18n.t("blog.review.unavailable"), status: :not_found+ end++ rescue_from ActiveRecord::RecordInvalid do |error|+ render_json_error error.record, status: :unprocessable_entity+ end++ def csrf+ render json: { csrf: form_authenticity_token }+ end++ def show+ respond_to do |format|+ format.html { render "default/empty" }+ format.json do+ render json: @review.as_json(only: %i[title cooked post_version created_at expires_at])+ end+ end+ end++ def feedback+ raise Discourse::InvalidAccess unless request.headers["Origin"] == Configuration.origin+ RateLimiter.new(nil, "blog-review-feedback-ip-#{request.remote_ip}", 30, 1.hour).performed!+ RateLimiter.new(nil, "blog-review-feedback-#{@review.id}", 60, 1.hour).performed!+ @review.submit_feedback!(params.require(:feedback).permit(:name, :email, :message).to_h)+ head :no_content+ end++ private++ def prepare_review_request+ response.headers["Cache-Control"] = "private, no-store"+ response.headers["X-Robots-Tag"] = "noindex, nofollow"+ response.headers["Referrer-Policy"] = "no-referrer"+ request.env[ApplicationController::NO_THEMES] = true+ request.env[Auth::DefaultCurrentUserProvider::CURRENT_USER_KEY] = nil+ raise Discourse::NotFound unless Configuration.blog_request?(request)+ end++ def find_review+ @review = Review.find_by_token!(params[:review_token])+ end+ end+enddiff --git a/plugins/blog/app/controllers/blog/reviews_controller.rb b/plugins/blog/app/controllers/blog/reviews_controller.rbnew file mode 100644index 00000000000..7c2debaeb50--- /dev/null+++ b/plugins/blog/app/controllers/blog/reviews_controller.rb@@ -0,0 +1,103 @@+# frozen_string_literal: true++module ::Blog+ class ReviewsController < ::ApplicationController+ requires_plugin PLUGIN_NAME+ requires_login+ before_action :find_topic++ rescue_from ActiveRecord::RecordInvalid do |error|+ render_json_error error.record, status: :unprocessable_entity+ end++ def index+ records =+ Review+ .where(topic_id: @topic.id)+ .includes(:creator)+ .order(id: :desc)+ .offset(page * 30)+ .limit(31)+ .to_a+ counts = ReviewFeedback.where(review_id: records.map(&:id)).group(:review_id).count+ eligible = Review.eligible_topic?(@topic)+ creators = {}+ reviews =+ records+ .first(30)+ .map do |review|+ allowed =+ creators.fetch(review.creator_id) do+ creators[review.creator_id] = Review.creator_allowed?(review.creator, @topic)+ end+ entry(review, active: eligible && review.current? && allowed).merge(+ feedback_count: counts[review.id] || 0,+ )+ end+ render json: { reviews: reviews, more: records.length > 30 }+ end++ def create+ review = Review.issue!(topic: @topic, user: current_user, label: params[:label].to_s)+ render json: { review: entry(review) }, status: :created+ end++ def destroy+ Review.where(topic_id: @topic.id).find(params[:id]).revoke!(current_user)+ head :no_content+ end++ def topic_feedback+ records =+ ReviewFeedback+ .joins(:review)+ .where(blog_reviews: { topic_id: @topic.id })+ .includes(:review)+ .order(id: :desc)+ .offset(page * 30)+ .limit(31)+ .to_a+ render json: {+ feedback:+ records+ .first(30)+ .map do |record|+ record.as_json(only: %i[id name email message created_at]).merge(+ review: record.review.as_json(only: %i[id label post_version revoked_at]),+ )+ end,+ more: records.length > 30,+ }+ end++ def feedback+ review = Review.where(topic_id: @topic.id).find(params[:id])+ records = review.feedback.order(:id).offset(page * 30).limit(31).to_a+ render json: {+ feedback: records.first(30).as_json(only: %i[id name email message created_at]),+ more: records.length > 30,+ total: review.feedback.count,+ }+ end++ private++ def find_topic+ raise Discourse::NotFound if Configuration.blog_host?(request)+ @topic = Topic.find(params[:topic_id])+ Configuration.ensure_editor!(current_user, @topic)+ response.headers["Cache-Control"] = "private, no-store"+ end++ def page+ [params[:page].to_i, 0].max+ end++ def entry(review, active: review.accessible?)+ review.as_json(only: %i[id label title post_version created_at expires_at revoked_at]).merge(+ active: active,+ url: (review.url if active),+ )+ end+ end+enddiff --git a/plugins/blog/app/controllers/blog/themes_controller.rb b/plugins/blog/app/controllers/blog/themes_controller.rbnew file mode 100644index 00000000000..c2a8117b0a3--- /dev/null+++ b/plugins/blog/app/controllers/blog/themes_controller.rb@@ -0,0 +1,185 @@+# frozen_string_literal: true++module ::Blog+ class ThemesController < ::Admin::AdminController+ helper Blog::BlogHelper+ requires_plugin PLUGIN_NAME+ skip_before_action :check_xhr, only: :export+ before_action :ensure_discussion_host++ rescue_from RemoteTheme::ImportError do |error|+ render_json_error error.message, status: :unprocessable_entity+ end++ def authoring+ publications =+ Publication+ .publicly_visible+ .newest+ .limit(30)+ .includes(:published_revision, discussion_topic: %i[first_post user image_upload tags])+ @publication =+ (+ if params[:article_id].present?+ publications.find(params[:article_id])+ else+ publications.first+ end+ )+ @publications = publications.first(10)+ @article = @publication&.article+ @topic = @publication&.discussion_topic+ @page = 1+ sample = view_context.blog_template_assigns+ sample["article"] ||= {+ "title" => I18n.t("blog.themes.sample_article"),+ "url" => "#{Configuration.base_url}/example",+ "excerpt" => I18n.t("blog.themes.sample_body"),+ "standfirst" => "",+ "author" => "",+ "published_at" => nil,+ "date" => "",+ "relative_date" => "",+ "reading_time" => "",+ "featured" => false,+ "image_url" => nil,+ "discussion_url" => Discourse.base_url,+ "replies" => 0,+ "replies_label" => "",+ "index" => "01",+ "updated_label" => nil,+ "body_html" => "<p>#{ERB::Util.html_escape(I18n.t("blog.themes.sample_body"))}</p>",+ "tags" => [],+ }+ render json: {+ templates:+ TemplateRenderer::PAGES.to_h { |page|+ ["template_#{page}", TemplateRenderer.builtin(page)]+ },+ articles:+ publications.map { |publication|+ { id: publication.id, title: publication.article.title }+ },+ variables: sample,+ }+ end++ def working_preview+ RateLimiter.new(current_user, "blog-theme-preview", 20, 1.minute).performed!+ path =+ case params[:page]+ when "index"+ "/"+ when "archive"+ "/archive"+ when "about"+ "/about"+ when "not_found"+ "/theme-preview-not-found-#{SecureRandom.hex(16)}"+ when "article"+ Publication.publicly_visible.find(params.require(:article_id)).path+ else+ raise Discourse::InvalidParameters.new(:page)+ end+ token = BlogTheme.working_preview(theme_params, user: current_user)+ render json: {+ url: "#{Configuration.base_url}#{path}?#{{ blog_theme_preview: token }.to_query}",+ },+ status: :created+ end++ def index+ render json: {+ themes: BlogTheme.all.map { |theme| present(theme) },+ active: BlogTheme.active,+ }+ end++ def show+ render json: { theme: present(BlogTheme.find(params[:id])), active: BlogTheme.active }+ end++ def create+ theme = BlogTheme.save(theme_params, user: current_user)+ render json: present(theme), status: :created+ end++ def update+ theme =+ BlogTheme.save(+ theme_params,+ id: params[:id],+ revision: params.require(:revision),+ user: current_user,+ )+ render json: present(theme)+ end++ def destroy+ BlogTheme.destroy(params[:id], revision: params.require(:revision), user: current_user)+ head :no_content+ end++ def activate+ theme =+ BlogTheme.activate(params[:id], revision: params.require(:revision), user: current_user)+ render json: present(theme)+ end++ def export+ theme = BlogTheme.find(params[:id])+ send_data ThemeExporter.export(theme),+ filename: "blog-theme-#{theme["name"].parameterize.presence || "export"}.zip",+ type: "application/zip"+ end++ def import+ if params[:file]+ theme = ThemeImporter.import_file(file: params[:file], user: current_user)+ return render json: present(theme), status: :created+ end++ repository = params.require(:repository)+ branch = params[:branch]+ hijack do+ theme = ThemeImporter.import(repository: repository, branch: branch, user: current_user)+ render json: present(theme), status: :created+ end+ end++ def pull+ theme = BlogTheme.find(params[:id])+ source = theme["source"]+ raise Discourse::InvalidParameters.new(:source) unless source+ revision = params.require(:revision)+ hijack do+ updated =+ ThemeImporter.import(+ repository: source["repository"],+ branch: source["branch"],+ user: current_user,+ id: theme["id"],+ revision: revision,+ )+ render json: present(updated)+ end+ end++ private++ def present(theme)+ token = BlogTheme.preview_token(theme)+ theme.merge(+ "preview_url" => "#{Configuration.base_url}/?#{{ blog_theme_preview: token }.to_query}",+ )+ end++ def theme_params+ params.require(:theme).permit(*BlogTheme::FIELDS).to_h+ end++ def ensure_discussion_host+ raise Discourse::NotFound if Configuration.blog_host?(request)+ end+ end+enddiff --git a/plugins/blog/app/helpers/blog/blog_helper.rb b/plugins/blog/app/helpers/blog/blog_helper.rbnew file mode 100644index 00000000000..747c36f164b--- /dev/null+++ b/plugins/blog/app/helpers/blog/blog_helper.rb@@ -0,0 +1,210 @@+# frozen_string_literal: true++module ::Blog+ module BlogHelper+ def blog_url(path = "")+ url = "#{Configuration.base_url}#{path}"+ if @theme_preview_token+ url +=+ "#{path.include?("?") ? "&" : "?"}#{{ blog_theme_preview: @theme_preview_token }.to_query}"+ end+ url+ end++ def blog_theme+ @blog_theme ||= BlogTheme.active+ end++ def blog_customizations_disabled?+ params[:blog_safe_mode] == "1"+ end++ def blog_theme_asset_url(path = "/blog-theme.css")+ query = {}+ query[:blog_safe_mode] = "1" if blog_customizations_disabled?+ query[:blog_theme_snapshot] = blog_theme["snapshot"] if !@theme_preview_token &&+ blog_theme["snapshot"]+ suffix = query.present? ? "?#{query.to_query}" : ""+ blog_url("#{path}#{suffix}")+ end++ def blog_article_html(post)+ doc = Nokogiri::HTML5.fragment(post&.cooked.to_s)+ doc+ .css("[href], [src], [poster]")+ .each do |element|+ %w[href src poster].each do |attribute|+ value = element[attribute]+ next if value.blank? || value.start_with?("#")+ element[attribute] = (+ if attribute == "href"+ UrlHelper.absolute_without_cdn(value)+ else+ UrlHelper.absolute(value)+ end+ ) if value.start_with?("/") && !value.start_with?("//")+ end+ end+ doc+ .css("[srcset]")+ .each do |element|+ element["srcset"] = element["srcset"]+ .split(",")+ .map do |candidate|+ url, descriptor = candidate.strip.split(/\s+/, 2)+ url = UrlHelper.absolute(url) if url&.start_with?("/") && !url.start_with?("//")+ [url, descriptor].compact.join(" ")+ end+ .join(", ")+ end+ doc.css(".spoiler").each { |element| element["tabindex"] = "0" }+ doc.to_html.html_safe+ end++ def blog_date(date)+ I18n.l(date || Time.current, format: :date_only)+ end++ def blog_revision_tags(revision)+ Tag.visible(Guardian.new).where(name: revision.data["tags"])+ end++ def blog_revision_image(revision)+ url = revision&.data&.[]("image_url")+ UrlHelper.absolute(url) if url.present?+ end++ def blog_page_url(page)+ values = { page: page, q: @query.presence }.compact+ blog_url("#{Configuration.relative_path(request)}?#{values.to_query}")+ end++ def blog_render_template(page, content: nil)+ assigns = blog_template_assigns+ assigns["content_html"] = TemplateRenderer::Html.new(content.to_s) if content+ TemplateRenderer.render(+ page,+ assigns,+ theme: blog_theme,+ custom: !@preview && !blog_customizations_disabled?,+ diagnostics: @theme_preview_token.present?,+ ).html_safe+ end++ def blog_template_assigns+ @blog_template_assigns ||= {+ "site" => {+ "title" => SiteSetting.blog_title,+ "description" => SiteSetting.blog_description,+ "url" => blog_url("/"),+ "archive_url" => blog_url("/archive"),+ "about_url" => blog_url("/about"),+ "feed_url" => blog_url("/feed.xml"),+ "community_url" => Discourse.base_url,+ "editor_url" => "#{Discourse.base_url}/blog-editor",+ "about_html" =>+ TemplateRenderer::Html.new(+ PrettyText.cook(SiteSetting.blog_about.presence || SiteSetting.blog_description),+ ),+ },+ "page" => {+ "title" => @page_title,+ "heading" =>+ (+ if @archive+ I18n.t("blog.archive")+ else+ @tag&.name || SiteSetting.blog_title+ end+ ),+ "eyebrow" =>+ (+ if @tag+ I18n.t("blog.tagged", tag: @tag.name)+ else+ I18n.t("blog.from_the_blog")+ end+ ),+ "archive" => !!@archive,+ "query" => @query,+ "preview_token" => @theme_preview_token,+ "previous_url" => @page && @page > 1 ? blog_page_url(@page - 1) : nil,+ "next_url" => @more ? blog_page_url(@page + 1) : nil,+ },+ "labels" => I18n.t("blog").select { |key, value| value.is_a?(String) }.stringify_keys,+ "articles" =>+ (@publications || []).each_with_index.map do |publication, index|+ blog_template_article(+ publication,+ publication.article,+ publication.discussion_topic,+ index: index,+ )+ end,+ "article" =>+ (+ if @article && @publication+ blog_template_article(@publication, @article, @topic, body: true)+ else+ nil+ end+ ),+ }+ end++ def blog_template_article(publication, article, topic, index: 0, body: false)+ date = publication.published_at+ values = {+ "title" => article.title,+ "url" => blog_url(publication.path),+ "excerpt" => publication.display_excerpt,+ "standfirst" => article.data["excerpt"].presence,+ "author" => article.data["author_name"],+ "published_at" => date&.iso8601,+ "date" => date && blog_date(date),+ "relative_date" =>+ date && I18n.t("blog.time_ago", time: distance_of_time_in_words(date, Time.current)),+ "reading_time" => I18n.t("blog.reading_time", count: article.reading_minutes),+ "featured" => publication.featured?,+ "image_url" => blog_revision_image(article),+ "discussion_url" => topic.url,+ "replies" => [topic.posts_count - 1, 0].max,+ "replies_label" => I18n.t("blog.replies", count: [topic.posts_count - 1, 0].max),+ "index" => format("%02d", index + 1),+ "updated_label" =>+ (+ if date && publication.article_updated_at.to_date > date.to_date+ I18n.t("blog.updated", date: blog_date(publication.article_updated_at))+ else+ nil+ end+ ),+ }+ if body+ values["body_html"] = TemplateRenderer::Html.new(blog_article_html(article))+ values["tags"] = blog_revision_tags(article).map do |tag|+ { "name" => tag.name, "url" => blog_url("/tag/#{tag.slug}") }+ end+ end+ values+ end++ def blog_article_schema+ {+ "@context" => "https://schema.org",+ "@type" => "BlogPosting",+ "headline" => @article.title,+ "description" => @description,+ "url" => @publication.url,+ "mainEntityOfPage" => @publication.url,+ "datePublished" => @publication.published_at&.iso8601,+ "dateModified" => @publication.article_updated_at&.iso8601,+ "author" => {+ "@type" => "Person",+ "name" => @article.data["author_name"],+ },+ "image" => blog_revision_image(@article),+ }.compact.to_json+ end+ end+enddiff --git a/plugins/blog/app/jobs/regular/publish_blog_revision.rb b/plugins/blog/app/jobs/regular/publish_blog_revision.rbnew file mode 100644index 00000000000..9d002a54641--- /dev/null+++ b/plugins/blog/app/jobs/regular/publish_blog_revision.rb@@ -0,0 +1,12 @@+# frozen_string_literal: true++module ::Jobs+ class PublishBlogRevision < ::Jobs::Base+ def execute(args)+ return unless UpcomingChanges.enabled?(:blog_enabled)++ publication = Blog::Publication.find_by(id: args[:publication_id])+ publication&.run_schedule!(args[:token])+ end+ end+enddiff --git a/plugins/blog/app/jobs/scheduled/clean_up_blog_review_uploads.rb b/plugins/blog/app/jobs/scheduled/clean_up_blog_review_uploads.rbnew file mode 100644index 00000000000..b4c6c426dd1--- /dev/null+++ b/plugins/blog/app/jobs/scheduled/clean_up_blog_review_uploads.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++module ::Jobs+ class CleanUpBlogReviewUploads < ::Jobs::Scheduled+ every 1.hour++ def execute(args)+ return unless UpcomingChanges.enabled?(:blog_enabled)++ Blog::Review.release_inactive_uploads!+ end+ end+enddiff --git a/plugins/blog/app/jobs/scheduled/recover_blog_schedules.rb b/plugins/blog/app/jobs/scheduled/recover_blog_schedules.rbnew file mode 100644index 00000000000..789bcb3bc5c--- /dev/null+++ b/plugins/blog/app/jobs/scheduled/recover_blog_schedules.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++module ::Jobs+ class RecoverBlogSchedules < ::Jobs::Scheduled+ every 5.minutes++ def execute(args = nil)+ return unless UpcomingChanges.enabled?(:blog_enabled)++ Blog::Publication+ .where("scheduled_at <= ?", Time.current)+ .order(:scheduled_at)+ .limit(100)+ .pluck(:id, :schedule_token)+ .each do |publication_id, token|+ Jobs.enqueue(:publish_blog_revision, publication_id: publication_id, token: token)+ end+ end+ end+enddiff --git a/plugins/blog/app/models/blog/path.rb b/plugins/blog/app/models/blog/path.rbnew file mode 100644index 00000000000..ec436a88689--- /dev/null+++ b/plugins/blog/app/models/blog/path.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++module ::Blog+ class Path < ActiveRecord::Base+ self.table_name = "blog_paths"+ belongs_to :publication+ validates :path, presence: true, uniqueness: true+ end+end++# == Schema Information+#+# Table name: blog_paths+#+# id :bigint not null, primary key+# path :string not null+# created_at :datetime not null+# updated_at :datetime not null+# publication_id :bigint not null+#+# Indexes+#+# index_blog_paths_on_path (path) UNIQUE+# index_blog_paths_on_publication_id (publication_id)+#diff --git a/plugins/blog/app/models/blog/publication.rb b/plugins/blog/app/models/blog/publication.rbnew file mode 100644index 00000000000..0ab73a0d4bb--- /dev/null+++ b/plugins/blog/app/models/blog/publication.rb@@ -0,0 +1,549 @@+# frozen_string_literal: true++module ::Blog+ class Publication < ActiveRecord::Base+ self.table_name = "blog_publications"+ RESERVED_PATHS =+ (+ %w[+ about+ tag+ feed+ feed.xml+ sitemap+ sitemap.xml+ robots+ robots.txt+ blog+ session+ admin+ t+ u+ review+ posts+ posts.rss+ posts.atom+ blog-theme.css+ blog-custom.js+ blog-highlight+ ] + Configuration::ASSET_PREFIXES+ ).freeze+ METADATA = %w[path excerpt featured published_at].freeze++ belongs_to :topic+ belongs_to :draft_topic, class_name: "Topic", optional: true+ belongs_to :discussion_topic, class_name: "Topic", optional: true+ belongs_to :publisher, class_name: "User", optional: true+ belongs_to :scheduler, class_name: "User", optional: true+ belongs_to :published_revision, class_name: "Blog::Revision", optional: true+ belongs_to :submitted_revision, class_name: "Blog::Revision", optional: true+ belongs_to :approved_revision, class_name: "Blog::Revision", optional: true+ belongs_to :scheduled_revision, class_name: "Blog::Revision", optional: true+ has_many :revisions, dependent: :destroy+ has_many :paths, dependent: :destroy++ validates :topic_id, uniqueness: true+ validates :path,+ presence: true,+ length: {+ maximum: 240,+ },+ format: {+ with: %r{\A/(?:[a-zA-Z0-9_+.,-]|%2[bBcC])+(?:/(?:[a-zA-Z0-9_+.,-]|%2[bBcC])+)*\z},+ }+ validates :excerpt, length: { maximum: 1000 }, exclusion: { in: [nil] }+ validates :featured, inclusion: { in: [true, false] }+ validate :available_path+ validate :valid_publication_date+ before_validation :initialize_topics, on: :create+ after_create :capture_initial_publication++ scope :newest, -> { order(published_at: :desc, id: :desc) }++ def self.publicly_visible+ return none unless Configuration.public_enabled?+ topics = Topic.secured.visible.listable_topics.where(category_id: SiteSetting.blog_category)+ topics = topics.where.not(id: Category.select(:topic_id).where.not(topic_id: nil))+ topics = topics.where.not(id: SharedDraft.select(:topic_id))+ joins(:published_revision, discussion_topic: :first_post)+ .where(published: true, discussion_topic_id: topics.select(:id))+ .where("blog_publications.published_at <= ?", Time.current)+ .where(posts: { hidden: false, deleted_at: nil, post_type: Post.types[:regular] })+ end++ def self.for_topic(topic)+ where(topic_id: topic.id)+ .or(where(draft_topic_id: topic.id))+ .or(where(discussion_topic_id: topic.id))+ .first || new(topic: topic, path: "/#{topic.slug.presence || topic.id}")+ end++ def publicly_visible?+ persisted? && self.class.publicly_visible.where(id: id).exists?+ end++ def editorial_topic+ draft_topic || (topic if topic.category_id == SiteSetting.blog_drafts_category.to_i)+ end++ def editorial_metadata+ values = attributes.slice(*METADATA).as_json.merge(draft_metadata)+ values["published_at"] ||= published_at&.iso8601+ values+ end++ def draft_correction?+ pending_changes.any?+ end++ # Names of the article pieces that differ between the working copy and the live revision.+ def pending_changes+ source = editorial_topic+ return [] unless published_revision && source&.first_post++ metadata = editorial_metadata+ live = published_revision.data+ changes = {+ "title" => source.title != published_revision.title,+ "body" => source.first_post.raw != published_revision.raw,+ "path" => metadata["path"] != live["path"],+ "excerpt" => metadata["excerpt"] != live["excerpt"],+ "featured" => metadata["featured"] != live["featured"],+ "published_at" => draft_date_changed?(metadata["published_at"]),+ "revision" => submitted_revision_differs?,+ }+ changes.select { |_, changed| changed }.keys+ end++ def edits_since_publish+ source = editorial_topic+ return 0 unless last_published_at && source&.first_post+ PostRevision.where(post: source.first_post).where("created_at > ?", last_published_at).count+ end++ def article+ published_revision || Revision.new(data: Revision.capture(self, editorial_topic || topic))+ end++ def url+ "#{Configuration.base_url}#{published_revision&.data&.fetch("path") || path}"+ end++ def preview_url+ "#{Discourse.base_url}/blog-editor/preview/#{topic_id}"+ end++ def display_excerpt+ article.data["excerpt"].presence ||+ PrettyText.excerpt(article.cooked.to_s, 240, strip_links: true, strip_tags: true)+ end++ def article_updated_at+ last_published_at || published_at || updated_at+ end++ def save_metadata!(user, attributes)+ Configuration.ensure_ready!+ topic.with_lock do+ reload if persisted?+ Configuration.ensure_editor!(user, editorial_topic || topic)+ values = editorial_metadata.merge(attributes.to_h.stringify_keys.slice(*METADATA))+ values["published_at"] = published_at if published_revision_id &&+ values["published_at"].blank?+ previous = self.attributes.slice(*METADATA)+ assign_attributes(values)+ raise ActiveRecord::RecordInvalid.new(self) unless valid?+ self.draft_metadata = self.attributes.slice(*METADATA).as_json+ assign_attributes(previous) if published_revision_id+ save!+ StaffActionLogger.new(user).log_custom(+ "blog_metadata",+ topic_id: topic_id,+ path: values["path"],+ )+ end+ self+ end++ def prepare_draft!(user)+ Configuration.ensure_ready!+ topic.with_lock do+ reload if persisted?+ Configuration.ensure_editor!(user, editorial_topic || topic)+ save! unless persisted?+ unless editorial_topic+ source = discussion_topic || topic+ unless source.first_post && !source.first_post.hidden? && !source.archived?+ raise Discourse::InvalidAccess+ end+ creator =+ PostCreator.new(+ source.user || user,+ title: source.title,+ raw: source.first_post.raw,+ tags: source.tags.visible(Guardian.new).pluck(:name),+ category: SiteSetting.blog_drafts_category.to_i,+ guardian: user.guardian,+ acting_user: user,+ skip_jobs: true,+ )+ post = copy_post!(creator, source, SiteSetting.blog_drafts_category.to_i)+ post.topic.update!(image_upload_id: source.image_upload_id)+ update!(draft_topic: post.topic)+ DB.after_commit { creator.enqueue_jobs }+ end+ update!(draft_topic: editorial_topic) unless draft_topic_id+ end+ editorial_topic+ end++ def submit!(user)+ source = prepare_draft!(user)+ topic.with_lock do+ reload+ source.with_lock do+ Configuration.ensure_editor!(user, source)+ ensure_source!(source)+ source.first_post.with_lock do+ revision =+ revisions.create!(+ source_topic: source,+ creator: user,+ data: Revision.capture(self, source),+ )+ update!(submitted_revision: revision, approved_revision: nil)+ end+ end+ StaffActionLogger.new(user).log_custom(+ "blog_submit",+ topic_id: topic_id,+ revision_id: submitted_revision_id,+ )+ end+ submitted_revision+ end++ def approve!(user, revision_id)+ topic.with_lock do+ reload+ Configuration.ensure_publisher!(user, editorial_topic || topic)+ revision = revisions.find(revision_id)+ unless revision.id == submitted_revision_id+ raise Discourse::InvalidParameters.new(I18n.t("blog.editorial.stale"))+ end+ revision.update!(approver: user, approved_at: Time.current) unless revision.approved_at+ update!(approved_revision: revision)+ StaffActionLogger.new(user).log_custom(+ "blog_approve",+ topic_id: topic_id,+ revision_id: revision.id,+ )+ end+ self+ end++ def publish!(user, revision_id: nil)+ # Trusted callers can explicitly approve and publish their current draft in one operation.+ unless revision_id+ revision = submit!(user)+ approve!(user, revision.id)+ revision_id = revision.id+ end+ topic.with_lock do+ reload+ revision = revisions.find(revision_id)+ Configuration.ensure_publisher!(user, editorial_topic || topic)+ unless approved_revision_id == revision.id+ raise Discourse::InvalidParameters.new(I18n.t("blog.editorial.stale"))+ end+ publish_revision!(user, revision)+ clear_schedule!+ end+ self+ end++ def schedule!(user, revision_id:, at:)+ time =+ begin+ Time.zone.parse(at.to_s)+ rescue ArgumentError+ nil+ end+ unless time && time > 1.minute.from_now && time <= 1.year.from_now+ raise Discourse::InvalidParameters.new(I18n.t("blog.editorial.schedule_time"))+ end+ topic.with_lock do+ reload+ Configuration.ensure_ready!+ Configuration.ensure_publisher!(user, editorial_topic || topic)+ revision = revisions.find(revision_id)+ unless approved_revision_id == revision.id && revision.approved_at+ raise Discourse::InvalidParameters.new(I18n.t("blog.editorial.approval_required"))+ end+ update!(+ scheduled_revision: revision,+ scheduled_at: time,+ scheduler: user,+ schedule_token: SecureRandom.uuid,+ schedule_error: "",+ )+ token = schedule_token+ DB.after_commit do+ Jobs.enqueue_at(time, :publish_blog_revision, publication_id: id, token: token)+ end+ StaffActionLogger.new(user).log_custom(+ "blog_schedule",+ topic_id: topic_id,+ revision_id: revision.id,+ scheduled_at: time,+ )+ end+ self+ end++ def cancel_schedule!(user)+ topic.with_lock do+ reload+ Configuration.ensure_publisher!(user, editorial_topic || topic)+ clear_schedule!+ end+ end++ def run_schedule!(token)+ topic.with_lock do+ reload+ return unless schedule_token == token && scheduled_at && scheduled_at <= Time.current+ begin+ self+ .class+ .transaction(requires_new: true) { publish_revision!(scheduler, scheduled_revision) }+ clear_schedule!+ rescue Discourse::InvalidAccess,+ Discourse::InvalidParameters,+ ActiveRecord::RecordInvalid,+ ActiveRecord::RecordNotSaved => error+ reload+ clear_schedule!(+ error:+ (+ if error.is_a?(Discourse::InvalidAccess)+ I18n.t("blog.editorial.access_lost")+ else+ error.message+ end+ ).first(500),+ )+ end+ end+ end++ def unpublish!(user)+ topic.with_lock do+ reload+ Configuration.ensure_publisher!(user, editorial_topic || topic)+ update!(published: false)+ clear_schedule!+ StaffActionLogger.new(user).log_custom("blog_unpublish", topic_id: topic_id)+ end+ end++ def return_to_drafts!(user)+ unpublish!(user)+ prepare_draft!(user)+ end++ private++ def draft_date_changed?(value)+ return false if value.blank?+ parsed =+ begin+ Time.zone.parse(value.to_s)+ rescue ArgumentError+ nil+ end+ parsed.present? && parsed.to_i != published_at&.to_i+ end++ # A re-submission of an unchanged draft is not a pending change.+ def submitted_revision_differs?+ return false if submitted_revision_id.blank? || submitted_revision_id == published_revision_id+ compared = %w[title raw path excerpt featured]+ submitted_revision.data.slice(*compared) != published_revision.data.slice(*compared)+ end++ def initialize_topics+ if topic.category_id == SiteSetting.blog_drafts_category.to_i+ self.draft_topic ||= topic+ elsif topic.category_id == SiteSetting.blog_category.to_i+ self.discussion_topic ||= topic+ end+ end++ def capture_initial_publication+ return unless published? && discussion_topic && !published_revision_id+ revision =+ revisions.create!(+ source_topic: topic,+ creator: publisher || topic.user,+ approver: publisher || topic.user,+ approved_at: published_at,+ data: Revision.capture(self, topic),+ )+ update!(published_revision: revision, last_published_at: updated_at)+ end++ def ensure_source!(source)+ if source.deleted_at || source.archived? || source.shared_draft? || !source.visible ||+ source.category_id != SiteSetting.blog_drafts_category.to_i || !source.first_post ||+ source.first_post.deleted_at || source.first_post.hidden?+ raise Discourse::InvalidAccess+ end+ end++ def publish_revision!(user, revision)+ Configuration.ensure_ready!+ source = editorial_topic+ unless source && revision&.approved_at && revision.publication_id == id+ raise Discourse::InvalidAccess+ end+ ensure_source!(source)+ Configuration.ensure_publisher!(user, source)+ Configuration.ensure_publisher!(revision.approver, source)+ user.guardian.ensure_can_create_topic_on_category!(SiteSetting.blog_category.to_i)+ if PublishedPage.exists?(topic_id: source.id)+ raise Discourse::InvalidParameters.new(I18n.t("blog.errors.published_page"))+ end+ data = revision.data+ if discussion_topic+ user.guardian.ensure_can_see!(discussion_topic)+ if discussion_topic.deleted_at || discussion_topic.archived? ||+ discussion_topic.shared_draft? || !discussion_topic.visible ||+ !discussion_topic.first_post || discussion_topic.first_post.hidden? ||+ discussion_topic.category_id != SiteSetting.blog_category.to_i+ raise Discourse::InvalidAccess+ end+ previous = Thread.current[:blog_publishing_topic]+ begin+ Thread.current[:blog_publishing_topic] = discussion_topic_id+ unless PostRevisor.new(discussion_topic.first_post).revise!(+ user,+ { raw: data["raw"], title: data["title"], tags: data["tags"] },+ force_new_version: true,+ )+ raise ActiveRecord::RecordInvalid.new(discussion_topic.first_post)+ end+ ensure+ Thread.current[:blog_publishing_topic] = previous+ end+ else+ creator =+ PostCreator.new(+ source.user || user,+ raw: data["raw"],+ title: data["title"],+ tags: data["tags"],+ category: SiteSetting.blog_category.to_i,+ guardian: user.guardian,+ acting_user: user,+ skip_jobs: true,+ )+ post = copy_post!(creator, source, SiteSetting.blog_category.to_i)+ self.discussion_topic = post.topic+ DB.after_commit { creator.enqueue_jobs }+ end+ self.path = data["path"]+ self.excerpt = data["excerpt"]+ self.featured = data["featured"]+ self.published_at = data["published_at"].presence || published_at || Time.current+ self.last_published_at = Time.current+ self.published_revision = revision+ self.publisher = user+ self.published = true+ save!+ paths.find_or_create_by!(path: path)+ Review.revoke_for_topic!(source.id)+ StaffActionLogger.new(user).log_custom(+ "blog_publish",+ topic_id: discussion_topic_id,+ revision_id: revision.id,+ )+ end++ def copy_post!(creator, source, category_id)+ previous = Thread.current[:blog_copy]+ Thread.current[:blog_copy] = { source_id: source.id, category_id: category_id }+ creator.create!+ ensure+ Thread.current[:blog_copy] = previous+ end++ def clear_schedule!(error: "")+ # Cleanup must succeed even when publication metadata is no longer valid.+ update_columns(+ scheduled_at: nil,+ scheduled_revision_id: nil,+ scheduler_id: nil,+ schedule_token: nil,+ schedule_error: error,+ updated_at: Time.current,+ )+ end++ def available_path+ segments = path.to_s.split("/")+ # Dated archive imports may use the otherwise reserved editorial prefix.+ legacy_archive = path.to_s.match?(%r{\A/blog/archive/\d{4}/\d{2}/\d{2}/[^/]+\z})+ reserved = RESERVED_PATHS.include?(segments[1].to_s.downcase) && !legacy_archive+ if path.to_s.downcase == "/archive" || reserved || segments.intersect?(%w[. ..]) ||+ Path.where(path: path).where.not(publication_id: id).exists?+ errors.add(:path, I18n.t("blog.errors.path_taken"))+ end+ end++ def valid_publication_date+ if (published? || published_at_before_type_cast.present?) && published_at.nil?+ errors.add(:published_at, :invalid)+ end+ if published_at && published_at > Time.current+ errors.add(:published_at, I18n.t("blog.errors.future_date"))+ end+ end+ end+end++# == Schema Information+#+# Table name: blog_publications+#+# id :bigint not null, primary key+# draft_metadata :jsonb not null+# excerpt :string default(""), not null+# featured :boolean default(FALSE), not null+# last_published_at :datetime+# path :string not null+# published :boolean default(FALSE), not null+# published_at :datetime+# schedule_error :text default(""), not null+# schedule_token :string+# scheduled_at :datetime+# created_at :datetime not null+# updated_at :datetime not null+# approved_revision_id :bigint+# discussion_topic_id :bigint+# draft_topic_id :bigint+# published_revision_id :bigint+# publisher_id :bigint+# scheduled_revision_id :bigint+# scheduler_id :bigint+# submitted_revision_id :bigint+# topic_id :bigint not null+#+# Indexes+#+# idx_blog_publications_scheduled_at (scheduled_at) WHERE (scheduled_at IS NOT NULL)+# index_blog_publications_on_discussion_topic_id (discussion_topic_id) UNIQUE+# index_blog_publications_on_draft_topic_id (draft_topic_id) UNIQUE+# index_blog_publications_on_published_and_published_at (published,published_at)+# index_blog_publications_on_topic_id (topic_id) UNIQUE+#diff --git a/plugins/blog/app/models/blog/review.rb b/plugins/blog/app/models/blog/review.rbnew file mode 100644index 00000000000..709a033c328--- /dev/null+++ b/plugins/blog/app/models/blog/review.rb@@ -0,0 +1,167 @@+# frozen_string_literal: true++module ::Blog+ class Review < ActiveRecord::Base+ include HasPostUploadReferences++ self.table_name = "blog_reviews"+ TOKEN_FORMAT = /\A[A-Za-z0-9_-]{43}\z/++ belongs_to :topic+ belongs_to :creator, class_name: "User"+ has_many :feedback, class_name: "Blog::ReviewFeedback", dependent: :delete_all+ has_many :upload_references, as: :target, dependent: :destroy++ after_create :link_post_uploads+ after_update :release_uploads, if: -> { saved_change_to_revoked_at? && revoked_at? }++ validates :label, length: { maximum: 100 }+ validates :title, :cooked, :post_version, :expires_at, presence: true+ validates :token, format: { with: TOKEN_FORMAT }+ scope :unexpired, -> { where(revoked_at: nil).where("expires_at > ?", Time.current) }++ def self.issue!(topic:, user:, label: "")+ topic.with_lock do+ Configuration.ensure_ready!+ Configuration.ensure_editor!(user, topic)+ raise Discourse::InvalidAccess unless eligible_topic?(topic)+ if where(topic_id: topic.id).unexpired.count >= 20+ raise Discourse::InvalidParameters.new(I18n.t("blog.review.limit"))+ end+ post = topic.first_post+ post.with_lock do+ raise Discourse::InvalidAccess unless eligible_topic?(topic)+ review =+ create!(+ topic: topic,+ creator: user,+ label: label,+ title: topic.title,+ cooked: snapshot_html(post),+ post_version: post.version,+ token: SecureRandom.urlsafe_base64(32),+ expires_at: 7.days.from_now,+ )+ StaffActionLogger.new(user).log_custom(+ "blog_review_create",+ topic_id: topic.id,+ review_id: review.id,+ )+ review+ end+ end+ end++ def self.find_by_token!(token)+ raise Discourse::NotFound unless token.is_a?(String) && token.match?(TOKEN_FORMAT)+ review = unexpired.find_by(token: token)+ raise Discourse::NotFound unless review&.accessible?+ review+ end++ # The link only reaches editors, who can already read the draft and issue more links.+ def url+ "#{Configuration.review_url}?#{{ review_token: token }.to_query}"+ end++ def self.eligible_topic?(topic)+ Configuration.public_enabled? && topic.present? && !topic.deleted_at && topic.visible &&+ topic.category_id == SiteSetting.blog_drafts_category.to_i &&+ topic.category&.read_restricted? && !topic.private_message? && !topic.shared_draft? &&+ topic.first_post.present? && !topic.first_post.deleted_at && !topic.first_post.hidden? &&+ !Publication.where(discussion_topic_id: topic.id, published: true).exists?+ end++ def current?+ !revoked_at && expires_at > Time.current+ end++ def accessible?+ current? && self.class.eligible_topic?(topic) && self.class.creator_allowed?(creator, topic)+ end++ def self.creator_allowed?(creator, topic)+ return false unless creator&.active? && !creator.suspended?+ Configuration.ensure_editor!(creator, topic)+ true+ rescue Discourse::InvalidAccess+ false+ end++ def submit_feedback!(attributes)+ topic.with_lock do+ with_lock do+ raise Discourse::NotFound unless accessible?+ if feedback.count >= 200+ raise Discourse::InvalidParameters.new(I18n.t("blog.review.feedback_limit"))+ end+ feedback.create!(attributes)+ end+ end+ end++ def revoke!(user)+ topic.with_lock do+ Configuration.ensure_editor!(user, topic)+ update!(revoked_at: Time.current) unless revoked_at+ StaffActionLogger.new(user).log_custom(+ "blog_review_revoke",+ topic_id: topic_id,+ review_id: id,+ )+ end+ end++ def self.revoke_for_topic!(topic_id)+ transaction do+ where(topic_id: topic_id, revoked_at: nil).update_all(revoked_at: Time.current)+ UploadReference.where(target: where(topic_id: topic_id)).delete_all+ end+ end++ def self.release_inactive_uploads!+ inactive = where.not(revoked_at: nil).or(where("expires_at <= ?", Time.current))+ UploadReference.where(target: inactive).delete_all+ end++ def self.snapshot_html(post)+ helper = Object.new.extend(BlogHelper)+ doc = Nokogiri::HTML5.fragment(PrettyText.sanitize(helper.blog_article_html(post)))+ doc.css("script, iframe, object, embed, form, input, button, style, link, meta").remove+ doc.css("a").each { |link| link["rel"] = "noopener noreferrer" }+ html = doc.to_html+ raise Discourse::InvalidParameters.new(:cooked) if html.bytesize > 1_048_576+ html+ end+ private_class_method :snapshot_html++ private++ def release_uploads+ upload_references.delete_all+ end+ end+end++# == Schema Information+#+# Table name: blog_reviews+#+# id :bigint not null, primary key+# cooked :text not null+# expires_at :datetime not null+# label :string(100) default(""), not null+# post_version :integer not null+# revoked_at :datetime+# title :string not null+# token :string(64)+# created_at :datetime not null+# updated_at :datetime not null+# creator_id :bigint not null+# topic_id :bigint not null+#+# Indexes+#+# index_blog_reviews_on_token (token) UNIQUE+# index_blog_reviews_on_topic_id_and_created_at (topic_id,created_at)+#diff --git a/plugins/blog/app/models/blog/review_feedback.rb b/plugins/blog/app/models/blog/review_feedback.rbnew file mode 100644index 00000000000..25d38d7defb--- /dev/null+++ b/plugins/blog/app/models/blog/review_feedback.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++module ::Blog+ class ReviewFeedback < ActiveRecord::Base+ self.table_name = "blog_review_feedback"++ belongs_to :review+ before_validation do+ self.name = name.to_s.strip+ self.email = email.to_s.strip+ end+ validates :message, presence: true, length: { maximum: 10_000 }+ validates :name, length: { maximum: 100 }+ validates :email,+ length: {+ maximum: 254,+ },+ format: {+ with: URI::MailTo::EMAIL_REGEXP,+ allow_blank: true,+ }+ end+end++# == Schema Information+#+# Table name: blog_review_feedback+#+# id :bigint not null, primary key+# email :string(254) default(""), not null+# message :text not null+# name :string(100) default(""), not null+# created_at :datetime not null+# updated_at :datetime not null+# review_id :bigint not null+#+# Indexes+#+# idx_blog_review_feedback_review_created (review_id,created_at)+#diff --git a/plugins/blog/app/models/blog/revision.rb b/plugins/blog/app/models/blog/revision.rbnew file mode 100644index 00000000000..b522b65c4a0--- /dev/null+++ b/plugins/blog/app/models/blog/revision.rb@@ -0,0 +1,69 @@+# frozen_string_literal: true++module ::Blog+ class Revision < ActiveRecord::Base+ self.table_name = "blog_revisions"+ belongs_to :publication+ belongs_to :source_topic, class_name: "Topic"+ belongs_to :creator, class_name: "User"+ belongs_to :approver, class_name: "User", optional: true+ has_many :upload_references, as: :target, dependent: :destroy+ after_create :retain_uploads+ attr_readonly :data, :publication_id, :source_topic_id, :creator_id++ def self.capture(publication, source)+ post = source.first_post+ metadata = publication.editorial_metadata+ upload = source.image_upload+ metadata.merge(+ "title" => source.title,+ "raw" => post.raw,+ "cooked" => post.cooked,+ "author_name" => source.user&.name.presence || source.user&.username,+ "image_url" => upload && !upload.secure? ? upload.url : "",+ "tags" => source.tags.visible(Guardian.new).pluck(:name),+ )+ end++ def title+ data["title"]+ end++ def cooked+ data["cooked"]+ end++ def reading_minutes+ [(PrettyText.excerpt(cooked.to_s, 100_000, strip_tags: true).split.size / 220.0).ceil, 1].max+ end++ def raw+ data["raw"]+ end++ private++ def retain_uploads+ UploadReference.ensure_exist!(upload_ids: Upload.extract_upload_ids(raw), target: self)+ end+ end+end++# == Schema Information+#+# Table name: blog_revisions+#+# id :bigint not null, primary key+# approved_at :datetime+# data :jsonb not null+# created_at :datetime not null+# updated_at :datetime not null+# approver_id :bigint+# creator_id :bigint not null+# publication_id :bigint not null+# source_topic_id :bigint not null+#+# Indexes+#+# index_blog_revisions_on_publication_id_and_id (publication_id,id)+#diff --git a/plugins/blog/app/views/blog/articles/about.html.erb b/plugins/blog/app/views/blog/articles/about.html.erbnew file mode 100644index 00000000000..b7a7ac9f71b--- /dev/null+++ b/plugins/blog/app/views/blog/articles/about.html.erb@@ -0,0 +1 @@+<%= blog_render_template("about") %>diff --git a/plugins/blog/app/views/blog/articles/feed.rss.builder b/plugins/blog/app/views/blog/articles/feed.rss.buildernew file mode 100644index 00000000000..9b3fcc8df0d--- /dev/null+++ b/plugins/blog/app/views/blog/articles/feed.rss.builder@@ -0,0 +1,21 @@+# frozen_string_literal: true++xml.instruct!+xml.rss(version: "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom") do+ xml.channel do+ xml.title SiteSetting.blog_title+ xml.link blog_url("/")+ xml.description SiteSetting.blog_description+ xml.tag!("atom:link", href: blog_url("/feed.xml"), rel: "self", type: "application/rss+xml")+ @publications.each do |publication|+ xml.item do+ xml.title publication.article.title+ xml.link publication.url+ xml.guid "#{Discourse.base_url}/blog/publications/#{publication.topic_id}", isPermaLink: "false"+ xml.pubDate publication.published_at.rfc2822+ xml.description blog_article_html(publication.article)+ xml.comments publication.discussion_topic.url+ end+ end+ end+enddiff --git a/plugins/blog/app/views/blog/articles/index.html.erb b/plugins/blog/app/views/blog/articles/index.html.erbnew file mode 100644index 00000000000..c78951b844c--- /dev/null+++ b/plugins/blog/app/views/blog/articles/index.html.erb@@ -0,0 +1 @@+<%= blog_render_template("index") %>diff --git a/plugins/blog/app/views/blog/articles/not_found.html.erb b/plugins/blog/app/views/blog/articles/not_found.html.erbnew file mode 100644index 00000000000..a8a58d4c28b--- /dev/null+++ b/plugins/blog/app/views/blog/articles/not_found.html.erb@@ -0,0 +1 @@+<%= blog_render_template("not_found") %>diff --git a/plugins/blog/app/views/blog/articles/show.html.erb b/plugins/blog/app/views/blog/articles/show.html.erbnew file mode 100644index 00000000000..8c3bb05f806--- /dev/null+++ b/plugins/blog/app/views/blog/articles/show.html.erb@@ -0,0 +1,13 @@+<%= blog_render_template("article") %>+<% unless @preview %>+ <% discussion_closed = @topic.closed? || @topic.archived? %>+ <section id="discussion" class="blog-discussion">+ <div class="blog-discussion__heading"><h2 id="comments"><%= t('blog.discussion') %></h2><a href="<%= @topic.url %>"><%= t('blog.open_discussion') %> ↗</a></div>+ <p><%= discussion_closed ? t('blog.discussion_closed') : t('blog.discussion_description') %></p>+ <% if !discussion_closed || @topic.posts_count > 1 %>+ <p class="blog-discussion__load-error" role="status" hidden><%= t('blog.discussion_load_error') %></p>+ <div id="discourse-comments" data-discourse-url="<%= Discourse.base_url %>/" data-topic-id="<%= @topic.id %>" data-title="<%= t('blog.discussion') %>"></div>+ <% end %>+ <noscript><p><a href="<%= @topic.url %>"><%= t('blog.open_discussion') %></a></p></noscript>+ </section>+<% end %>diff --git a/plugins/blog/app/views/blog/articles/sitemap.xml.builder b/plugins/blog/app/views/blog/articles/sitemap.xml.buildernew file mode 100644index 00000000000..9f0504aa3f4--- /dev/null+++ b/plugins/blog/app/views/blog/articles/sitemap.xml.builder@@ -0,0 +1,12 @@+# frozen_string_literal: true++xml.instruct!+xml.urlset(xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9") do+ %w[/ /archive /about].each { |path| xml.url { xml.loc blog_url(path) } }+ @publications.each do |publication|+ xml.url do+ xml.loc publication.url+ xml.lastmod publication.article_updated_at.iso8601+ end+ end+enddiff --git a/plugins/blog/app/views/layouts/blog.html.erb b/plugins/blog/app/views/layouts/blog.html.erbnew file mode 100644index 00000000000..3d19cee7ac6--- /dev/null+++ b/plugins/blog/app/views/layouts/blog.html.erb@@ -0,0 +1,59 @@+<!DOCTYPE html>+<html lang="<%= I18n.locale %>">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title><%= @page_title %><%= " · #{SiteSetting.blog_title}" unless @page_title == SiteSetting.blog_title %></title>+ <meta name="description" content="<%= @description %>">+ <% if @preview || @theme_preview_token %>+ <meta name="robots" content="noindex, nofollow">+ <% else %>+ <link rel="canonical" href="<%= @canonical_url %>">+ <% end %>+ <meta property="og:title" content="<%= @page_title %>">+ <meta property="og:description" content="<%= @description %>">+ <meta property="og:site_name" content="<%= SiteSetting.blog_title %>">+ <meta property="og:url" content="<%= @canonical_url %>">+ <meta property="og:type" content="<%= @topic ? 'article' : 'website' %>">+ <meta name="twitter:card" content="<%= @topic && blog_revision_image(@article) ? 'summary_large_image' : 'summary' %>">+ <% if @topic && !@preview %>+ <% if blog_revision_image(@article) %><meta property="og:image" content="<%= blog_revision_image(@article) %>"><% end %>+ <meta property="article:published_time" content="<%= @publication.published_at&.iso8601 %>">+ <meta property="article:modified_time" content="<%= @publication.article_updated_at&.iso8601 %>">+ <script type="application/ld+json" nonce="<%= csp_nonce_placeholder %>"><%= raw ERB::Util.json_escape(blog_article_schema) %></script>+ <% end %>+ <link rel="alternate" type="application/rss+xml" title="<%= SiteSetting.blog_title %>" href="<%= blog_url('/feed.xml') %>">+ <% if SiteSetting.favicon %><link rel="icon" href="<%= ::UrlHelper.absolute(SiteSetting.favicon.url) %>"><% end %>+ <%= discourse_color_scheme_stylesheets %>+ <link rel="stylesheet" href="<%= Discourse.base_url %>/plugins/blog/blog.css">+ <link rel="stylesheet" href="<%= blog_theme_asset_url %>">+ <%= javascript_include_tag "#{Discourse.base_url}/plugins/blog/blog.js", defer: true, nonce: csp_nonce_placeholder %>+ <% if !@preview && !blog_customizations_disabled? && blog_theme["javascript"].present? %>+ <%= javascript_include_tag blog_theme_asset_url('/blog-custom.js'), defer: true, nonce: csp_nonce_placeholder, data: { blog_custom_script: true } %>+ <% end %>+ </head>+ <body+ class="blog"+ data-blog-highlight-core-url="<%= blog_url(Blog::SyntaxHighlighter.path) %>"+ data-blog-highlight-languages-url="<%= Discourse.base_url %><%= HighlightJs.path %>"+ data-blog-highlight-auto="<%= SiteSetting.autohighlight_all_code %>"+ data-blog-lightbox-close-label="<%= t('blog.lightbox.close') %>"+ data-blog-lightbox-dialog-label="<%= t('blog.lightbox.dialog') %>"+ data-blog-lightbox-open-label="<%= t('blog.lightbox.open') %>"+ data-blog-lightbox-open-with-description-label="<%= t('blog.lightbox.open_with_description', description: '__IMAGE_DESCRIPTION__') %>"+ data-blog-lightbox-original-label="<%= t('blog.lightbox.original') %>"+ data-blog-page="<%= @topic ? 'article' : (@archive ? 'archive' : action_name) %>"+ >+ <a class="blog__skip" href="#main"><%= t('blog.skip_content') %></a>+ <% if blog_customizations_disabled? %>+ <aside class="blog__preview"><%= t('blog.customizations_disabled') %></aside>+ <% end %>+ <% if @theme_preview_token %>+ <aside class="blog__preview"><strong><%= t('blog.themes.preview', name: blog_theme["name"]) %></strong> <%= t('blog.themes.preview_notice') %> <a href="<%= ::Blog::Configuration.base_url %><%= ::Blog::Configuration.relative_path(request) %>"><%= t('blog.themes.exit_preview') %></a></aside>+ <% end %>+ <% if @preview %>+ <aside class="blog__preview"><strong><%= t('blog.preview') %></strong> <%= t('blog.preview_notice') %> <a href="<%= @topic.url %>"><%= t('blog.back_to_editor') %></a></aside>+ <% end %>+ <%= blog_render_template("layout", content: yield) %>+ </body>+</html>diff --git a/plugins/blog/app/views/layouts/blog_review.html.erb b/plugins/blog/app/views/layouts/blog_review.html.erbnew file mode 100644index 00000000000..2af27dbbae6--- /dev/null+++ b/plugins/blog/app/views/layouts/blog_review.html.erb@@ -0,0 +1,40 @@+<!DOCTYPE html>+<html lang="<%= html_lang %>" class="<%= html_classes %>">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="robots" content="noindex, nofollow">+ <meta name="referrer" content="no-referrer">+ <meta name="discourse_theme_id" content="">+ <meta name="discourse_current_homepage" content="<%= current_homepage %>">+ <title><%= t("blog.review.page_title") %></title>+ <%= discourse_color_scheme_meta_tag %>+ <%= discourse_csrf_tags %>+ <%= render("layouts/plugin_js", opts: { include_official: allow_plugins?, include_unofficial: allow_third_party_plugins?, request: request, include_admin_asset: false, only: [Blog::PLUGIN_NAME] }) %>+ <script nonce="<%= csp_nonce_placeholder %>">window.EmberENV ??= {}; window.EmberENV._DEFAULT_ASYNC_OBSERVERS = true;</script>+ <%= preload_script_url ExtraLocalesController.url("main"), type_module: true %>+ <%= preload_script_url ExtraLocalesController.url("mf"), type_module: true %>+ <% if ExtraLocalesController.client_overrides_exist? %><%= preload_script_url ExtraLocalesController.url("overrides"), type_module: true %><% end %>+ <%= preload_script "js/browser-detect" %>+ <%= preload_script "vendor", type_module: true %>+ <%= module_preloads_for "discourse" %>+ <%= tag.meta id: "data-discourse-setup", data: client_side_setup_data.merge(safe_mode: "no_themes", service_worker_url: nil) %>+ <meta name="discourse/config/environment" content="<%= u discourse_config_environment %>">+ </head>+ <body class="<%= body_classes %> blog-review-page">+ <discourse-assets>+ <discourse-assets-stylesheets>+ <%= discourse_color_scheme_stylesheets %>+ <%= discourse_stylesheet_link_tag(:common, supports_rtl: true) %>+ <% Discourse.find_plugin_css_assets(include_official: true, include_unofficial: true, only: [Blog::PLUGIN_NAME], request: request).each do |asset| %>+ <%= discourse_stylesheet_link_tag(asset, supports_rtl: true) %>+ <% end %>+ </discourse-assets-stylesheets>+ <discourse-assets-json><script type="application/json" id="data-preloaded"><%= raw(preloaded_json) %></script></discourse-assets-json>+ <discourse-assets-icons></discourse-assets-icons>+ </discourse-assets>+ <noscript><p><%= t("blog.review.javascript_required") %></p></noscript>+ <section id="main"></section>+ <%= preload_script "discourse", type_module: true %>+ </body>+</html>diff --git a/plugins/blog/assets/javascripts/discourse/admin-discourse-blog-route-map.js b/plugins/blog/assets/javascripts/discourse/admin-discourse-blog-route-map.jsnew file mode 100644index 00000000000..a7d68b116c0--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/admin-discourse-blog-route-map.js@@ -0,0 +1,14 @@+export default {+ resource: "admin.adminPlugins.show",+ path: "/plugins",++ map() {+ this.route("discourse-blog-appearance", { path: "appearance" });+ this.route("discourse-blog-identity", { path: "identity" });+ this.route("discourse-blog-themes", { path: "themes" }, function () {+ this.route("new");+ this.route("import", { path: "import/new" });+ this.route("edit", { path: "/:id/edit" });+ });+ },+};diff --git a/plugins/blog/assets/javascripts/discourse/components/blog-dashboard.gjs b/plugins/blog/assets/javascripts/discourse/components/blog-dashboard.gjsnew file mode 100644index 00000000000..66ef0221b96--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/components/blog-dashboard.gjs@@ -0,0 +1,303 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import DiscourseURL from "discourse/lib/url";+import Category from "discourse/models/category";+import DButton from "discourse/ui-kit/d-button";+import DEmptyState from "discourse/ui-kit/d-empty-state";+import DFlashMessage from "discourse/ui-kit/d-flash-message";+import DPageHeader from "discourse/ui-kit/d-page-header";+import { i18n } from "discourse-i18n";++export default class BlogDashboard extends Component {+ @service composer;+ @service currentUser;+ @service siteSettings;++ @tracked filter = "all";+ @tracked loading = false;+ @tracked page = 0;+ @tracked query = "";+ @tracked _data;++ get data() {+ return this._data || this.args.model;+ }++ get searchData() {+ return { q: this.query };+ }++ get topics() {+ return this.data?.topics || [];+ }++ @action+ async newDraft() {+ const category = Category.findById(this.siteSettings.blog_drafts_category);+ await this.composer.openNewTopic({ category });+ }++ @action+ async setFilter(filter) {+ if (this.loading) {+ return;+ }+ const previousFilter = this.filter;+ this.filter = filter;+ if (!(await this.refresh())) {+ this.filter = previousFilter;+ }+ }++ @action+ async search(data) {+ if (this.loading) {+ return;+ }+ const previousQuery = this.query;+ this.query = data.q?.trim() || "";+ if (!(await this.refresh())) {+ this.query = previousQuery;+ }+ }++ @action+ async refresh() {+ if (this.loading) {+ return;+ }+ this.loading = true;+ try {+ this._data = await ajax("/blog-editor.json", {+ data: { filter: this.filter, q: this.query },+ });+ this.page = 0;+ return true;+ } catch (error) {+ popupAjaxError(error);+ return false;+ } finally {+ this.loading = false;+ }+ }++ @action+ async loadMore() {+ if (this.loading) {+ return;+ }+ this.loading = true;+ try {+ const data = await ajax("/blog-editor.json", {+ data: { page: this.page + 1, filter: this.filter, q: this.query },+ });+ this.page += 1;+ this._data = {+ ...data,+ topics: [+ ...new Map(+ [...this.data.topics, ...data.topics].map((topic) => [+ topic.id,+ topic,+ ])+ ).values(),+ ],+ };+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.loading = false;+ }+ }++ @action+ async editPrivately(topic) {+ try {+ const publication = await ajax(+ `/blog-editor/publications/${topic.id}/prepare.json`,+ { type: "POST" }+ );+ DiscourseURL.routeTo(publication.source_url);+ } catch (error) {+ popupAjaxError(error);+ }+ }++ <template>+ <div class="blog-dashboard" ...attributes>+ <DPageHeader+ @collapseActionsOnMobile={{false}}+ @descriptionLabel={{i18n "blog.editor_description"}}+ @titleLabel={{i18n "blog.editor_title"}}+ >+ <:actions>+ <DButton+ class="btn-primary"+ @action={{this.newDraft}}+ @disabled={{this.data.error}}+ @icon="pen-to-square"+ @label="blog.new_draft"+ />+ </:actions>+ </DPageHeader>+ {{#if this.data.error}}+ <DFlashMessage @flash={{this.data.error}} @type="warning" />+ <a href="/admin/site_settings/category/plugins?filter=blog_">{{i18n+ "blog.settings"+ }}</a>+ {{/if}}+ <div class="blog-dashboard__toolbar">+ <div class="blog-dashboard__filters">+ <DButton+ class="btn-default"+ @action={{fn this.setFilter "all"}}+ @ariaPressed={{eq this.filter "all"}}+ @disabled={{this.loading}}+ @label="blog.all"+ />+ <DButton+ class="btn-default"+ @action={{fn this.setFilter "drafts"}}+ @ariaPressed={{eq this.filter "drafts"}}+ @disabled={{this.loading}}+ @label="blog.drafts"+ />+ <DButton+ class="btn-default"+ @action={{fn this.setFilter "published"}}+ @ariaPressed={{eq this.filter "published"}}+ @disabled={{this.loading}}+ @label="blog.published"+ />+ <DButton+ class="btn-default"+ @action={{fn this.setFilter "unpublished"}}+ @ariaPressed={{eq this.filter "unpublished"}}+ @disabled={{this.loading}}+ @label="blog.not_published"+ />+ </div>+ <div class="blog-dashboard__links">+ {{#if this.currentUser.admin}}<a+ href="/admin/plugins/blog/themes"+ >{{i18n "blog.appearance_link"}}</a>{{/if}}+ <a+ href={{this.data.blog_url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.visit_blog"}} ↗</a>+ <DButton+ class="btn-flat"+ @action={{this.refresh}}+ @disabled={{this.loading}}+ @icon="arrows-rotate"+ @title="blog.refresh"+ />+ </div>+ </div>+ <Form+ class="blog-dashboard__search"+ @data={{this.searchData}}+ @onSubmit={{this.search}}+ as |form|+ >+ <form.Field+ @format="full"+ @name="q"+ @showOptional={{false}}+ @title={{i18n "blog.editor_search"}}+ @type="input"+ as |field|+ >+ <field.Control+ maxlength="100"+ placeholder={{i18n "blog.editor_search_hint"}}+ @type="search"+ />+ </form.Field>+ <form.Actions>+ <form.Submit+ @disabled={{this.loading}}+ @label="blog.search_articles"+ />+ </form.Actions>+ </Form>+ <p class="blog-dashboard__hint">{{i18n "blog.editor_pagination_hint"}}</p>+ <p class="blog-dashboard__hint">{{i18n "blog.drafts_hint"}}</p>+ {{#each this.topics as |topic|}}+ <article class="blog-dashboard__entry" data-topic-id={{topic.id}}>+ <div class="blog-dashboard__entry-content">+ <div class="blog-dashboard__statuses">+ <span class="blog-dashboard__status">{{#if topic.draft}}{{i18n+ "blog.private_draft"+ }}{{else if topic.live}}{{i18n+ "blog.published"+ }}{{else}}{{i18n "blog.not_published"}}{{/if}}</span>+ {{#if topic.draft_correction}}<span+ class="blog-dashboard__correction"+ >{{i18n "blog.draft_correction"}}</span>{{/if}}+ </div>+ {{#if topic.live}}+ <h2><a href={{topic.url}}>{{or+ topic.public_title+ topic.title+ }}</a></h2>+ {{#if topic.public_excerpt}}<p>{{topic.public_excerpt}}</p>{{/if}}+ <span class="blog-dashboard__path">{{or+ topic.public_path+ topic.path+ }}</span>+ {{else}}+ <h2><a href={{topic.topic_url}}>{{topic.title}}</a></h2>+ {{#if topic.excerpt}}<p>{{topic.excerpt}}</p>{{/if}}+ <span class="blog-dashboard__path">{{topic.path}}</span>+ {{/if}}+ </div>+ <div class="blog-dashboard__entry-actions">+ {{#if topic.live}}+ <a href={{topic.discussion_url}}>{{i18n+ "blog.public_discussion"+ }}</a>+ {{else}}+ <a+ href={{topic.preview_url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.preview"}}</a>+ {{/if}}+ {{#if topic.source_url}}+ <a+ class="btn btn-default blog-dashboard__edit-private"+ href={{topic.source_url}}+ >{{i18n "blog.open_draft"}}</a>+ {{else}}+ <DButton+ class="blog-dashboard__edit-private btn-default"+ @action={{fn this.editPrivately topic}}+ @label="blog.edit_privately"+ />+ {{/if}}+ </div>+ </article>+ {{else}}+ <DEmptyState+ @body={{i18n "blog.editor_no_results_hint"}}+ @title={{i18n "blog.editor_no_results"}}+ />+ {{/each}}+ {{#if this.data.more}}<DButton+ class="btn-default"+ data-blog-load-more+ @action={{this.loadMore}}+ @disabled={{this.loading}}+ @label="blog.load_more"+ />{{/if}}+ </div>+ </template>+}diff --git a/plugins/blog/assets/javascripts/discourse/components/blog-post-summary.gjs b/plugins/blog/assets/javascripts/discourse/components/blog-post-summary.gjsnew file mode 100644index 00000000000..45bbb5bca61--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/components/blog-post-summary.gjs@@ -0,0 +1,82 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { uniqueId } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import EmbedMode from "discourse/lib/embed-mode";+import DButton from "discourse/ui-kit/d-button";+import { i18n } from "discourse-i18n";++const EXPANSION_KEY = "discourse-blog-article-expanded";++export default class BlogPostSummary extends Component {+ @service router;+ @service siteSettings;++ @tracked _expanded = false;++ get article() {+ return this.args.outletArgs.post.blog_article;+ }++ get expanded() {+ return (+ this.args.outletArgs.decoratorState?.get(EXPANSION_KEY) ?? this._expanded+ );+ }++ get showSummary() {+ const params = new URLSearchParams(this.router.currentURL?.split("?")[1]);+ return (+ this.siteSettings.blog_enabled &&+ !EmbedMode.enabled &&+ this.args.outletArgs.post.post_number === 1 &&+ this.article &&+ !params.has("search") &&+ !params.has("context") &&+ !window.location.hash.startsWith("#p-")+ );+ }++ @action+ toggleExpanded() {+ this._expanded = !this.expanded;+ this.args.outletArgs.decoratorState?.set(EXPANSION_KEY, this._expanded);+ }++ <template>+ {{#let (uniqueId) as |contentId|}}+ {{#if this.showSummary}}+ <div class="blog-post-summary">+ <p class="blog-post-summary__label">{{i18n+ "blog.article_summary.from_blog"+ blog=this.article.blog_name+ }}</p>+ {{#unless this.expanded}}+ <p class="blog-post-summary__excerpt">{{this.article.excerpt}}</p>+ {{/unless}}+ <div class="blog-post-summary__actions">+ <a href={{this.article.url}}>{{i18n "blog.article_summary.read"}}+ ↗</a>+ <DButton+ aria-controls={{contentId}}+ aria-expanded={{if this.expanded "true" "false"}}+ class="btn-default"+ @action={{this.toggleExpanded}}+ @label={{if+ this.expanded+ "blog.article_summary.collapse"+ "blog.article_summary.expand"+ }}+ />+ </div>+ </div>+ <div hidden={{unless this.expanded true}} id={{contentId}}>+ {{#if this.expanded}}{{yield}}{{/if}}+ </div>+ {{else}}+ {{yield}}+ {{/if}}+ {{/let}}+ </template>+}diff --git a/plugins/blog/assets/javascripts/discourse/components/blog-publication-panel.gjs b/plugins/blog/assets/javascripts/discourse/components/blog-publication-panel.gjsnew file mode 100644index 00000000000..dc8e2bb275b--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/components/blog-publication-panel.gjs@@ -0,0 +1,967 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn, uniqueId } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import Form from "discourse/components/form";+import DMenu from "discourse/float-kit/components/d-menu";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import EmbedMode from "discourse/lib/embed-mode";+import { longDate } from "discourse/lib/formatter";+import DiscourseURL from "discourse/lib/url";+import DButton from "discourse/ui-kit/d-button";+import DComboButton from "discourse/ui-kit/d-combo-button";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";+import DFlashMessage from "discourse/ui-kit/d-flash-message";+import DInterpolatedTranslation from "discourse/ui-kit/d-interpolated-translation";+import dAgeWithTooltip from "discourse/ui-kit/helpers/d-age-with-tooltip";+import { i18n } from "discourse-i18n";+import BlogReviews from "./modal/blog-reviews.gjs";+import BlogSchedule from "./modal/blog-schedule.gjs";++export default class BlogPublicationPanel extends Component {+ @service appEvents;+ @service dialog;+ @service modal;+ @service toasts;++ @tracked busy = false;+ @tracked diff;+ @tracked diffOpen = false;+ @tracked feedback;+ @tracked feedbackMore = false;+ @tracked feedbackOpen = false;+ @tracked settingsOpen = false;+ // The settings form keeps its own snapshot so state changes do not discard edits in progress.+ @tracked settingsData;+ #feedbackPage = 0;+ #form;+ #menu;+ #replaced;+ @tracked _publication;++ constructor() {+ super(...arguments);+ this.appEvents.on("composer:edited-post", this, this.refresh);+ this.settingsData = this.#settingsSnapshot();+ }++ willDestroy() {+ super.willDestroy(...arguments);+ this.appEvents.off("composer:edited-post", this, this.refresh);+ }++ get publication() {+ // A topic reload replaces the serialized entry, which supersedes any locally applied mutation.+ const override = this._publication;+ const base = this.args.outletArgs.model.blog_publication;+ return base && base === this.#replaced ? override : base;+ }++ get visible() {+ return !!this.publication && !EmbedMode.enabled;+ }++ get isDiscussion() {+ return this.publication.role === "discussion";+ }++ get status() {+ return this.publication.status;+ }++ get statusClass() {+ return `--${this.status.replaceAll("_", "-")}`;+ }++ get badge() {+ return i18n(`blog.panel.badge.${this.status}`);+ }++ get headline() {+ if (this.status === "scheduled") {+ return i18n("blog.panel.headline.scheduled", {+ date: longDate(new Date(this.publication.scheduled_at)),+ });+ }+ return i18n(`blog.panel.headline.${this.status}`);+ }++ get displayUrl() {+ return this.publication.url.replace(/^https?:\/\//, "");+ }++ get publishedDate() {+ return longDate(+ new Date(+ this.publication.last_published_at || this.publication.published_at+ )+ );+ }++ get changedFields() {+ return this.publication.changes+ .map((field) => i18n(`blog.panel.change.${field}`))+ .join(", ");+ }++ get hasPendingChanges() {+ return this.publication.published && this.publication.changes.length > 0;+ }++ get canShowDiff() {+ return (+ this.hasPendingChanges &&+ this.publication.changes.some((field) =>+ ["title", "body"].includes(field)+ )+ );+ }++ get pendingRevision() {+ const submitted = this.publication.submitted_revision;+ if (!submitted || submitted.id === this.publication.published_revision_id) {+ return null;+ }+ return submitted;+ }++ get hasReviews() {+ return (+ this.publication.review_feedback_count > 0 ||+ this.publication.active_review_links > 0+ );+ }++ get canRelease() {+ return !this.publication.published || this.hasPendingChanges;+ }++ get primaryLabel() {+ if (!this.publication.can_publish) {+ return "blog.panel.submit";+ }+ return this.hasPendingChanges+ ? "blog.panel.publish_correction"+ : "blog.panel.publish";+ }++ @action+ registerForm(api) {+ this.#form = api;+ }++ @action+ registerMenu(api) {+ this.#menu = api;+ }++ @action+ toggleSettings() {+ this.settingsOpen = !this.settingsOpen;+ }++ @action+ async toggleDiff() {+ if (!this.diffOpen && !this.diff) {+ this.busy = true;+ try {+ this.diff = await ajax(this.#url("/changes"));+ } catch (error) {+ popupAjaxError(error);+ return;+ } finally {+ this.busy = false;+ }+ }+ this.diffOpen = !this.diffOpen;+ }++ @action+ async toggleFeedback() {+ if (!this.feedbackOpen && !this.feedback) {+ if (!(await this.#loadFeedback(0))) {+ return;+ }+ }+ this.feedbackOpen = !this.feedbackOpen;+ }++ @action+ loadMoreFeedback() {+ return this.#loadFeedback(this.#feedbackPage + 1);+ }++ @action+ async refresh() {+ if (!this.publication) {+ return;+ }+ try {+ this.#apply(await ajax(this.#url("")));+ } catch (error) {+ popupAjaxError(error);+ }+ }++ @action+ async publish() {+ await this.#menu?.close();+ const correction = this.hasPendingChanges;+ this.dialog.confirm({+ message: i18n(+ correction+ ? "blog.panel.publish_correction_confirm"+ : "blog.panel.publish_confirm",+ { title: this.publication.title }+ ),+ didConfirm: async () => {+ if (await this.#mutate("/publish")) {+ this.#announcePublished();+ }+ },+ });+ }++ @action+ async publishRevision(revision) {+ if (this.publication.approved_revision?.id !== revision.id) {+ if (!(await this.#mutate("/approve", { revision_id: revision.id }))) {+ return;+ }+ }+ if (await this.#mutate("/publish", { revision_id: revision.id })) {+ this.#announcePublished();+ }+ }++ @action+ async submit() {+ await this.#menu?.close();+ await this.#mutate("/submit");+ }++ @action+ async openSchedule() {+ await this.#menu?.close();+ this.modal.show(BlogSchedule, { model: { onSchedule: this.schedule } });+ }++ @action+ async schedule(scheduledAt) {+ // Scheduling freezes the draft as it is now, so it goes through submission and approval first.+ const submitted = await this.#mutate("/submit");+ if (!submitted) {+ return false;+ }+ const revisionId = submitted.submitted_revision.id;+ if (!(await this.#mutate("/approve", { revision_id: revisionId }))) {+ return false;+ }+ return this.#mutate("/schedule", {+ revision_id: revisionId,+ scheduled_at: new Date(scheduledAt).toISOString(),+ });+ }++ @action+ cancelSchedule() {+ return this.#mutate("/schedule", {}, "DELETE");+ }++ @action+ async unpublish() {+ await this.#menu?.close();+ this.dialog.confirm({+ message: i18n("blog.unpublish_confirm"),+ didConfirm: () => this.#mutate("", {}, "DELETE"),+ });+ }++ @action+ async saveSettings(data) {+ const current = this.publication.published_at;+ const result = await this.#mutate(+ "",+ {+ publication: {+ ...data,+ published_at:+ data.published_at === current?.slice(0, 10)+ ? current+ : data.published_at || null,+ },+ },+ "PUT"+ );+ if (result) {+ this.#form.commit();+ }+ }++ @action+ shareForReview() {+ const open = async () => {+ await this.modal.show(BlogReviews, {+ model: { topicId: this.publication.source_topic_id, draft: true },+ });+ // Links may have been issued or revoked while the modal was open.+ await this.refresh();+ };+ if (this.#form?.isDirty) {+ this.dialog.confirm({+ message: i18n("blog.review.discard_metadata"),+ didConfirm: open,+ });+ } else {+ open();+ }+ }++ @action+ async editPrivately() {+ let url = this.publication.source_url;+ if (!url) {+ const result = await this.#mutate("/prepare");+ if (!result) {+ return;+ }+ url = result.source_url;+ }+ DiscourseURL.routeTo(url);+ }++ #url(suffix) {+ return `/blog-editor/publications/${this.publication.id}${suffix}.json`;+ }++ async #loadFeedback(page) {+ this.busy = true;+ try {+ const result = await ajax(+ `/blog-editor/publications/${this.publication.source_topic_id}/feedback.json`,+ { data: { page } }+ );+ this.feedback = page+ ? [...this.feedback, ...result.feedback]+ : result.feedback;+ this.feedbackMore = result.more;+ this.#feedbackPage = page;+ return true;+ } catch (error) {+ popupAjaxError(error);+ return false;+ } finally {+ this.busy = false;+ }+ }++ async #mutate(suffix, data = {}, type = "POST") {+ this.busy = true;+ try {+ const entry =+ (await ajax(this.#url(suffix), { type, data })) ||+ (await ajax(this.#url("")));+ this.#apply(entry);+ return entry;+ } catch (error) {+ popupAjaxError(error);+ return false;+ } finally {+ this.busy = false;+ }+ }++ #apply(entry) {+ // The editor endpoints do not know which topic is being viewed, so the role is kept.+ const { role } = this.publication;+ this.#replaced = this.args.outletArgs.model.blog_publication;+ this._publication = { ...entry, role };+ this.diff = null;+ this.diffOpen = false;+ this.feedback = null;+ this.feedbackOpen = false;+ if (!this.#form?.isDirty) {+ this.settingsData = this.#settingsSnapshot();+ }+ }++ #settingsSnapshot() {+ return {+ path: this.publication?.path,+ excerpt: this.publication?.excerpt || "",+ featured: this.publication?.featured,+ published_at: this.publication?.published_at?.slice(0, 10) || "",+ };+ }++ #announcePublished() {+ this.toasts.success({+ data: {+ message: i18n("blog.panel.published", {+ id: this.publication.published_revision_id,+ }),+ },+ });+ }++ <template>+ {{#if this.visible}}+ {{#if this.isDiscussion}}+ <div class="blog-discussion-banner">+ <span+ class="blog-discussion-banner__badge+ {{if this.publication.live '--live' '--unpublished'}}"+ >{{i18n+ (if+ this.publication.live+ "blog.panel.discussion.live"+ "blog.panel.discussion.not_live"+ )+ }}</span>+ <p class="blog-discussion-banner__text">+ {{#if this.publication.live}}+ <DInterpolatedTranslation+ @key="blog.panel.discussion.intro"+ as |Placeholder|+ >+ <Placeholder @name="article">+ <a+ href={{this.publication.url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{this.displayUrl}} ↗</a>+ </Placeholder>+ </DInterpolatedTranslation>+ {{else}}+ {{i18n "blog.panel.discussion.intro_not_live"}}+ {{/if}}+ {{#if this.publication.source_url}}+ <DInterpolatedTranslation+ @key={{if+ this.publication.draft_correction+ "blog.panel.discussion.working_copy_pending"+ "blog.panel.discussion.working_copy"+ }}+ as |Placeholder|+ >+ <Placeholder @name="link">+ <a href={{this.publication.source_url}}>{{i18n+ "blog.panel.discussion.working_copy_link"+ }}</a>+ </Placeholder>+ </DInterpolatedTranslation>+ {{else}}+ {{i18n "blog.panel.discussion.no_working_copy"}}+ {{/if}}+ </p>+ <DButton+ class="btn-default blog-discussion-banner__edit"+ @action={{this.editPrivately}}+ @disabled={{this.busy}}+ @label="blog.panel.discussion.edit_privately"+ />+ </div>+ {{else}}+ {{#let (uniqueId) as |settingsId|}}+ <section+ aria-label={{i18n "blog.panel.aria_label"}}+ class="blog-publication-panel {{this.statusClass}}"+ >+ <div class="blog-publication-panel__summary">+ <div class="blog-publication-panel__status">+ <span+ class="blog-publication-panel__badge {{this.statusClass}}"+ >{{this.badge}}</span>+ <span+ class="blog-publication-panel__headline"+ >{{this.headline}}</span>+ </div>+ <p class="blog-publication-panel__meta">+ {{#if (eq this.status "draft")}}+ <DInterpolatedTranslation+ @key="blog.panel.will_publish_to"+ as |Placeholder|+ >+ <Placeholder @name="url">+ <a+ href={{this.publication.url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{this.displayUrl}}</a>+ </Placeholder>+ </DInterpolatedTranslation>+ {{#if this.publication.draft_updated_at}}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ <DInterpolatedTranslation+ @key="blog.panel.saved"+ as |Placeholder|+ >+ <Placeholder @name="age">{{dAgeWithTooltip+ this.publication.draft_updated_at+ }}</Placeholder>+ </DInterpolatedTranslation>+ {{/if}}+ {{else if (eq this.status "scheduled")}}+ {{i18n+ "blog.panel.scheduled_revision"+ id=this.publication.scheduled_revision.id+ user=this.publication.scheduled_revision.approved_by+ }}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ {{i18n "blog.panel.scheduled_notice"}}+ {{else if (eq this.status "unpublished")}}+ {{i18n "blog.panel.last_published" date=this.publishedDate}}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ {{i18n "blog.panel.unpublished_notice"}}+ {{else}}+ {{i18n+ "blog.panel.published_as"+ date=this.publishedDate+ id=this.publication.published_revision_id+ }}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ <a+ class="blog-publication-panel__view-live"+ href={{this.publication.url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.panel.view_live"}}</a>+ {{#if this.publication.edits_since_publish}}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ {{i18n+ "blog.panel.edits_since"+ count=this.publication.edits_since_publish+ }}+ {{/if}}+ {{/if}}+ </p>+ </div>++ <div class="blog-publication-panel__actions">+ {{#if (eq this.status "scheduled")}}+ <a+ class="btn btn-default blog-publication-panel__preview"+ href={{this.publication.scheduled_revision.preview_url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n+ "blog.panel.preview_revision"+ id=this.publication.scheduled_revision.id+ }}</a>+ {{#if this.publication.can_publish}}+ <DButton+ class="btn-default blog-publication-panel__cancel-schedule"+ @action={{this.cancelSchedule}}+ @disabled={{this.busy}}+ @label="blog.panel.cancel_schedule"+ />+ <DButton+ class="btn-primary blog-publication-panel__publish-now"+ @action={{fn+ this.publishRevision+ this.publication.scheduled_revision+ }}+ @disabled={{this.busy}}+ @label="blog.panel.publish_now"+ />+ {{/if}}+ {{else}}+ <a+ class="btn btn-default blog-publication-panel__preview"+ href={{this.publication.preview_url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.panel.preview"}}</a>+ {{#if this.publication.source_topic_id}}+ <DButton+ class="btn-default blog-publication-panel__reviews"+ @action={{this.shareForReview}}+ @disabled={{this.busy}}+ @label="blog.panel.share_for_review"+ />+ {{/if}}+ {{#if this.canRelease}}+ <DComboButton+ class="blog-publication-panel__primary"+ @btnTypeClass="btn-primary"+ @hasMenu={{this.publication.can_publish}}+ as |combo|+ >+ <combo.Button+ class="blog-publication-panel__publish"+ @action={{if+ this.publication.can_publish+ this.publish+ this.submit+ }}+ @disabled={{this.busy}}+ @label={{this.primaryLabel}}+ />+ <combo.Menu+ class="blog-publication-panel__menu-trigger"+ @identifier="blog-publish-menu"+ @modalForMobile={{true}}+ @onRegisterApi={{this.registerMenu}}+ @title={{i18n "blog.panel.more_options"}}+ >+ <DDropdownMenu as |dropdown|>+ <dropdown.item>+ <DButton+ class="btn-transparent --with-description blog-publication-panel__menu-item blog-publication-panel__menu-publish"+ @action={{this.publish}}+ >+ <span+ class="blog-publication-panel__menu-label"+ >{{i18n "blog.panel.publish_now"}}</span>+ <span+ class="blog-publication-panel__menu-hint"+ >{{i18n+ (if+ this.hasPendingChanges+ "blog.panel.publish_correction_hint"+ "blog.panel.publish_now_hint"+ )+ }}</span>+ </DButton>+ </dropdown.item>+ <dropdown.item>+ <DButton+ class="btn-transparent --with-description blog-publication-panel__menu-item blog-publication-panel__menu-schedule"+ @action={{this.openSchedule}}+ >+ <span+ class="blog-publication-panel__menu-label"+ >{{i18n "blog.panel.schedule"}}</span>+ <span+ class="blog-publication-panel__menu-hint"+ >{{i18n "blog.panel.schedule_hint"}}</span>+ </DButton>+ </dropdown.item>+ <dropdown.item>+ <DButton+ class="btn-transparent --with-description blog-publication-panel__menu-item blog-publication-panel__menu-submit"+ @action={{this.submit}}+ >+ <span+ class="blog-publication-panel__menu-label"+ >{{i18n "blog.panel.submit"}}</span>+ <span+ class="blog-publication-panel__menu-hint"+ >{{i18n "blog.panel.submit_hint"}}</span>+ </DButton>+ </dropdown.item>+ {{#if this.publication.published}}+ <dropdown.divider />+ <dropdown.item>+ <DButton+ class="btn-transparent --with-description blog-publication-panel__menu-item blog-publication-panel__unpublish"+ @action={{this.unpublish}}+ >+ <span+ class="blog-publication-panel__menu-label"+ >{{i18n "blog.unpublish"}}</span>+ <span+ class="blog-publication-panel__menu-hint"+ >{{i18n "blog.panel.unpublish_hint"}}</span>+ </DButton>+ </dropdown.item>+ {{/if}}+ </DDropdownMenu>+ </combo.Menu>+ </DComboButton>+ {{else if this.publication.can_publish}}+ {{! Nothing differs from the live article, so only withdrawal is offered. }}+ <DMenu+ class="btn-default blog-publication-panel__options"+ @disabled={{this.busy}}+ @icon="chevron-down"+ @identifier="blog-publish-menu"+ @label={{i18n "blog.panel.options"}}+ @modalForMobile={{true}}+ @onRegisterApi={{this.registerMenu}}+ >+ <:content>+ <DDropdownMenu as |dropdown|>+ <dropdown.item>+ <DButton+ class="btn-transparent --with-description blog-publication-panel__menu-item blog-publication-panel__unpublish"+ @action={{this.unpublish}}+ >+ <span+ class="blog-publication-panel__menu-label"+ >{{i18n "blog.unpublish"}}</span>+ <span+ class="blog-publication-panel__menu-hint"+ >{{i18n "blog.panel.unpublish_hint"}}</span>+ </DButton>+ </dropdown.item>+ </DDropdownMenu>+ </:content>+ </DMenu>+ {{/if}}+ {{/if}}+ </div>++ {{#if this.pendingRevision}}+ <div class="blog-publication-panel__pending">+ <span>{{i18n+ "blog.panel.submitted"+ id=this.pendingRevision.id+ }}</span>+ <a+ href={{this.pendingRevision.preview_url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n+ "blog.panel.preview_revision"+ id=this.pendingRevision.id+ }}</a>+ {{#if this.publication.can_publish}}+ <DButton+ class="btn-default blog-publication-panel__approve"+ @action={{fn this.publishRevision this.pendingRevision}}+ @disabled={{this.busy}}+ @translatedLabel={{i18n+ "blog.panel.approve_and_publish"+ id=this.pendingRevision.id+ }}+ />+ {{/if}}+ </div>+ {{/if}}++ {{#if this.hasPendingChanges}}+ <div class="blog-publication-panel__changes">+ <div class="blog-publication-panel__changes-header">+ <span class="blog-publication-panel__changes-title">{{i18n+ "blog.panel.changes_title"+ }}</span>+ {{#if this.canShowDiff}}+ <DButton+ aria-expanded={{if this.diffOpen "true" "false"}}+ class="btn-flat blog-publication-panel__toggle-diff"+ @action={{this.toggleDiff}}+ @disabled={{this.busy}}+ @label={{if+ this.diffOpen+ "blog.panel.hide_diff"+ "blog.panel.show_diff"+ }}+ />+ {{/if}}+ </div>+ <p class="blog-publication-panel__changed">{{i18n+ "blog.panel.changed"+ fields=this.changedFields+ }}</p>+ {{#if this.diffOpen}}+ {{#if this.diff.diff_error}}+ <p class="blog-publication-panel__diff-error">{{i18n+ "blog.panel.diff_error"+ }}</p>+ {{else}}+ {{#if this.diff.title_diff_html}}+ <div class="blog-publication-panel__diff --title">+ {{trustHTML this.diff.title_diff_html}}+ </div>+ {{/if}}+ <div class="blog-publication-panel__diff">+ {{trustHTML this.diff.diff_html}}+ </div>+ {{/if}}+ {{/if}}+ </div>+ {{/if}}++ {{#if this.hasReviews}}+ <div class="blog-publication-panel__reviews">+ <div class="blog-publication-panel__reviews-header">+ <span class="blog-publication-panel__reviews-title">+ {{#if this.publication.review_feedback_count}}+ {{i18n+ "blog.panel.feedback.count"+ count=this.publication.review_feedback_count+ }}+ {{else}}+ {{i18n "blog.panel.feedback.none"}}+ {{/if}}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ <span class="blog-publication-panel__reviews-links">{{#if+ this.publication.active_review_links+ }}{{i18n+ "blog.panel.feedback.active_links"+ count=this.publication.active_review_links+ }}{{else}}{{i18n+ "blog.panel.feedback.no_active_links"+ }}{{/if}}</span>+ </span>+ <span class="blog-publication-panel__reviews-actions">+ {{#if this.publication.review_feedback_count}}+ <DButton+ aria-expanded={{if this.feedbackOpen "true" "false"}}+ class="btn-flat blog-publication-panel__toggle-feedback"+ @action={{this.toggleFeedback}}+ @disabled={{this.busy}}+ @label={{if+ this.feedbackOpen+ "blog.panel.feedback.hide"+ "blog.panel.feedback.show"+ }}+ />+ {{/if}}+ <DButton+ class="btn-flat blog-publication-panel__manage-reviews"+ @action={{this.shareForReview}}+ @disabled={{this.busy}}+ @label="blog.panel.feedback.manage_links"+ />+ </span>+ </div>+ {{#if this.feedbackOpen}}+ <p class="blog-publication-panel__feedback-notice">{{i18n+ "blog.review.unverified"+ }}</p>+ <ul class="blog-publication-panel__feedback">+ {{#each this.feedback key="id" as |entry|}}+ <li class="blog-publication-panel__feedback-entry">+ <div class="blog-publication-panel__feedback-meta">+ <strong>{{or+ entry.name+ (i18n "blog.review.anonymous")+ }}</strong>+ {{#if entry.email}}+ <span+ class="blog-publication-panel__feedback-email"+ >{{entry.email}}</span>+ {{/if}}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ {{dAgeWithTooltip entry.created_at}}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>+ <span+ class="blog-publication-panel__feedback-review"+ >{{#if entry.review.label}}{{entry.review.label}}+ <span+ aria-hidden="true"+ class="blog-publication-panel__sep"+ >·</span>{{/if}}{{i18n+ "blog.review.version"+ version=entry.review.post_version+ }}</span>+ </div>+ <p+ class="blog-publication-panel__feedback-message"+ >{{entry.message}}</p>+ </li>+ {{/each}}+ </ul>+ {{#if this.feedbackMore}}+ <DButton+ class="btn-flat blog-publication-panel__more-feedback"+ @action={{this.loadMoreFeedback}}+ @disabled={{this.busy}}+ @label="blog.load_more"+ />+ {{/if}}+ {{/if}}+ </div>+ {{/if}}++ {{#if this.publication.schedule_error}}+ <div class="blog-publication-panel__error">+ <DFlashMessage+ @flash={{this.publication.schedule_error}}+ @type="error"+ />+ </div>+ {{/if}}++ <div class="blog-publication-panel__settings">+ <DButton+ aria-controls={{settingsId}}+ aria-expanded={{if this.settingsOpen "true" "false"}}+ class="btn-flat blog-publication-panel__settings-toggle"+ @action={{this.toggleSettings}}+ @icon={{if this.settingsOpen "chevron-down" "chevron-right"}}+ @label="blog.panel.settings"+ >+ <span class="blog-publication-panel__settings-hint">{{i18n+ "blog.panel.settings_hint"+ }}</span>+ </DButton>+ <div hidden={{unless this.settingsOpen true}} id={{settingsId}}>+ <Form+ class="blog-publication-panel__form"+ @data={{this.settingsData}}+ @onRegisterApi={{this.registerForm}}+ @onSubmit={{this.saveSettings}}+ as |form|+ >+ <form.Field+ @description={{i18n "blog.path_hint"}}+ @format="full"+ @name="path"+ @title={{i18n "blog.path"}}+ @type="input"+ @validation="required"+ as |field|+ ><field.Control maxlength="240" /></form.Field>+ <form.Field+ @description={{i18n "blog.excerpt_hint"}}+ @format="full"+ @name="excerpt"+ @title={{i18n "blog.excerpt"}}+ @type="textarea"+ as |field|+ ><field.Control maxlength="1000" @rows={{3}} /></form.Field>+ <form.Field+ @description={{i18n "blog.date_hint"}}+ @name="published_at"+ @title={{i18n "blog.date"}}+ @type="input"+ as |field|+ ><field.Control @type="date" /></form.Field>+ <form.Field+ @name="featured"+ @title={{i18n "blog.featured"}}+ @type="checkbox"+ as |field|+ ><field.Control /></form.Field>+ <form.Actions>+ <form.Submit @disabled={{this.busy}} @label="blog.save" />+ </form.Actions>+ </Form>+ </div>+ </div>+ </section>+ {{/let}}+ {{/if}}+ {{/if}}+ </template>+}diff --git a/plugins/blog/assets/javascripts/discourse/components/blog-review.gjs b/plugins/blog/assets/javascripts/discourse/components/blog-review.gjsnew file mode 100644index 00000000000..91a42f619e1--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/components/blog-review.gjs@@ -0,0 +1,107 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { trustHTML } from "@ember/template";+import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import DFlashMessage from "discourse/ui-kit/d-flash-message";+import { i18n } from "discourse-i18n";++export default class BlogReview extends Component {+ @tracked submitted = false;+ @tracked unavailable = false;++ get expiresAt() {+ return new Date(this.args.review.expires_at).toLocaleString();+ }++ get article() {+ // The server freezes and sanitizes this HTML when the editor issues the grant.+ return trustHTML(this.args.review.cooked);+ }++ @action+ async submit(data) {+ try {+ await ajax("/blog/review/feedback.json", {+ type: "POST",+ data: { review_token: this.args.review.token, feedback: data },+ });+ this.submitted = true;+ } catch (error) {+ if ([403, 404].includes(error.jqXHR?.status)) {+ this.unavailable = true;+ } else {+ popupAjaxError(error);+ throw error;+ }+ }+ }++ <template>+ <section class="blog-review">+ {{#if this.unavailable}}+ <DFlashMessage+ @flash={{i18n "blog.review.unavailable"}}+ @type="error"+ />+ {{else}}+ <p class="blog-review__notice">{{i18n+ "blog.review.reader_notice"+ [email protected]_version+ }}+ {{i18n "blog.review.expires" date=this.expiresAt}}</p>+ <article>+ <h1>{{@review.title}}</h1>+ <div class="blog-review__article cooked">{{this.article}}</div>+ </article>+ <section class="blog-review__feedback">+ <h2>{{i18n "blog.review.leave_feedback"}}</h2>+ {{#if this.submitted}}+ <DFlashMessage+ @flash={{i18n "blog.review.thanks"}}+ @type="success"+ />+ {{else}}+ <p>{{i18n "blog.review.feedback_privacy"}}</p>+ <Form @onSubmit={{this.submit}} as |form|>+ <form.Field+ @format="full"+ @name="message"+ @title={{i18n "blog.review.message"}}+ @type="textarea"+ @validation="required"+ as |field|+ ><field.Control maxlength="10000" @rows={{6}} /></form.Field>+ <form.Field+ @format="full"+ @name="name"+ @title={{i18n "blog.review.name"}}+ @type="input"+ as |field|+ ><field.Control+ autocomplete="name"+ maxlength="100"+ /></form.Field>+ <form.Field+ @format="full"+ @name="email"+ @title={{i18n "blog.review.email"}}+ @type="input"+ as |field|+ ><field.Control+ autocomplete="email"+ maxlength="254"+ @type="email"+ /></form.Field>+ <form.Actions><form.Submit+ @label="blog.review.send_feedback"+ /></form.Actions>+ </Form>+ {{/if}}+ </section>+ {{/if}}+ </section>+ </template>+}diff --git a/plugins/blog/assets/javascripts/discourse/components/modal/blog-reviews.gjs b/plugins/blog/assets/javascripts/discourse/components/modal/blog-reviews.gjsnew file mode 100644index 00000000000..b6e32d9a95d--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/components/modal/blog-reviews.gjs@@ -0,0 +1,259 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { clipboardCopy } from "discourse/lib/utilities";+import DButton from "discourse/ui-kit/d-button";+import DFlashMessage from "discourse/ui-kit/d-flash-message";+import DModal from "discourse/ui-kit/d-modal";+import { i18n } from "discourse-i18n";++export default class BlogReviews extends Component {+ @service dialog;+ @service toasts;++ @tracked busy = false;+ @tracked reviews = [];+ @tracked more = false;+ @tracked selectedReview;+ @tracked feedback = [];+ @tracked feedbackMore = false;++ #page = 0;+ #feedbackPage = 0;++ constructor() {+ super(...arguments);+ this.#load();+ }++ get baseUrl() {+ return `/blog-editor/publications/${this.args.model.topicId}/reviews`;+ }++ formatDate(value) {+ return value ? new Date(value).toLocaleString() : "";+ }++ @action+ async create(data) {+ if (await this.#request(".json", { type: "POST", data })) {+ this.#page = 0;+ await this.#load();+ }+ }++ @action+ async copy(review) {+ try {+ await clipboardCopy(review.url);+ this.toasts.success({+ data: { message: i18n("blog.review.copied") },+ });+ } catch {+ this.dialog.alert({ message: i18n("blog.review.copy_failed") });+ }+ }++ @action+ revoke(review) {+ this.dialog.confirm({+ message: i18n("blog.review.revoke_confirm"),+ didConfirm: async () => {+ const result = await this.#request(`/${review.id}.json`, {+ type: "DELETE",+ });+ if (result !== false) {+ this.#page = 0;+ await this.#load();+ }+ },+ });+ }++ @action+ async loadMore() {+ await this.#load(this.#page + 1);+ }++ @action+ async viewFeedback(review) {+ const result = await this.#request(`/${review.id}/feedback.json`);+ if (result) {+ this.selectedReview = review;+ if (result.total !== undefined) {+ this.reviews = this.reviews.map((entry) =>+ entry.id === review.id+ ? { ...entry, feedback_count: result.total }+ : entry+ );+ }+ this.feedback = result.feedback;+ this.feedbackMore = result.more;+ this.#feedbackPage = 0;+ }+ }++ @action+ async loadMoreFeedback() {+ const page = this.#feedbackPage + 1;+ const result = await this.#request(+ `/${this.selectedReview.id}/feedback.json`,+ { data: { page } }+ );+ if (result) {+ this.feedback = [...this.feedback, ...result.feedback];+ this.feedbackMore = result.more;+ this.#feedbackPage = page;+ }+ }++ async #load(page = 0) {+ const result = await this.#request(".json", { data: { page } });+ if (result) {+ this.reviews = page+ ? [...this.reviews, ...result.reviews]+ : result.reviews;+ this.more = result.more;+ this.#page = page;+ }+ }++ async #request(path, options = {}) {+ this.busy = true;+ try {+ return await ajax(`${this.baseUrl}${path}`, options);+ } catch (error) {+ popupAjaxError(error);+ return false;+ } finally {+ if (!this.isDestroying) {+ this.busy = false;+ }+ }+ }++ <template>+ <DModal+ class="blog-reviews"+ @closeModal={{@closeModal}}+ @submitOnEnter={{false}}+ @title={{i18n "blog.review.manage"}}+ >+ <:body>+ {{#if @model.draft}}+ <DFlashMessage+ @flash={{i18n "blog.review.sharing_notice"}}+ @type="warning"+ />+ <Form+ class="blog-reviews__create"+ @onSubmit={{this.create}}+ as |form|+ >+ <form.Field+ @format="full"+ @name="label"+ @title={{i18n "blog.review.label"}}+ @type="input"+ as |field|+ ><field.Control maxlength="100" /></form.Field>+ <form.Actions><form.Submit+ @disabled={{this.busy}}+ @label="blog.review.create"+ /></form.Actions>+ </Form>+ {{/if}}+ <h3>{{i18n "blog.review.links"}}</h3>+ {{#if this.reviews}}+ <p class="blog-reviews__notice">{{i18n "blog.review.copy_notice"}}</p>+ {{/if}}+ {{#each this.reviews key="id" as |review|}}+ <section class="blog-reviews__entry" data-review-id={{review.id}}>+ <strong>{{review.label}}</strong>+ <p>{{i18n+ "blog.review.expires"+ date=(this.formatDate review.expires_at)+ }}</p>+ <p>{{i18n "blog.review.version" version=review.post_version}}+ ·+ {{#if review.active}}{{i18n "blog.review.active"}}{{else}}{{i18n+ "blog.review.inactive"+ }}{{/if}}</p>+ {{#if review.url}}+ <div class="blog-reviews__link">+ <input+ aria-label={{i18n "blog.review.link"}}+ class="blog-reviews__link-url"+ readonly+ value={{review.url}}+ />+ <DButton+ class="blog-reviews__copy"+ @action={{fn this.copy review}}+ @disabled={{this.busy}}+ @icon="copy"+ @label="blog.review.copy"+ />+ <a+ class="blog-reviews__open"+ href={{review.url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{i18n "blog.review.open"}}</a>+ </div>+ {{/if}}+ <DButton+ class="blog-reviews__feedback-toggle"+ @action={{fn this.viewFeedback review}}+ @disabled={{this.busy}}+ @translatedLabel={{i18n+ "blog.review.feedback_count"+ count=review.feedback_count+ }}+ />+ {{#unless review.revoked_at}}+ <DButton+ class="blog-reviews__revoke"+ @action={{fn this.revoke review}}+ @disabled={{this.busy}}+ @label="blog.review.revoke"+ />+ {{/unless}}+ </section>+ {{else}}<p>{{i18n "blog.review.no_links"}}</p>{{/each}}+ {{#if this.more}}<DButton+ @action={{this.loadMore}}+ @disabled={{this.busy}}+ @label="blog.load_more"+ />{{/if}}+ {{#if this.selectedReview}}+ <h3>{{i18n+ "blog.review.feedback_for"+ version=this.selectedReview.post_version+ }}</h3>+ <p>{{i18n "blog.review.unverified"}}</p>+ {{#each this.feedback key="id" as |entry|}}+ <article class="blog-reviews__feedback">+ <strong>{{or entry.name (i18n "blog.review.anonymous")}}</strong>+ <span>{{entry.email}}</span>+ <time datetime={{entry.created_at}}>{{this.formatDate+ entry.created_at+ }}</time>+ <p>{{entry.message}}</p>+ </article>+ {{else}}<p>{{i18n "blog.review.no_feedback"}}</p>{{/each}}+ {{#if this.feedbackMore}}<DButton+ @action={{this.loadMoreFeedback}}+ @disabled={{this.busy}}+ @label="blog.load_more"+ />{{/if}}+ {{/if}}+ </:body>+ </DModal>+ </template>+}diff --git a/plugins/blog/assets/javascripts/discourse/components/modal/blog-schedule.gjs b/plugins/blog/assets/javascripts/discourse/components/modal/blog-schedule.gjsnew file mode 100644index 00000000000..a9a1496fbd2--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/components/modal/blog-schedule.gjs@@ -0,0 +1,53 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import Form from "discourse/components/form";+import DModal from "discourse/ui-kit/d-modal";+import { i18n } from "discourse-i18n";++export default class BlogSchedule extends Component {+ @tracked busy = false;++ @action+ async schedule(data) {+ this.busy = true;+ try {+ if (await this.args.model.onSchedule(data.scheduled_at)) {+ this.args.closeModal();+ }+ } finally {+ this.busy = false;+ }+ }++ <template>+ <DModal+ class="blog-schedule"+ @closeModal={{@closeModal}}+ @title={{i18n "blog.panel.schedule_title"}}+ >+ <:body>+ <p class="blog-schedule__notice">{{i18n+ "blog.panel.schedule_notice"+ }}</p>+ <Form @onSubmit={{this.schedule}} as |form|>+ <form.Field+ @description={{i18n "blog.panel.schedule_time_hint"}}+ @format="full"+ @name="scheduled_at"+ @title={{i18n "blog.panel.schedule_time"}}+ @type="input"+ @validation="required"+ as |field|+ ><field.Control @type="datetime-local" /></form.Field>+ <form.Actions>+ <form.Submit+ @disabled={{this.busy}}+ @label="blog.panel.schedule_submit"+ />+ </form.Actions>+ </Form>+ </:body>+ </DModal>+ </template>+}diff --git a/plugins/blog/assets/javascripts/discourse/discourse-blog-route-map.js b/plugins/blog/assets/javascripts/discourse/discourse-blog-route-map.jsnew file mode 100644index 00000000000..2345165ccc8--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/discourse-blog-route-map.js@@ -0,0 +1,4 @@+export default function () {+ this.route("blog-review", { path: "/blog/review" });+ this.route("blog-editor");+}diff --git a/plugins/blog/assets/javascripts/discourse/initializers/admin-blog-navigation.js b/plugins/blog/assets/javascripts/discourse/initializers/admin-blog-navigation.jsnew file mode 100644index 00000000000..6ef08a44436--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/initializers/admin-blog-navigation.js@@ -0,0 +1,26 @@+import { withPluginApi } from "discourse/lib/plugin-api";++export default {+ name: "discourse-blog-admin-navigation",++ initialize(container) {+ if (!container.lookup("service:current-user")?.admin) {+ return;+ }+ withPluginApi((api) => {+ api.setAdminPluginIcon("blog", "pen-to-square");+ api.addAdminPluginConfigurationNav("blog", [+ {+ label: "blog.admin.themes",+ route: "adminPlugins.show.discourse-blog-themes",+ description: "blog.admin.themes_description",+ },+ {+ label: "blog.admin.identity_tab",+ route: "adminPlugins.show.discourse-blog-identity",+ description: "blog.admin.identity_description",+ },+ ]);+ });+ },+};diff --git a/plugins/blog/assets/javascripts/discourse/initializers/blog-discussion-resize.js b/plugins/blog/assets/javascripts/discourse/initializers/blog-discussion-resize.jsnew file mode 100644index 00000000000..b37225ac8a3--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/initializers/blog-discussion-resize.js@@ -0,0 +1,55 @@+import EmbedMode from "discourse/lib/embed-mode";+import blogOrigin from "discourse/plugins/blog/discourse/lib/blog-origin";++let observer;+let frame;++export default {+ after: "discourse-blog-discussion",++ initialize(container) {+ const settings = container.lookup("service:site-settings");+ const origin = blogOrigin(container.lookup("service:site").blog_base_url);+ if (+ !settings.blog_enabled ||+ !EmbedMode.enabled ||+ !document.documentElement.classList.contains(+ "discourse-blog-discussion"+ ) ||+ !origin+ ) {+ return;+ }++ const element = document.getElementById("main");+ if (!element) {+ return;+ }++ let previousHeight;+ // Core's initial resize notifications stop; replies and composer edits do not.+ observer = new ResizeObserver(() => {+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => {+ const height = Math.ceil(+ Math.max(element.scrollHeight, element.getBoundingClientRect().height)+ );+ if (height !== previousHeight) {+ previousHeight = height;+ window.parent.postMessage(+ { type: "discourse-blog-resize", height },+ origin+ );+ }+ });+ });+ observer.observe(element, { box: "border-box" });+ },++ teardown() {+ observer?.disconnect();+ observer = null;+ cancelAnimationFrame(frame);+ frame = null;+ },+};diff --git a/plugins/blog/assets/javascripts/discourse/initializers/blog-discussion.js b/plugins/blog/assets/javascripts/discourse/initializers/blog-discussion.jsnew file mode 100644index 00000000000..b25ad270cc3--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/initializers/blog-discussion.js@@ -0,0 +1,74 @@+import { schedule } from "@ember/runloop";+import EmbedMode from "discourse/lib/embed-mode";+import { withPluginApi } from "discourse/lib/plugin-api";+import blogOrigin from "discourse/plugins/blog/discourse/lib/blog-origin";++let paletteListener;++export default {+ name: "discourse-blog-discussion",++ initialize(container) {+ const settings = container.lookup("service:site-settings");+ // Boots other than the embed must not keep a listener from an earlier boot.+ window.removeEventListener("message", paletteListener);+ paletteListener = null;+ const root = document.documentElement;+ const embedClass = "discourse-blog-discussion";+ const requestedClass = new URLSearchParams(window.location.search).get(+ "class_name"+ );+ if (+ !settings.blog_enabled ||+ !EmbedMode.enabled ||+ (!root.classList.contains(embedClass) && requestedClass !== embedClass)+ ) {+ return;+ }++ // An iframe-only reload can lose the server class when its referrer changes.+ root.classList.add(embedClass);++ const parentOrigin = blogOrigin(+ container.lookup("service:site").blog_base_url+ );++ withPluginApi((api) => {+ api.onPageChange(() => {+ schedule("afterRender", () => {+ if (parentOrigin) {+ window.parent.postMessage(+ { type: "discourse-blog-ready" },+ parentOrigin+ );+ }+ });+ });+ });++ // The blog owns the design, so it sends its palette once the frame is ready.+ paletteListener = (event) => {+ if (+ event.origin !== parentOrigin ||+ event.data?.type !== "discourse-blog-palette"+ ) {+ return;+ }++ const palette = {+ accent: event.data.accent,+ paper: event.data.paper,+ ink: event.data.ink,+ };+ const colors = Object.entries(palette);+ if (!colors.every(([, color]) => /^#[0-9a-f]{6}$/i.test(color))) {+ return;+ }++ for (const [name, color] of colors) {+ root.style.setProperty(`--blog-${name}-color`, color);+ }+ };+ window.addEventListener("message", paletteListener);+ },+};diff --git a/plugins/blog/assets/javascripts/discourse/initializers/blog-post-summary.gjs b/plugins/blog/assets/javascripts/discourse/initializers/blog-post-summary.gjsnew file mode 100644index 00000000000..a3e9f3c5ead--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/initializers/blog-post-summary.gjs@@ -0,0 +1,7 @@+import { apiInitializer } from "discourse/lib/api";+import BlogPostSummary from "../components/blog-post-summary.gjs";++export default apiInitializer((api) => {+ api.addTrackedPostProperties("blog_article");+ api.renderInOutlet("post-content-cooked-html", BlogPostSummary);+});diff --git a/plugins/blog/assets/javascripts/discourse/initializers/discourse-blog.js b/plugins/blog/assets/javascripts/discourse/initializers/discourse-blog.jsnew file mode 100644index 00000000000..2cd4569b300--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/initializers/discourse-blog.js@@ -0,0 +1,26 @@+import { withPluginApi } from "discourse/lib/plugin-api";+import { i18n } from "discourse-i18n";+import BlogPublicationPanel from "../components/blog-publication-panel.gjs";++export default {+ name: "discourse-blog",++ initialize(container) {+ const settings = container.lookup("service:site-settings");+ if (!settings.blog_enabled) {+ return;+ }+ withPluginApi((api) => {+ if (api.getCurrentUser()?.can_blog_edit ?? api.getCurrentUser()?.staff) {+ api.addCommunitySectionLink({+ name: "blog-editor",+ route: "blog-editor",+ icon: "pen-to-square",+ title: i18n("blog.editor_title"),+ text: i18n("blog.editor_title"),+ });+ }+ api.renderInOutlet("topic-above-post-stream", BlogPublicationPanel);+ });+ },+};diff --git a/plugins/blog/assets/javascripts/discourse/lib/blog-origin.js b/plugins/blog/assets/javascripts/discourse/lib/blog-origin.jsnew file mode 100644index 00000000000..df5b81c70da--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/lib/blog-origin.js@@ -0,0 +1,13 @@+/**+ * The origin of the configured blog, or `null` when the setting is missing or unusable.+ *+ * @param {string} url - The blog's base URL from the site data.+ * @returns {string|null}+ */+export default function blogOrigin(url) {+ try {+ return new URL(url).origin;+ } catch {+ return null;+ }+}diff --git a/plugins/blog/assets/javascripts/discourse/routes/blog-editor.js b/plugins/blog/assets/javascripts/discourse/routes/blog-editor.jsnew file mode 100644index 00000000000..9b93ace7494--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/routes/blog-editor.js@@ -0,0 +1,24 @@+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";++export default class BlogEditorRoute extends DiscourseRoute {+ @service currentUser;+ @service router;++ beforeModel(transition) {+ if (!this.currentUser) {+ transition.send("showLogin");+ return;+ }+ if (!(this.currentUser.can_blog_edit ?? this.currentUser.staff)) {+ return this.router.transitionTo("discovery.latest");+ }+ }++ model() {+ if (this.currentUser?.can_blog_edit ?? this.currentUser?.staff) {+ return ajax("/blog-editor.json");+ }+ }+}diff --git a/plugins/blog/assets/javascripts/discourse/routes/blog-review.js b/plugins/blog/assets/javascripts/discourse/routes/blog-review.jsnew file mode 100644index 00000000000..19a2f24c2ac--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/routes/blog-review.js@@ -0,0 +1,45 @@+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";+import { i18n } from "discourse-i18n";++export default class BlogReviewRoute extends DiscourseRoute {+ queryParams = { review_token: { refreshModel: true } };++ #previousHeader;+ #previousSidebar;++ activate() {+ const application = this.controllerFor("application");+ this.#previousHeader = application.showSiteHeader;+ this.#previousSidebar = application.sidebarDisabledRouteOverride;+ application.setProperties({+ showSiteHeader: false,+ sidebarDisabledRouteOverride: true,+ });+ }++ deactivate() {+ this.controllerFor("application").setProperties({+ showSiteHeader: this.#previousHeader,+ sidebarDisabledRouteOverride: this.#previousSidebar,+ });+ }++ titleToken() {+ return this.currentModel?.title || i18n("blog.review.page_title");+ }++ async model({ review_token }) {+ try {+ const review = await ajax("/blog/review.json", {+ data: { review_token },+ });+ return { ...review, token: review_token };+ } catch (error) {+ if ([403, 404].includes(error.jqXHR?.status)) {+ return { unavailable: true };+ }+ throw error;+ }+ }+}diff --git a/plugins/blog/assets/javascripts/discourse/templates/blog-editor.gjs b/plugins/blog/assets/javascripts/discourse/templates/blog-editor.gjsnew file mode 100644index 00000000000..dc4eb50795c--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/templates/blog-editor.gjs@@ -0,0 +1,5 @@+import BlogDashboard from "../components/blog-dashboard.gjs";++export default <template>+ {{#if @model}}<BlogDashboard @model={{@model}} />{{/if}}+</template>diff --git a/plugins/blog/assets/javascripts/discourse/templates/blog-review.gjs b/plugins/blog/assets/javascripts/discourse/templates/blog-review.gjsnew file mode 100644index 00000000000..cf712370772--- /dev/null+++ b/plugins/blog/assets/javascripts/discourse/templates/blog-review.gjs@@ -0,0 +1,18 @@+import bodyClass from "discourse/helpers/body-class";+import hideApplicationFooter from "discourse/helpers/hide-application-footer";+import hideScrollableContent from "discourse/helpers/hide-scrollable-content";+import DFlashMessage from "discourse/ui-kit/d-flash-message";+import { i18n } from "discourse-i18n";+import BlogReview from "../components/blog-review.gjs";++export default <template>+ {{bodyClass "blog-review-page"}}+ {{hideApplicationFooter}}+ {{hideScrollableContent "above"}}+ {{hideScrollableContent "below"}}+ {{#if @model.unavailable}}+ <DFlashMessage @flash={{i18n "blog.review.unavailable"}} @type="error" />+ {{else}}+ <BlogReview @review={{@model}} />+ {{/if}}+</template>diff --git a/plugins/blog/assets/stylesheets/admin/blog-admin.scss b/plugins/blog/assets/stylesheets/admin/blog-admin.scssnew file mode 100644index 00000000000..ef4179d41fd--- /dev/null+++ b/plugins/blog/assets/stylesheets/admin/blog-admin.scss@@ -0,0 +1,322 @@+@use "lib/viewport";++.blog-identity {+ &__links {+ display: flex;+ flex-wrap: wrap;+ gap: 1.5em;+ margin-bottom: 1.5em;+ }++ .admin-config-area-card {+ margin-bottom: 1.5em;+ }+}++.blog-themes {+ .themes-cards-container {+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 23rem), 1fr));+ }++ &__active {+ margin-inline-start: 0.5em;+ color: var(--success);+ font-size: var(--font-down-1);+ }+}++.blog-theme-card {+ .admin-config-area-card__content {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ grid-template-rows: auto 1fr;+ }++ .theme-card-preview__image-wrapper {+ grid-column: 1 / -1;+ height: auto;+ min-height: 14rem;+ }++ .theme-card-preview__content {+ padding-block: 1rem;+ justify-content: center;+ }++ .theme-card__footer {+ align-self: center;+ padding: 1rem;+ padding-inline-start: 0;+ }++ .theme-card__controls {+ gap: 0.5rem;+ margin: 0;+ }++ .theme-card__description {+ margin: 0;+ font-size: var(--font-down-1);+ color: var(--primary-high);+ }++ .theme-card__badges {+ min-height: 0;+ margin-top: 0.5rem;+ }+}++.blog-theme-thumbnail {+ width: 100%;+ min-width: 0;+ align-self: stretch;+ padding: 1.5rem 1.75rem;+ background: var(--blog-theme-paper);+ color: var(--blog-theme-ink);++ &__eyebrow {+ font-size: var(--font-down-2);+ letter-spacing: 0.12em;+ color: var(--blog-theme-accent);+ }++ &__headline {+ margin-block: 1rem 0.5rem;+ font-family: Georgia, "Times New Roman", serif;+ font-size: 2.75rem;+ font-weight: 400;+ line-height: 1.1;+ letter-spacing: -0.04em;+ overflow-wrap: anywhere;+ }++ &__excerpt {+ max-width: 34ch;+ margin: 0;+ font-family: Georgia, "Times New Roman", serif;+ font-size: var(--font-down-1);+ line-height: 1.5;+ }++ &__palette {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.4rem;+ margin-top: 1rem;+ }++ &__swatch {+ width: 0.85rem;+ height: 0.85rem;+ border-radius: 50%;++ &.--ink {+ background: var(--blog-theme-ink);+ }++ &.--accent {+ background: var(--blog-theme-accent);+ }++ &.--paper {+ background: var(--blog-theme-paper);+ border: 1px solid var(--blog-theme-ink);+ }+ }++ &__caption {+ margin-inline-start: 0.25rem;+ font-size: var(--font-down-2);+ }+}++.blog-theme-editor {+ &__template-field {+ .ace-wrapper,+ .ace-wrapper > .loading-container {+ width: 100%;+ }+ }++ &__template-control {+ height: 520px;+ }++ &__tabs {+ margin-bottom: var(--space-4);+ }++ &__marker {+ display: inline-block;+ width: 0.4em;+ height: 0.4em;+ margin-inline-start: 0.4em;+ border-radius: 50%;+ background: var(--tertiary);+ vertical-align: middle;+ }++ &__state {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-1) var(--space-3);+ padding: var(--space-2) var(--space-3);+ margin-bottom: var(--space-3);+ background: var(--tertiary-low);+ border-radius: var(--d-border-radius);+ }++ &__state-text {+ flex: 1 1 20rem;+ margin: 0;+ }++ &__state-actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2);+ margin-inline-start: auto;+ }++ &__builtin {+ max-height: 520px;+ overflow: auto;++ pre {+ margin: 0;+ }+ }++ &__source,+ &__javascript {+ min-width: 0;+ margin-block: var(--space-4);+ overflow-wrap: anywhere;++ summary {+ cursor: pointer;+ margin-bottom: var(--space-3);+ font-weight: 600;+ }+ }+}++.blog-theme-preview {+ &__hint {+ margin-top: 0;+ }++ &__controls {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2);++ .d-native-select {+ width: auto;+ min-width: 10rem;+ max-width: 100%;+ }+ }++ &__scroll {+ margin-top: var(--space-3);+ overflow: auto;+ }++ &__link {+ margin-bottom: 0;+ }++ &__frame {+ width: 1100px;+ height: 750px;+ max-width: none;+ border: 1px solid var(--primary-low);+ }++ &__frame[data-size="mobile"] {+ width: 390px;+ height: 844px;+ }+}++.blog-theme-variables {+ &__hint {+ margin-top: 0;+ }++ &__controls {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2);++ .filter-input-container {+ flex: 1 1 14rem;+ min-width: 0;+ }++ .d-native-select {+ width: auto;+ min-width: 12rem;+ max-width: 100%;+ }+ }++ &__list {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ margin: var(--space-3) 0 0;+ padding: 0;+ list-style: none;+ }++ &__item {+ padding-bottom: var(--space-2);+ border-bottom: 1px solid var(--primary-low);++ &:last-child {+ padding-bottom: 0;+ border-bottom: 0;+ }+ }++ &__header {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2);+ }++ &__path {+ flex: 1 1 auto;+ background: transparent;+ padding: 0;+ }++ &__type {+ color: var(--primary-medium);+ font-size: var(--font-down-2);+ }++ &__example {+ max-height: 6em;+ margin: var(--space-1) 0 0;+ padding: var(--space-2);+ overflow: auto;+ background: var(--primary-very-low);+ border-radius: var(--d-border-radius);+ font-size: var(--font-down-1);+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ }++ .d-modal__container {+ max-width: 800px;+ }+}diff --git a/plugins/blog/assets/stylesheets/blog-discussion.scss b/plugins/blog/assets/stylesheets/blog-discussion.scssnew file mode 100644index 00000000000..9c7c95b3d6c--- /dev/null+++ b/plugins/blog/assets/stylesheets/blog-discussion.scss@@ -0,0 +1,157 @@+html.discourse-blog-discussion {+ color-scheme: light dark;++ --blog-canvas: light-dark(+ var(--blog-paper-color, var(--secondary)),+ var(--secondary)+ );+ --blog-foreground: light-dark(+ var(--blog-ink-color, var(--primary)),+ var(--primary)+ );+ --blog-muted: color-mix(+ in srgb,+ var(--blog-foreground) 72%,+ var(--blog-canvas)+ );+ --blog-rule: color-mix(+ in srgb,+ var(--blog-foreground) 23%,+ var(--blog-canvas)+ );+ --blog-tint: color-mix(+ in srgb,+ var(--blog-foreground) 5%,+ var(--blog-canvas)+ );+ --blog-link: light-dark(+ color-mix(+ in srgb,+ var(--blog-accent-color, var(--tertiary)) 85%,+ var(--blog-ink-color, var(--primary))+ ),+ color-mix(+ in srgb,+ var(--blog-accent-color, var(--tertiary)) 35%,+ var(--primary)+ )+ );++ body.embed-mode {+ --primary: var(--blog-foreground);+ --secondary: var(--blog-canvas);+ --primary-low: var(--blog-rule);+ --primary-very-low: var(--blog-tint);+ --primary-medium: var(--blog-muted);+ --primary-high: var(--blog-foreground);+ --tertiary: var(--blog-link);+ --content-background: var(--blog-canvas);+ --content-border-color: var(--blog-rule);+ --d-input-bg-color: var(--blog-canvas);+ background: var(--blog-canvas);+ color: var(--blog-foreground);+ font-family: system-ui, sans-serif;++ #main-outlet {+ padding-bottom: 0;+ }++ #main-outlet-wrapper {+ grid-template-areas: "content";+ grid-template-columns: minmax(0, 1fr);+ min-height: 0;+ }++ .topic-area {+ padding: 0;+ }++ // The invisible original post must not inflate the frame’s scroll height.+ .post-stream .topic-post.topic-owner:first-child,+ .nested-view__op {+ overflow: hidden;+ }++ .topic-avatar {+ flex-shrink: 0;+ min-width: max-content;+ }++ .topic-body {+ flex: 1;+ min-width: 0;+ width: auto;+ max-width: none;+ }++ .topic-avatar,+ .topic-body {+ border-color: var(--blog-rule);+ padding-top: 1.5em;+ }++ .cooked {+ font-size: 1rem;+ line-height: 1.7;+ }++ .names .username a {+ color: var(--blog-foreground);+ font-weight: 700;+ }++ .btn-primary {+ --d-button-primary-bg-color: var(--blog-foreground);+ --d-button-primary-text-color: var(--blog-canvas);+ --d-button-primary-icon-color: var(--blog-canvas);+ --d-button-primary-bg-color--hover: var(--blog-link);+ border-radius: 100px;+ padding-inline: 1.25em;+ }++ .embed-topic-footer {+ margin-top: 0;++ &__first-reply {+ padding: 1.5em 1em 0.5em;+ gap: 0.75em;+ color: var(--blog-foreground);++ > .d-icon {+ color: var(--blog-link);+ }+ }++ &__powered-by {+ font-size: var(--font-down-1);+ }+ }++ .embed-mode-composer {+ padding-inline: 0;++ .docked-composer {+ --docked-composer-input-min-height: 6em;+ }+ }++ nav.post-controls {+ --primary-low-mid: var(--blog-muted);+ --d-post-control-text-color: var(--blog-muted);+ --d-post-control-icon-color: var(--blog-muted);+ --d-post-control-create-text-color: var(--blog-foreground);+ --d-post-control-create-icon-color: var(--blog-foreground);+ }++ #topic-footer-buttons,+ #topic-progress-wrapper,+ .topic-map,+ .topic-navigation,+ .embed-floating-buttons,+ .small-action,+ .dev-tools-toolbar,+ .profiler-results {+ display: none;+ }+ }+}diff --git a/plugins/blog/assets/stylesheets/blog-editor.scss b/plugins/blog/assets/stylesheets/blog-editor.scssnew file mode 100644index 00000000000..136ad1b046f--- /dev/null+++ b/plugins/blog/assets/stylesheets/blog-editor.scss@@ -0,0 +1,60 @@+.blog-dashboard {+ max-width: 1000px;+ width: 100%;+ margin-inline: auto;+ padding-block: 2em;++ &__toolbar,+ &__filters,+ &__links,+ &__entry-actions,+ &__statuses {+ display: flex;+ align-items: center;+ gap: 0.75em;+ flex-wrap: wrap;+ }++ &__toolbar {+ justify-content: space-between;+ margin-block: 2em 1em;+ }++ &__filters .btn[aria-pressed="true"] {+ color: var(--tertiary);+ background: var(--tertiary-low);+ }++ &__correction,+ &__hint,+ &__path {+ color: var(--primary-high);+ font-size: var(--font-down-1);+ }++ &__entry {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 1.5em;+ flex-wrap: wrap;+ padding-block: 1.5em;+ border-bottom: 1px solid var(--primary-low);+ }++ &__entry-content {+ min-width: 0;+ flex: 1 1 300px;++ h2 {+ margin-block: 0.5em;+ font-size: var(--font-up-2);+ }+ }++ &__status {+ color: var(--tertiary);+ font-size: var(--font-down-1);+ font-weight: 600;+ }+}diff --git a/plugins/blog/assets/stylesheets/blog-post-summary.scss b/plugins/blog/assets/stylesheets/blog-post-summary.scssnew file mode 100644index 00000000000..78ea4965582--- /dev/null+++ b/plugins/blog/assets/stylesheets/blog-post-summary.scss@@ -0,0 +1,24 @@+.blog-post-summary {+ padding: 1em var(--topic-body-width-padding);++ &__label {+ margin: 0 0 0.75em;+ color: var(--primary-high);+ font-size: var(--font-down-1);+ font-weight: 600;+ }++ &__excerpt {+ margin: 0 0 1em;+ color: var(--primary);+ font-size: var(--font-up-1);+ line-height: 1.6;+ }++ &__actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 1em;+ }+}diff --git a/plugins/blog/assets/stylesheets/blog-publication-panel.scss b/plugins/blog/assets/stylesheets/blog-publication-panel.scssnew file mode 100644index 00000000000..07a5ec7eda5--- /dev/null+++ b/plugins/blog/assets/stylesheets/blog-publication-panel.scss@@ -0,0 +1,304 @@+%blog-status-badge {+ padding: 0.15em 0.6em;+ border-radius: 999px;+ background: var(--primary-low);+ color: var(--primary-high);+ font-size: var(--font-down-2);+ font-weight: 700;+ letter-spacing: 0.02em;+ text-transform: uppercase;+ white-space: nowrap;++ &.--live {+ background: var(--success-low);+ color: var(--success);+ }++ &.--changes-pending,+ &.--scheduled {+ background: var(--tertiary-low);+ color: var(--tertiary);+ }++ &.--unpublished {+ background: var(--danger-low);+ color: var(--danger);+ }+}++.blog-publication-panel {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ align-items: center;+ gap: var(--space-2) var(--space-6);+ max-width: calc(+ var(--topic-body-width) + var(--topic-body-width-padding) * 2 ++ var(--topic-avatar-width)+ );+ margin-block-end: var(--space-5);+ padding: var(--space-4) var(--space-5);+ border: 1px solid var(--primary-low);+ border-inline-start: 4px solid var(--primary-medium);+ border-radius: var(--d-border-radius);+ background: var(--secondary);++ &.--live {+ border-inline-start-color: var(--success);+ }++ &.--changes-pending,+ &.--scheduled {+ border-inline-start-color: var(--tertiary);+ }++ &.--unpublished {+ border-inline-start-color: var(--danger);+ }++ &__summary {+ min-width: 0;+ }++ &__status {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: var(--space-3);+ font-size: var(--font-up-1);+ font-weight: 700;+ }++ &__badge {+ @extend %blog-status-badge;+ }++ &__meta {+ margin: var(--space-1) 0 0;+ color: var(--primary-high);+ font-size: var(--font-down-1);++ a {+ color: var(--tertiary);+ }+ }++ &__sep {+ margin-inline: var(--space-1);+ }++ &__actions {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-wrap: wrap;+ gap: var(--space-2);+ }++ &__pending,+ &__changes,+ &__reviews,+ &__error,+ &__settings {+ grid-column: 1 / -1;+ }++ &__reviews {+ padding: var(--space-3) var(--space-4);+ border-radius: var(--d-border-radius);+ background: var(--primary-very-low);+ font-size: var(--font-down-1);+ }++ &__reviews-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: var(--space-2);+ }++ &__reviews-title {+ font-weight: 600;+ }++ &__reviews-links {+ color: var(--primary-high);+ font-weight: normal;+ }++ &__reviews-actions {+ display: flex;+ gap: var(--space-1);+ }++ &__feedback-notice {+ margin: var(--space-2) 0 0;+ color: var(--primary-high);+ }++ &__feedback {+ max-height: 24em;+ margin: var(--space-3) 0 0;+ padding: 0;+ list-style: none;+ overflow: auto;+ }++ &__feedback-entry {+ padding: var(--space-3);+ border-radius: var(--d-border-radius);+ background: var(--secondary);++ + .blog-publication-panel__feedback-entry {+ margin-block-start: var(--space-2);+ }+ }++ &__feedback-meta {+ color: var(--primary-high);+ }++ &__feedback-email {+ margin-inline-start: var(--space-2);+ }++ &__feedback-message {+ margin: var(--space-2) 0 0;+ color: var(--primary);+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ }++ &__pending {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: var(--space-3);+ padding: var(--space-3) var(--space-4);+ border-radius: var(--d-border-radius);+ background: var(--tertiary-very-low);+ font-size: var(--font-down-1);+ }++ &__changes {+ padding: var(--space-3) var(--space-4);+ border-radius: var(--d-border-radius);+ background: var(--primary-very-low);+ font-size: var(--font-down-1);+ }++ &__changes-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+ }++ &__changes-title {+ font-weight: 600;+ }++ &__changed {+ margin: var(--space-1) 0 0;+ color: var(--primary-high);+ }++ &__diff {+ max-height: 24em;+ margin-block-start: var(--space-3);+ padding: var(--space-3);+ border-radius: var(--d-border-radius);+ background: var(--secondary);+ overflow: auto;++ ins {+ background: var(--success-low);+ text-decoration: none;+ }++ del {+ background: var(--danger-low);+ }++ img {+ max-width: 100%;+ }+ }++ &__settings {+ padding-block-start: var(--space-3);+ border-top: 1px solid var(--primary-low);+ }++ &__settings-toggle {+ padding-inline: 0;+ }++ &__settings-hint {+ margin-inline-start: var(--space-2);+ color: var(--primary-high);+ font-weight: normal;+ }++ &__form {+ margin-block-start: var(--space-3);+ }++ &__menu-item {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ width: 100%;+ text-align: start;+ }++ &__menu-hint {+ color: var(--primary-high);+ font-size: var(--font-down-1);+ }++ &__unpublish {+ &,+ .blog-publication-panel__menu-hint {+ color: var(--danger);+ }+ }++ @media (width <= 767px) {+ grid-template-columns: minmax(0, 1fr);++ &__actions {+ justify-content: flex-start;+ }+ }+}++.blog-discussion-banner {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: var(--space-3);+ max-width: calc(+ var(--topic-body-width) + var(--topic-body-width-padding) * 2 ++ var(--topic-avatar-width)+ );+ margin-block-end: var(--space-4);+ padding: var(--space-2) var(--space-4);+ border-radius: var(--d-border-radius);+ background: var(--primary-very-low);+ color: var(--primary-high);+ font-size: var(--font-down-1);++ &__badge {+ @extend %blog-status-badge;+ }++ &__text {+ flex: 1 1 20em;+ margin: 0;++ a {+ color: var(--tertiary);+ }+ }+}diff --git a/plugins/blog/assets/stylesheets/blog-review.scss b/plugins/blog/assets/stylesheets/blog-review.scssnew file mode 100644index 00000000000..c476dc51704--- /dev/null+++ b/plugins/blog/assets/stylesheets/blog-review.scss@@ -0,0 +1,83 @@+.blog-review-page {+ .d-header-wrap,+ .sidebar-wrapper,+ .footer-nav {+ display: none;+ }++ #main-outlet-wrapper {+ display: block;+ max-width: 800px;+ padding-inline: var(--space-4);+ }++ #main-outlet {+ padding-top: var(--space-6);+ }+}++.blog-reviews {+ &__notice {+ color: var(--primary-high);+ }++ &__link {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: var(--space-2);+ margin-block: var(--space-2);+ }++ &__link-url {+ flex: 1 1 20em;+ min-width: 0;+ margin: 0;+ }+}++.blog-review {+ &__notice {+ color: var(--primary-high);+ border-bottom: 1px solid var(--content-border-color);+ padding-bottom: var(--space-3);+ }++ &__article {+ font-size: var(--font-up-1);+ line-height: 1.7;+ overflow-wrap: anywhere;++ img {+ max-width: 100%;+ height: auto;+ }++ pre {+ overflow-x: auto;+ }+ }++ &__feedback {+ margin-block: var(--space-8);+ padding-top: var(--space-5);+ border-top: 1px solid var(--content-border-color);+ }+}++.blog-reviews {+ &__entry,+ &__feedback {+ padding-block: var(--space-4);+ border-bottom: 1px solid var(--content-border-color);+ overflow-wrap: anywhere;+ }++ &__feedback p {+ white-space: pre-wrap;+ }++ &__open {+ margin-inline-start: var(--space-3);+ }+}diff --git a/plugins/blog/branding/discourse-blog/README.md b/plugins/blog/branding/discourse-blog/README.mdnew file mode 100644index 00000000000..94eda2e5897--- /dev/null+++ b/plugins/blog/branding/discourse-blog/README.md@@ -0,0 +1,37 @@+# Discourse Blog++A standalone version-2 reader theme inspired by https://blog.discourse.org/ as+observed on September 9, 2026. It reproduces the lavender background, rounded+white cards, prominent lead story, three-column desktop listing, purple links,+and bold sans-serif headings paired with serif summaries and article text.++The theme keeps this site's identity, approved articles, author names, archive+search, feeds, and native discussion section. It does not copy the reference's+marketing navigation, logo, article images, analytics, or scripts. Author initials+replace avatars because the current Liquid contract does not expose avatar URLs.+A title-based graphic supplies the lead cover when the article has no image.+System fonts avoid additional font downloads and font-related layout shifts.++## Install and edit++A saved draft named **Discourse Blog** is installed on the development site under+**Admin → Plugins → Blog → Themes**. It is not activated automatically. Open its+editor to preview, customize, or activate it independently of existing themes.++For another site, copy `blog-theme.json`, `blog.css`, and `templates/` to the root+of a public Git repository and use **Import from Git**. No build step or JavaScript+is required. Palette fields remain configurable, and the stylesheet uses the+reader's light/dark palette. Layout, homepage/archive, article, About, and+not-found templates are included.++The listing uses real archive search instead of the reference's external search.+Preview search forms retain the signed capability. All page templates preserve+normal pagination, accessible navigation, and the core-owned content/discussion+slot; no publication or permission behavior changes.++## Checks++Request coverage is in `spec/requests/themes_spec.rb` under+"Discourse Blog reference theme". It renders each page through a signed preview,+checks for Liquid diagnostics and the discussion slot, confirms activation is+unchanged, and verifies empty listings and preview-aware search fields.diff --git a/plugins/blog/branding/discourse-blog/blog-theme.json b/plugins/blog/branding/discourse-blog/blog-theme.jsonnew file mode 100644index 00000000000..df1d9a382b1--- /dev/null+++ b/plugins/blog/branding/discourse-blog/blog-theme.json@@ -0,0 +1,7 @@+{+ "version": 2,+ "name": "Discourse Blog",+ "accent_color": "795ee8",+ "paper_color": "ffffff",+ "ink_color": "333638"+}diff --git a/plugins/blog/branding/discourse-blog/blog.css b/plugins/blog/branding/discourse-blog/blog.cssnew file mode 100644index 00000000000..5f1496efe95--- /dev/null+++ b/plugins/blog/branding/discourse-blog/blog.css@@ -0,0 +1,448 @@+.blog {+ --journal-sans:+ system-ui, -apple-system, blinkmacsystemfont, "Segoe UI", sans-serif;+ --journal-serif: georgia, "Times New Roman", serif;+ background: color-mix(+ in srgb,+ var(--blog-accent-color) 4%,+ var(--blog-canvas)+ );+ font-family: var(--journal-sans);+}++.discourse-journal {+ min-height: 100vh;+ background:+ radial-gradient(+ ellipse 55px 65px at 2% 270px,+ color-mix(in srgb, var(--blog-accent-color) 25%, transparent),+ transparent+ ),+ radial-gradient(+ ellipse 70px 100px at 99% 300px,+ color-mix(in srgb, var(--blog-accent-color) 30%, transparent),+ transparent+ ),+ linear-gradient(+ to bottom,+ color-mix(in srgb, var(--blog-accent-color) 24%, var(--blog-canvas)),+ transparent 850px+ );+}++.discourse-journal__header,+.discourse-journal__footer {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 24px;+ padding: 20px 32px;+ max-width: 1600px;+ margin-inline: auto;+}++.discourse-journal a.discourse-journal__brand {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-size: 28px;+ font-weight: 800;+ letter-spacing: -1px;+ color: var(--blog-foreground);+ overflow-wrap: anywhere;+}++.discourse-journal__mark,+.discourse-journal__avatar {+ display: inline-grid;+ place-items: center;+ flex-shrink: 0;+ background: var(--blog-link-color);+ color: var(--blog-canvas);+ font-family: var(--journal-sans);+ font-weight: 800;+ line-height: 1;+}++.discourse-journal__mark {+ width: 38px;+ height: 38px;+ border-radius: 50% 50% 50% 0;+ font-size: 24px;+}++.discourse-journal__nav {+ display: flex;+ flex-wrap: wrap;+ gap: 24px;+ font-weight: 500;+}++.discourse-journal__nav a,+.discourse-journal__toolbar > a,+.discourse-journal__card h2 a {+ color: var(--blog-foreground);+}++.discourse-journal a.discourse-journal__join {+ display: inline-block;+ padding: 10px 18px;+ border-radius: 30px;+ background: var(--blog-link-color);+ color: var(--blog-canvas);+ font-size: 14px;+ font-weight: 700;+}++.discourse-journal__intro {+ max-width: 860px;+ margin: 0 auto;+ padding: 48px 24px 70px;+ text-align: center;+}++.discourse-journal__intro h1 {+ margin: 0 0 18px;+ font-size: clamp(40px, 5vw, 58px);+ font-weight: 900;+ line-height: 1.15;+ letter-spacing: -2px;+ overflow-wrap: anywhere;+}++.discourse-journal__intro p {+ font: 24px / 1.4 var(--journal-serif);+ margin: 0;+}++.discourse-journal__listing {+ max-width: 1248px;+ padding-inline: 24px;+ margin-inline: auto;+}++.discourse-journal__toolbar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ margin-bottom: 40px;+ font-weight: 600;+}++.discourse-journal__search {+ display: flex;+ width: 320px;+ max-width: 100%;+ background: var(--blog-canvas);+ border-radius: 30px;+}++.discourse-journal__search input {+ width: 100%;+ min-width: 0;+ border: 0;+ border-radius: 30px;+ padding: 10px 16px;+ background: transparent;+ color: var(--blog-foreground);+ font: inherit;+ font-weight: 400;+}++.discourse-journal__search button {+ display: grid;+ place-items: center;+ border: 0;+ padding: 10px 14px;+ border-radius: 30px;+ background: transparent;+ color: var(--blog-link-color);+ cursor: pointer;+}++.discourse-journal__grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 40px;+}++.discourse-journal__card {+ display: flex;+ flex-direction: column;+ min-width: 0;+ padding: 24px;+ border-radius: 12px;+ background: var(--blog-canvas);+ box-shadow: 0 24px 36px -20px+ color-mix(in srgb, var(--blog-foreground) 28%, transparent);+}++.discourse-journal__card.--lead {+ display: grid;+ grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);+ align-items: center;+ gap: 40px;+ grid-column: 1 / -1;+}++.discourse-journal__card-content {+ min-width: 0;+ display: flex;+ flex: 1;+ flex-direction: column;+ align-items: flex-start;+}++.discourse-journal__cover,+.discourse-journal__art {+ display: block;+ width: 100%;+ aspect-ratio: 2 / 1;+ overflow: hidden;+ border-radius: 3px;+ margin-bottom: 16px;+}++.discourse-journal__cover img {+ display: block;+ width: 100%;+ height: 100%;+ object-fit: cover;+}++.discourse-journal a.discourse-journal__art {+ display: grid;+ place-items: center;+ position: relative;+ padding: 48px 36px;+ text-align: center;+ color: var(--blog-canvas);+ background: linear-gradient(+ 115deg,+ var(--blog-link-color),+ color-mix(in srgb, var(--blog-link-color) 70%, var(--blog-foreground))+ );+ font-size: clamp(24px, 3vw, 42px);+ font-weight: 900;+ line-height: 1.25;+ letter-spacing: -1px;+ overflow-wrap: anywhere;+}++.discourse-journal__art > span:first-child {+ max-width: 18ch;+}++.discourse-journal__art-brand {+ position: absolute;+ inset-block-start: 0;+ inset-inline-end: 24px;+ max-width: calc(100% - 48px);+ padding: 8px 14px;+ border-radius: 0 0 10px 10px;+ background: var(--blog-canvas);+ color: var(--blog-foreground);+ font-size: 13px;+ letter-spacing: 0;+}++.discourse-journal__card.--lead .discourse-journal__cover,+.discourse-journal__card.--lead .discourse-journal__art {+ margin-bottom: 0;+}++.discourse-journal__category {+ margin: 0 0 8px;+ color: var(--blog-link-color);+ font-size: 12px;+ text-transform: uppercase;+}++.discourse-journal__card h2 {+ margin: 0 0 12px;+ font-size: 24px;+ font-weight: 900;+ line-height: 1.15;+ letter-spacing: -0.8px;+ overflow-wrap: anywhere;+}++.discourse-journal__card.--lead h2 {+ font-size: 32px;+}++.discourse-journal__excerpt {+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 4;+ overflow: hidden;+ font: 20px / 1.4 var(--journal-serif);+ margin: 0 0 24px;+}++.discourse-journal__card.--lead .discourse-journal__excerpt {+ -webkit-line-clamp: 6;+ line-height: 1.55;+}++.discourse-journal__byline {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-top: auto;+ font: 13px / 1.5 var(--journal-sans);+}++.discourse-journal__byline strong {+ font-size: 14px;+ font-weight: 600;+}++.discourse-journal__avatar {+ width: 36px;+ height: 36px;+ border-radius: 50%;+ font-size: 16px;+}++.discourse-journal__replies {+ margin-top: 12px;+ font-size: 13px;+}++.discourse-journal__article {+ max-width: 768px;+ padding: 60px 24px;+ margin-inline: auto;+}++.discourse-journal__article-header {+ margin-bottom: 48px;+}++.discourse-journal__breadcrumbs {+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+ margin-bottom: 28px;+ font-size: 14px;+}++.discourse-journal__article h1,+.discourse-journal__empty h1 {+ margin: 0 0 24px;+ font-size: clamp(34px, 4vw, 48px);+ font-weight: 900;+ line-height: 1.15;+ letter-spacing: -1.5px;+ overflow-wrap: anywhere;+}++.discourse-journal__standfirst {+ font: 28px / 1.4 var(--journal-serif);+ margin: 0 0 24px;+}++.discourse-journal .blog-article__body {+ font: 22px / 1.7 var(--journal-serif);+ overflow-wrap: anywhere;+}++.discourse-journal .blog-article__body h2,+.discourse-journal .blog-article__body h3 {+ font-family: var(--journal-sans);+ font-weight: 800;+ letter-spacing: -0.5px;+}++.discourse-journal .blog-discussion {+ max-width: 1000px;+ margin: 0 auto 64px;+ padding-inline: 24px;+}++.discourse-journal__empty {+ grid-column: 1 / -1;+ max-width: 760px;+ margin-inline: auto;+ padding: 80px 24px;+ text-align: center;+}++.discourse-journal__footer {+ max-width: 1248px;+ padding: 64px 24px 40px;+ margin-top: 40px;+ border-top: 1px solid var(--blog-rule);+ font-size: 14px;+}++@media (width <= 1000px) {+ .discourse-journal__header .discourse-journal__nav {+ order: 3;+ justify-content: center;+ width: 100%;+ }++ .discourse-journal__grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 24px;+ }++ .discourse-journal__card.--lead {+ grid-template-columns: minmax(0, 1fr);+ gap: 24px;+ }+}++@media (width <= 600px) {+ .discourse-journal__header {+ padding: 16px 20px;+ gap: 16px;+ }++ .discourse-journal a.discourse-journal__brand {+ font-size: 22px;+ }++ .discourse-journal__header > .discourse-journal__brand {+ max-width: 100%;+ }++ .discourse-journal__nav {+ gap: 18px;+ font-size: 14px;+ }++ .discourse-journal__intro {+ padding-block: 36px 48px;+ }++ .discourse-journal__listing {+ padding-inline: 20px;+ }++ .discourse-journal__grid {+ grid-template-columns: minmax(0, 1fr);+ }++ .discourse-journal__card h2,+ .discourse-journal__card.--lead h2 {+ font-size: 24px;+ }++ .discourse-journal__article {+ padding: 36px 20px;+ }++ .discourse-journal__standfirst {+ font-size: 24px;+ }++ .discourse-journal .blog-article__body {+ font-size: 20px;+ }+}diff --git a/plugins/blog/branding/discourse-blog/templates/about.liquid b/plugins/blog/branding/discourse-blog/templates/about.liquidnew file mode 100644index 00000000000..d2e68590980--- /dev/null+++ b/plugins/blog/branding/discourse-blog/templates/about.liquid@@ -0,0 +1,5 @@+<article class="discourse-journal__article">+ <header class="discourse-journal__article-header"><h1>{{ labels.about }}</h1><p class="discourse-journal__standfirst">{{ site.description }}</p></header>+ <div class="blog-article__body cooked">{{ site.about_html }}</div>+ <p><a class="discourse-journal__join" href="{{ site.community_url }}">{{ labels.join_community }} ↗</a></p>+</article>diff --git a/plugins/blog/branding/discourse-blog/templates/article.liquid b/plugins/blog/branding/discourse-blog/templates/article.liquidnew file mode 100644index 00000000000..155a073457c--- /dev/null+++ b/plugins/blog/branding/discourse-blog/templates/article.liquid@@ -0,0 +1,17 @@+<article class="discourse-journal__article">+ <header class="discourse-journal__article-header">+ <nav class="discourse-journal__breadcrumbs" aria-label="{{ labels.navigation }}"><a href="{{ site.url }}">{{ labels.all_articles }}</a>{% for tag in article.tags %}<span aria-hidden="true">/</span><a href="{{ tag.url }}">{{ tag.name }}</a>{% endfor %}</nav>+ <h1>{{ article.title }}</h1>+ {% if article.standfirst %}<p class="discourse-journal__standfirst">{{ article.standfirst }}</p>{% endif %}+ <div class="discourse-journal__byline">+ <span class="discourse-journal__avatar" aria-hidden="true">{{ article.author | slice: 0 | upcase }}</span>+ <div><strong>{{ article.author }}</strong><div><time datetime="{{ article.published_at }}">{{ article.date }}</time> · {{ article.reading_time }}</div></div>+ </div>+ {% if article.updated_label %}<p class="blog__updated">{{ article.updated_label }}</p>{% endif %}+ </header>+ <div class="blog-article__body cooked">{{ article.body_html }}</div>+ <footer class="blog-article__footer">+ <div class="blog__tags">{% for tag in article.tags %}<a href="{{ tag.url }}">{{ tag.name }}</a>{% endfor %}</div>+ <a href="{{ article.discussion_url }}">{{ labels.view_topic }} ↗</a>+ </footer>+</article>diff --git a/plugins/blog/branding/discourse-blog/templates/index.liquid b/plugins/blog/branding/discourse-blog/templates/index.liquidnew file mode 100644index 00000000000..edd344dfb8a--- /dev/null+++ b/plugins/blog/branding/discourse-blog/templates/index.liquid@@ -0,0 +1,39 @@+<header class="discourse-journal__intro">+ <h1>{{ page.heading }}</h1>+ <p>{{ site.description }}</p>+</header>+<div class="discourse-journal__listing">+ <div class="discourse-journal__toolbar">+ <a href="{{ site.archive_url }}">{{ labels.all_articles }} ↗</a>+ <form class="discourse-journal__search" action="{{ site.archive_url }}" method="get" role="search">+ {% if page.preview_token %}<input type="hidden" name="blog_theme_preview" value="{{ page.preview_token }}">{% endif %}+ <input type="search" name="q" value="{{ page.query }}" maxlength="100" aria-label="{{ labels.search }}" placeholder="{{ labels.search_placeholder }}">+ <button type="submit" aria-label="{{ labels.search }}"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="10" cy="10" r="6"></circle><path d="m15 15 6 6"></path></svg></button>+ </form>+ </div>+ <div class="discourse-journal__grid">+ {% for article in articles %}+ <article class="discourse-journal__card{% if forloop.first %} --lead{% endif %}">+ {% if article.image_url %}+ <a class="discourse-journal__cover" href="{{ article.url }}" tabindex="-1" aria-hidden="true"><img src="{{ article.image_url }}" alt="" {% unless forloop.first %}loading="lazy"{% endunless %}></a>+ {% elsif forloop.first %}+ <a class="discourse-journal__art" href="{{ article.url }}" tabindex="-1" aria-hidden="true"><span>{{ article.title }}</span><span class="discourse-journal__art-brand">{{ site.title }}</span></a>+ {% endif %}+ <div class="discourse-journal__card-content">+ {% if article.featured %}<p class="discourse-journal__category">{{ labels.featured }}</p>{% endif %}+ <h2><a href="{{ article.url }}">{{ article.title }}</a></h2>+ <p class="discourse-journal__excerpt">{{ article.excerpt }}</p>+ <div class="discourse-journal__byline">+ <span class="discourse-journal__avatar" aria-hidden="true">{{ article.author | slice: 0 | upcase }}</span>+ <div><strong>{{ article.author }}</strong><div><time datetime="{{ article.published_at }}">{{ article.date }}</time> · {{ article.reading_time }}</div></div>+ </div>+ <a class="discourse-journal__replies" href="{{ article.url }}#discussion">{{ article.replies_label }} ↗</a>+ </div>+ </article>+ {% else %}<section class="discourse-journal__empty"><h2>{{ labels.empty_title }}</h2><p>{{ labels.empty_body }}</p></section>{% endfor %}+ </div>+ <nav class="blog__pagination" aria-label="{{ labels.pagination }}">+ {% if page.previous_url %}<a rel="prev" href="{{ page.previous_url }}">← {{ labels.newer }}</a>{% endif %}+ {% if page.next_url %}<a rel="next" href="{{ page.next_url }}">{{ labels.older }} →</a>{% endif %}+ </nav>+</div>diff --git a/plugins/blog/branding/discourse-blog/templates/layout.liquid b/plugins/blog/branding/discourse-blog/templates/layout.liquidnew file mode 100644index 00000000000..dec0633a6c7--- /dev/null+++ b/plugins/blog/branding/discourse-blog/templates/layout.liquid@@ -0,0 +1,21 @@+<div class="discourse-journal">+ <header class="discourse-journal__header">+ <a class="discourse-journal__brand" href="{{ site.url }}"><span class="discourse-journal__mark" aria-hidden="true">{{ site.title | slice: 0 | upcase }}</span>{{ site.title }}</a>+ <nav class="discourse-journal__nav" aria-label="{{ labels.navigation }}">+ <a href="{{ site.url }}">{{ labels.home }}</a>+ <a href="{{ site.about_url }}">{{ labels.about }}</a>+ <a href="{{ site.archive_url }}">{{ labels.archive }}</a>+ <a href="{{ site.feed_url }}">{{ labels.rss }}</a>+ </nav>+ <a class="discourse-journal__join" href="{{ site.community_url }}">{{ labels.join_community }} ↗</a>+ </header>+ <main id="main" class="discourse-journal__main">{{ content_html }}</main>+ <footer class="discourse-journal__footer">+ <div><a class="discourse-journal__brand" href="{{ site.url }}">{{ site.title }}</a><p>{{ labels.footer }}</p></div>+ <nav class="discourse-journal__nav" aria-label="{{ labels.navigation }}">+ <a href="{{ site.about_url }}">{{ labels.about }}</a>+ <a href="{{ site.feed_url }}">{{ labels.rss }}</a>+ <a href="{{ site.editor_url }}">{{ labels.editor }}</a>+ </nav>+ </footer>+</div>diff --git a/plugins/blog/branding/discourse-blog/templates/not_found.liquid b/plugins/blog/branding/discourse-blog/templates/not_found.liquidnew file mode 100644index 00000000000..1aa274ab1de--- /dev/null+++ b/plugins/blog/branding/discourse-blog/templates/not_found.liquid@@ -0,0 +1 @@+<section class="discourse-journal__empty"><h1>{{ labels.not_found_title }}</h1><p>{{ labels.not_found_body }}</p><a class="discourse-journal__join" href="{{ site.url }}">{{ labels.all_articles }} →</a></section>diff --git a/plugins/blog/config/locales/client.en.yml b/plugins/blog/config/locales/client.en.ymlnew file mode 100644index 00000000000..ab412937f5f--- /dev/null+++ b/plugins/blog/config/locales/client.en.yml@@ -0,0 +1,304 @@+en:+ admin_js:+ admin:+ logs:+ staff_actions:+ actions:+ blog_submit: Submit blog revision+ blog_approve: Approve blog revision+ blog_schedule: Schedule blog publication+ blog_review_create: Create draft review link+ blog_review_revoke: Revoke draft review link+ blog_theme_save: Save blog theme draft+ blog_theme_activate: Activate blog theme+ blog_theme_delete: Delete blog theme+ site_settings:+ categories:+ blog: Blog+ blog:+ admin:+ title: Blog+ open_blog: Open blog+ safe_mode: Open without custom code+ identity: Blog identity+ blog_title: Blog name+ tagline: Tagline+ accent: Accent color+ paper: Paper color+ ink: Ink color+ about: About page+ authoring_design: Design+ authoring_sections: Theme editor sections+ template_builtin_state: Built-in template. Customize it to make changes.+ template_custom_state: Custom template. Restore the default to discard your changes.+ overridden: Custom+ customize_template: Customize this template+ restore_default: Restore default+ restore_confirm: Discard this template override and use the built-in template? Save the theme to keep this change.+ variable_reference: Variables and examples+ find_variable: Find a variable+ no_variables: No variables match that search.+ insert: Insert+ sample_article: Sample published article+ array_value: List+ trusted_html: Trusted HTML+ escaped_text: Escaped value+ layout_content: The rendered page and discussion. Use once inside the layout’s main element.+ insert_hint: Examples use public content only. Insert appends the Liquid snippet to this template. Ordinary values are escaped; trusted HTML fragments render as markup.+ retry_reference: Reload authoring reference+ working_preview_hint: Preview your unsaved changes without saving or activating them. Changing the page or sample article updates the preview.+ preview_article_unavailable: Article previews need a published article.+ preview_page: Page to preview+ preview_home: Homepage+ preview_archive: Archive+ preview_article: Article+ preview_size: Preview size+ desktop: Desktop+ mobile: Mobile+ open_working_preview: Open preview in a new tab+ template_layout: Site layout+ template_index: Homepage and archive+ template_article: Article+ template_about: About page+ template_not_found: Not found page+ code_warning:+ "Add only code you trust: it runs with the blog origin's privileges and is+ publicly downloadable. It never runs in authenticated previews in the community."+ css: Custom CSS+ css_description: Plain CSS, up to 65,536 bytes. Loads after the base stylesheet.+ js: Custom JavaScript+ js_description:+ Plain JavaScript, up to 65,536 bytes. Script tags are not parsed — load+ another script by appending a script element (document.createElement("script")).+ save: Save identity+ saved: Blog identity saved. Reload the blog to see your changes.+ identity_tab: Identity+ identity_description: The name, introduction, and About content shared by all blog themes.+ themes_index_description: Choose a theme to edit. Draft changes stay private until you activate them.+ thumbnail:+ journal: The journal+ headline: Stay curious.+ excerpt: Notes on making things, staying curious, and finding meaning in the everyday.+ palette: Theme palette+ back_to_themes: Back to themes+ editor_description: Edit this theme, save a draft, then preview or activate it.+ preview_short: Preview draft+ new_theme_short: New theme+ git_source: Git source+ no_themes: No saved themes yet+ no_themes_description: Create a theme from your current design or import one from Git.+ themes: Themes+ themes_description: Keep multiple designs and iterate without changing the live blog. Readers see the last activated snapshot, not your draft edits or Git updates.+ theme_name: Theme name+ edit: Edit+ activate: Activate+ preview: Preview+ theme_actions: Theme actions+ local_edits_badge: Local edits+ new_theme_name: New blog theme+ new_theme: New theme from active design+ import: Import+ import_description: "Import a theme from a Git repository or ZIP file. Imports create new drafts without changing the active theme."+ import_source: Import from+ import_file: ZIP file+ theme_file: Theme file+ choose_theme_file: Choose ZIP file+ import_file_description: "Choose an exported blog theme ZIP (up to 2 MB). Discourse forum theme exports are not supported."+ export: Export+ export_description: "Download the last saved version as a ZIP file. Save any changes before exporting."+ import_git: Git repository+ git_description: "Import a public HTTPS repository containing blog-theme.json (version, name, accent_color, paper_color, ink_color), optional blog.css and blog.js, and, for version 2, optional templates/*.liquid overrides at its root. Files are plain, without a build step. Imports create drafts only."+ repository: Public Git repository URL+ branch: Branch (leave blank for the default)+ active_theme: "Active design: %{name} · revision %{revision}"+ active: Active+ revision: Draft revision+ save_draft: Save draft+ draft_saved: Theme draft saved. The live blog is unchanged.+ save_before_activate: Save your changes before activating this draft.+ activate_theme: Activate saved draft+ activate_confirm: "Activate %{name}? This replaces the design readers see. Your other saved themes remain available."+ activated: Theme activated. The live blog now uses this saved revision.+ pull_git: Pull latest from Git+ pull_confirm: Pull the latest commit? This replaces the saved draft, including local edits. The active design will not change.+ local_edits: This draft has local edits since its last Git import.+ delete_theme: Delete theme+ delete_confirm: "Delete %{name} and its saved draft? This cannot be undone."+ js:+ blog:+ homepage_option: Blog+ panel:+ aria_label: Blog publication+ badge:+ draft: Draft+ live: Live+ changes_pending: Changes pending+ scheduled: Scheduled+ unpublished: Unpublished+ headline:+ draft: Not on the blog yet+ live: Live on the blog+ changes_pending: Live article is out of date+ scheduled: "Publishes %{date}"+ unpublished: Removed from the blog+ will_publish_to: "Will publish to %{url}"+ saved: "Saved %{age}"+ published_as: "Published %{date} as revision %{id}"+ view_live: View live ↗+ edits_since:+ one: "%{count} edit since"+ other: "%{count} edits since"+ scheduled_revision: "Revision %{id}, approved by %{user}"+ scheduled_notice: Edits you make now are not included unless you reschedule+ last_published: "Last published %{date}"+ unpublished_notice: The public discussion stays open+ preview: Preview+ preview_revision: "Preview revision %{id}"+ share_for_review: Share for review+ publish: Publish+ publish_correction: Publish correction+ publish_now: Publish now+ publish_now_hint: Copies the article to the blog immediately+ publish_correction_hint: Replaces the live article immediately+ more_options: More publishing options+ options: Options+ schedule: Schedule…+ schedule_hint: Pick a date and time+ schedule_title: Schedule publication+ schedule_notice: Schedules the article as it is now. Later edits are not included unless you reschedule.+ schedule_time: Publish at+ schedule_time_hint: Uses your local timezone. Choose a time at least one minute ahead.+ schedule_submit: Schedule+ submit: Submit for approval+ submit_hint: Ask another publisher to sign off first+ submitted: "Revision %{id} submitted, awaiting approval"+ approve_and_publish: "Approve and publish revision %{id}"+ unpublish_hint: Remove from the blog; the discussion stays public+ cancel_schedule: Cancel schedule+ published: "Published — revision %{id} is live on the blog."+ publish_confirm: "Publish “%{title}” to the blog now? Only the article is copied; this topic and its replies stay private."+ publish_correction_confirm: "Replace the live article with the current draft? The article keeps its URL and public discussion."+ changes_title: What changes on the blog+ changed: "Changed: %{fields}"+ change:+ title: title+ body: body+ path: path+ excerpt: excerpt+ featured: featured flag+ published_at: publication date+ revision: submitted revision+ show_diff: Show diff+ hide_diff: Hide diff+ diff_error: The change is too large to show as a diff. Use Preview instead.+ settings: Article settings+ settings_hint: Path, excerpt, date, featured+ feedback:+ none: No private feedback yet+ count:+ one: "%{count} private feedback"+ other: "%{count} private feedback"+ no_active_links: no active review links+ active_links:+ one: "%{count} active review link"+ other: "%{count} active review links"+ show: Read feedback+ hide: Hide feedback+ manage_links: Review links+ discussion:+ live: Live on the blog+ not_live: Not on the blog+ intro: "This is the public discussion for %{article}."+ intro_not_live: This topic is not on the blog.+ working_copy: "Edits go through the %{link}."+ working_copy_pending: "Edits go through the %{link}, which has unpublished changes."+ working_copy_link: private working copy+ no_working_copy: Edit privately to prepare changes in a private working copy without touching this topic.+ edit_privately: Edit privately+ review:+ anonymous: Anonymous reviewer+ page_title: Draft review+ expires: "Expires %{date}"+ manage: Share for review and feedback+ discard_metadata: Discard unsaved publication settings and share the saved article?+ sharing_notice: "Create a frozen copy of the saved article for seven days. Anyone with the link can read it and send private feedback, without an account. Later edits are not included. Existing upload URLs are not protected: do not use this for confidential attachments."+ label: Reviewer or review-round label+ create: Create seven-day review link+ copy_notice: Anyone with this link can read the article revision it was created from. Revoke it to stop it working.+ link: Review link+ copy: Copy link+ copied: Review link copied+ copy_failed: Copying was blocked by your browser. Select and copy the review link from the field instead.+ open: Open review+ links: Review links+ version: "Article revision %{version}"+ active: Active+ inactive: Expired or revoked+ revoke: Revoke link+ revoke_confirm: Revoke this review link? It will immediately stop accepting new views and feedback. Existing feedback stays private and available here.+ feedback_count: "Feedback (%{count})"+ no_links: No review links yet.+ feedback_for: "Private feedback on revision %{version}"+ unverified: Names and email addresses are supplied by reviewers and are not verified. This feedback is never published with the article.+ no_feedback: No feedback on this review link yet.+ unavailable: This review link has expired, was revoked, or is no longer available. Ask the editor for a new link.+ reader_notice: "Draft for review · frozen article revision %{version}. This link can expire or be revoked by the editor."+ leave_feedback: Leave feedback+ feedback_privacy: Your feedback is private to the article editors. No account is required. Your name and email are optional; add an email if you would like the editor to contact you.+ message: Feedback+ name: Your name+ email: Your email+ send_feedback: Send private feedback+ thanks: Thank you. Your feedback has been saved privately for the editors.+ article_summary:+ from_blog: "From the %{blog} blog"+ read: Read the article+ expand: Expand article here+ collapse: Collapse article+ editor_pagination_hint: Search and status filters apply to all articles. Load more adds up to 30 results.+ editor_search: Search articles+ editor_search_hint: Search by title or article path+ search_articles: Search+ editor_no_results: No matching articles+ editor_no_results_hint: Try another search or status filter, or start a new draft.+ editor_title: Blog editor+ editor_description:+ Draft in private. Publish with intention. Keep the conversation+ going.+ new_draft: New draft+ settings: Configure blog settings+ all: All articles+ drafts: Drafts+ published: Published+ visit_blog: Visit blog+ refresh: Refresh articles+ drafts_hint:+ Published titles open the live blog article. Open a draft to publish, schedule, or correct it from its topic. Editorial working copies remain private after publication; public discussions stay in the Blog category.+ private_draft: Draft+ draft_correction: Draft correction+ edit_privately: Edit privately+ open_draft: Open draft+ public_discussion: Public discussion+ not_published: Not on the blog+ preview: Preview+ load_more: Load more+ unpublish_confirm:+ Remove this article from the blog? The topic and its replies+ will remain public in the community. Existing copies in feeds and search engines+ cannot be recalled.+ path: Article path+ path_hint:+ Start with / and use lowercase letters, numbers, hyphens, and optional+ path segments. Old paths redirect automatically after a change.+ excerpt: Excerpt+ excerpt_hint:+ A short introduction for article cards and search previews. Leave+ blank to generate an excerpt from the article.+ date: Publication date+ date_hint:+ Leave blank to use the first publication time. For imported articles,+ choose a date in the past. Dates use UTC.+ featured: Feature on the homepage+ save: Save settings+ unpublish: Unpublish+ appearance_link: Appearancediff --git a/plugins/blog/config/locales/server.en.yml b/plugins/blog/config/locales/server.en.ymlnew file mode 100644index 00000000000..f3d24efd547--- /dev/null+++ b/plugins/blog/config/locales/server.en.yml@@ -0,0 +1,144 @@+en:+ site_settings:+ blog_contributor_groups: Groups that can write and submit their own blog drafts. Also grant these groups access to the private drafts category. This does not grant forum staff privileges.+ blog_editor_groups: Groups that can edit and submit any blog draft they can see. Also grant access to the private drafts category. Publication requires the publisher role.+ blog_publisher_groups: Groups that can approve, publish, withdraw, and schedule blog revisions they can see. Publishers may approve their own work. Also grant access to the private drafts category and permission to create topics in the public blog category. Administrators always retain access.+ blog_enabled: "A blog built on your community. Write and review articles with your editorial team, publish them under /blog with their own design, and let readers discuss each article in a linked topic. Configure the blog and drafts categories after enabling it."+ blog_url:+ Serve the blog from its own HTTPS origin, without a trailing slash+ or path, instead of /blog on this site. It must differ from the discussion hostname. Configure this hostname+ as an alias of this site at the proxy and database connection.+ blog_category:+ The single public category whose explicitly published+ topics appear on the blog. Subcategories are not included. A topic is never+ published merely by being in this category.+ blog_drafts_category:+ A separate private category for editorial drafts.+ Restrict membership to editors. Publishing copies only the approved article into a separate discussion in {{setting:blog_category}}. Editorial topics and replies stay private.+ Upload URLs are not private when secure uploads are disabled.+ blog_title:+ The blog name displayed in navigation, page titles, and+ feeds.+ blog_description:+ A short description for the homepage, feed, and search+ engines.+ blog_about: Markdown content for the blog About page.+ blog_posts_per_page:+ Number of articles shown on each homepage or archive+ page.+ blog:+ home: Home+ continue_reading: Continue reading+ posted_by: Posted by+ permalink: Permalink+ comments: Comments+ twitter_updates: Twitter updates+ on_social: On social+ community_activity: Community activity+ online_content: Online content+ recent_questions: Recent questions+ recent_answers: Recent answers+ syndication: Syndication+ time_ago: "%{time} ago"+ discussion_load_error: "The inline discussion could not load. Refresh this page to try again, or use Open in the community above."+ lightbox:+ close: Close image+ dialog: Enlarged article image+ open: View image+ open_with_description: "View image: %{description}"+ original: Open original+ skip_content: Skip to content+ navigation: Blog navigation+ archive: Archive+ about: About+ community: Community+ rss: RSS+ preview: Preview+ preview_notice:+ Only authorized editors can see this preview. Save publication+ settings before previewing changes.+ back_to_editor: Back to the topic+ editor: Write in the community+ footer: Written in Discourse. Open for conversation.+ from_the_blog: Notes from the community+ tagged: Filed under %{tag}+ search: Search+ search_placeholder: Search article titles and excerpts+ featured: Featured+ reading_time:+ one: "%{count} min read"+ other: "%{count} min read"+ replies:+ one: "%{count} reply"+ other: "%{count} replies"+ empty_title: Nothing here yet+ empty_body: New stories will appear here when they are published.+ pagination: Article pages+ newer: Newer articles+ older: Older articles+ all_articles: All articles+ updated: Updated %{date}+ view_topic: View in the community+ discussion: The conversation+ open_discussion: Open in the community+ discussion_closed:+ This conversation is closed to new replies. You can still read+ the discussion below.+ discussion_description:+ Have a thought or a question? Join the discussion below+ with your community account.+ join_community: Join the community+ not_found_title: This page is not available+ not_found_body: It may have moved, returned to drafts, or not been published yet.+ errors:+ private_site:+ The blog requires a public site with secure uploads disabled.+ Draft text stays private, but uploaded files are not access-controlled without+ secure uploads.+ anonymous_uploads: "The blog requires anonymous upload downloads. Disable prevent_anons_from_downloading_files before publishing or sharing reviews."+ category: Choose one public Blog category in the blog site settings.+ drafts_category:+ Choose a separate private drafts category accessible only to configured editorial groups or staff, distinct from the core shared drafts category.+ published_page:+ Unpublish this topic from page publishing before publishing+ it on the blog.+ path_taken: is reserved or already belongs to another article+ future_date:+ must be today or earlier. Use the schedule controls to release+ an article in the future.+ color: "Use exactly six hexadecimal digits, without a # prefix."+ latest_stories: Latest stories+ explore_archive: Explore the archive+ customizations_disabled:+ Custom CSS and JavaScript are disabled for this page+ view.+ themes:+ sample_article: Example article (no public article selected)+ sample_body: Publish an article to see its real content in this reference.+ preview_diagnostic: "%{template}, line %{line}: %{message}"+ template_invalid: "Provide a valid Liquid template of at most 65,536 bytes."+ template_parse_error: "Invalid Liquid template: %{error}"+ current: Current appearance+ invalid: "Provide a name (up to 100 characters), an Editorial or Minimal layout, six-digit hexadecimal colors, and CSS/JavaScript of at most 65,536 bytes each."+ limit: You can save up to 30 blog themes. Delete an unused theme first.+ stale: This theme has changed. Reload it and review the latest draft before continuing.+ active_delete: Activate another theme before deleting this one.+ repository_invalid: Use a public HTTPS Git repository URL without credentials, query parameters, or fragments.+ archive_invalid: "The ZIP file is invalid, has too many files, or contains oversized theme files."+ manifest_invalid: The theme must contain a valid blog-theme.json manifest (version 1 or 2).+ file_too_large: "%{file} exceeds the allowed file size."+ preview: "Theme preview: %{name}"+ preview_notice: This preview is visible only through this temporary preview link. The live blog has not changed.+ exit_preview: Exit preview+ review:+ page_title: Draft review+ javascript_required: Enable JavaScript to read this shared draft and leave feedback.+ unavailable: This review link has expired, was revoked, or is no longer available. Ask the editor for a new link.+ limit: This draft already has 20 active review links. Revoke one before creating another.+ feedback_limit: This review has reached its feedback limit. Contact the editor for a new review link.+ editorial:+ access_lost: Scheduled publication stopped because publisher access or article eligibility changed. Check permissions and the private source, then schedule again.+ private_source: Editorial topics must stay in their private drafts category. Publish an approved revision instead.+ stale: This revision is no longer the current submitted or approved revision. Reload and review it again.+ approval_required: Approve a submitted revision before publishing or scheduling it.+ schedule_time: Choose a publication time at least one minute ahead and within the next year.diff --git a/plugins/blog/config/routes.rb b/plugins/blog/config/routes.rbnew file mode 100644index 00000000000..28cda112ba9--- /dev/null+++ b/plugins/blog/config/routes.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++Blog::Engine.routes.draw do+ get "/blog-editor/publications/:topic_id/reviews" => "reviews#index"+ post "/blog-editor/publications/:topic_id/reviews" => "reviews#create"+ delete "/blog-editor/publications/:topic_id/reviews/:id" => "reviews#destroy"+ get "/blog-editor/publications/:topic_id/reviews/:id/feedback" => "reviews#feedback"+ get "/blog-editor/publications/:topic_id/feedback" => "reviews#topic_feedback"+ get "/admin/plugins/blog/themes" => "themes#index"+ post "/admin/plugins/blog/themes" => "themes#create"+ post "/admin/plugins/blog/themes/import" => "themes#import"+ get "/admin/plugins/blog/theme-authoring" => "themes#authoring"+ post "/admin/plugins/blog/theme-authoring/preview" => "themes#working_preview"+ get "/admin/plugins/blog/themes/:id/export" => "themes#export"+ get "/admin/plugins/blog/themes/:id" => "themes#show"+ put "/admin/plugins/blog/themes/:id" => "themes#update"+ delete "/admin/plugins/blog/themes/:id" => "themes#destroy"+ post "/admin/plugins/blog/themes/:id/activate" => "themes#activate"+ post "/admin/plugins/blog/themes/:id/pull" => "themes#pull"+ get "/blog-editor" => "editor#index"+ get "/blog-editor/preview/:topic_id" => "editor#preview"+ get "/blog-editor/publications/:topic_id" => "editor#show"+ get "/blog-editor/publications/:topic_id/changes" => "editor#changes"+ put "/blog-editor/publications/:topic_id" => "editor#update"+ post "/blog-editor/publications/:topic_id/prepare" => "editor#prepare"+ post "/blog-editor/publications/:topic_id/submit" => "editor#submit"+ post "/blog-editor/publications/:topic_id/approve" => "editor#approve"+ post "/blog-editor/publications/:topic_id/schedule" => "editor#schedule"+ delete "/blog-editor/publications/:topic_id/schedule" => "editor#cancel_schedule"+ post "/blog-editor/publications/:topic_id/publish" => "editor#publish"+ post "/blog-editor/publications/:topic_id/return-to-drafts" => "editor#return_to_drafts"+ delete "/blog-editor/publications/:topic_id" => "editor#destroy"+enddiff --git a/plugins/blog/config/settings.yml b/plugins/blog/config/settings.ymlnew file mode 100644index 00000000000..349276fdff6--- /dev/null+++ b/plugins/blog/config/settings.yml@@ -0,0 +1,50 @@+blog:+ blog_enabled:+ default: false+ client: true+ hidden: true+ upcoming_change:+ status: "conceptual"+ impact: "feature,all_members"+ allow_enabled_for:+ - "everyone"+ requires_plugin_enabled: false+ permanent_warning: false+ blog_url:+ default: ""+ regex: "^$|^https://[a-z0-9.-]+(:[0-9]+)?$"+ blog_category:+ type: category+ default: ""+ client: true+ blog_drafts_category:+ type: category+ default: ""+ client: true+ blog_title:+ default: "The blog"+ blog_description:+ default: "Ideas, stories, and conversations."+ textarea: true+ blog_about:+ default: ""+ textarea: true+ blog_posts_per_page:+ default: 10+ min: 1+ max: 30+ blog_contributor_groups:+ type: group_list+ default: "3"+ disallowed_groups: "0"+ refresh: true+ blog_editor_groups:+ type: group_list+ default: "3"+ disallowed_groups: "0"+ refresh: true+ blog_publisher_groups:+ type: group_list+ default: "3"+ disallowed_groups: "0"+ refresh: truediff --git a/plugins/blog/db/migrate/20260908063229_create_discourse_blog_publications.rb b/plugins/blog/db/migrate/20260908063229_create_discourse_blog_publications.rbnew file mode 100644index 00000000000..7c73879d0ca--- /dev/null+++ b/plugins/blog/db/migrate/20260908063229_create_discourse_blog_publications.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++class CreateDiscourseBlogPublications < ActiveRecord::Migration[8.0]+ def change+ create_table :discourse_blog_publications do |table|+ table.bigint :topic_id, null: false+ table.bigint :publisher_id+ table.string :path, null: false+ table.string :excerpt, null: false, default: ""+ table.boolean :featured, null: false, default: false+ table.boolean :published, null: false, default: false+ table.datetime :published_at+ table.timestamps+ end+ add_index :discourse_blog_publications, :topic_id, unique: true+ add_index :discourse_blog_publications, %i[published published_at]++ create_table :discourse_blog_paths do |table|+ table.bigint :publication_id, null: false+ table.string :path, null: false+ table.timestamps+ end+ add_index :discourse_blog_paths, :path, unique: true+ add_index :discourse_blog_paths, :publication_id+ end+enddiff --git a/plugins/blog/db/migrate/20260909022122_create_discourse_blog_reviews.rb b/plugins/blog/db/migrate/20260909022122_create_discourse_blog_reviews.rbnew file mode 100644index 00000000000..61624d0f879--- /dev/null+++ b/plugins/blog/db/migrate/20260909022122_create_discourse_blog_reviews.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++class CreateDiscourseBlogReviews < ActiveRecord::Migration[8.0]+ def change+ create_table :discourse_blog_reviews do |table|+ table.bigint :topic_id, null: false+ table.bigint :creator_id, null: false+ table.string :token_digest, null: false, limit: 64+ table.string :label, null: false, default: "", limit: 100+ table.string :title, null: false+ table.text :cooked, null: false+ table.integer :post_version, null: false+ table.datetime :expires_at, null: false+ table.datetime :revoked_at+ table.timestamps+ end+ add_index :discourse_blog_reviews, :token_digest, unique: true+ add_index :discourse_blog_reviews, %i[topic_id created_at]++ create_table :discourse_blog_review_feedback do |table|+ table.bigint :review_id, null: false+ table.string :name, null: false, default: "", limit: 100+ table.string :email, null: false, default: "", limit: 254+ table.text :message, null: false+ table.timestamps+ end+ add_index :discourse_blog_review_feedback,+ %i[review_id created_at],+ name: "idx_blog_review_feedback_review_created"+ end+enddiff --git a/plugins/blog/db/migrate/20260909033948_add_discourse_blog_editorial_revisions.rb b/plugins/blog/db/migrate/20260909033948_add_discourse_blog_editorial_revisions.rbnew file mode 100644index 00000000000..1f2cc12b182--- /dev/null+++ b/plugins/blog/db/migrate/20260909033948_add_discourse_blog_editorial_revisions.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++class AddDiscourseBlogEditorialRevisions < ActiveRecord::Migration[8.0]+ def up+ create_table :discourse_blog_revisions do |table|+ table.bigint :publication_id, null: false+ table.bigint :source_topic_id, null: false+ table.bigint :creator_id, null: false+ table.jsonb :data, null: false, default: {}+ table.bigint :approver_id+ table.datetime :approved_at+ table.timestamps+ end+ add_index :discourse_blog_revisions, %i[publication_id id]+ change_table :discourse_blog_publications do |table|+ table.bigint :draft_topic_id+ table.bigint :discussion_topic_id+ table.bigint :published_revision_id+ table.bigint :submitted_revision_id+ table.bigint :approved_revision_id+ table.bigint :scheduled_revision_id+ table.bigint :scheduler_id+ table.datetime :scheduled_at+ table.datetime :last_published_at+ table.string :schedule_token+ table.text :schedule_error, null: false, default: ""+ table.jsonb :draft_metadata, null: false, default: {}+ end+ add_index :discourse_blog_publications, :draft_topic_id, unique: true+ add_index :discourse_blog_publications, :discussion_topic_id, unique: true++ return unless Migration::Helpers.existing_site?+ execute <<~SQL+ UPDATE discourse_blog_publications SET discussion_topic_id = topic_id WHERE published;+ INSERT INTO discourse_blog_revisions+ (publication_id, source_topic_id, creator_id, approver_id, approved_at, data, created_at, updated_at)+ SELECT publication.id, topic.id, post.user_id, COALESCE(publication.publisher_id, post.user_id),+ publication.published_at,+ jsonb_build_object(+ 'title', topic.title, 'raw', post.raw, 'cooked', post.cooked,+ 'path', publication.path, 'excerpt', publication.excerpt, 'featured', publication.featured,+ 'published_at', publication.published_at,+ 'author_name', COALESCE(NULLIF(author.name, ''), author.username),+ 'image_url', COALESCE(upload.url, ''), 'tags', '[]'::jsonb+ ), publication.updated_at, publication.updated_at+ FROM discourse_blog_publications publication+ JOIN topics topic ON topic.id = publication.topic_id+ JOIN posts post ON post.topic_id = topic.id AND post.post_number = 1+ JOIN users author ON author.id = post.user_id+ LEFT JOIN uploads upload ON upload.id = topic.image_upload_id+ WHERE publication.published;+ UPDATE discourse_blog_publications publication+ SET published_revision_id = revision.id, last_published_at = publication.updated_at+ FROM discourse_blog_revisions revision WHERE revision.publication_id = publication.id;+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration,+ "Private editorial sources and public discussion identities cannot be safely downgraded."+ end+enddiff --git a/plugins/blog/db/migrate/20260914042438_add_blog_publications_scheduled_at_index.rb b/plugins/blog/db/migrate/20260914042438_add_blog_publications_scheduled_at_index.rbnew file mode 100644index 00000000000..e44c9fe2d39--- /dev/null+++ b/plugins/blog/db/migrate/20260914042438_add_blog_publications_scheduled_at_index.rb@@ -0,0 +1,10 @@+# frozen_string_literal: true++class AddBlogPublicationsScheduledAtIndex < ActiveRecord::Migration[8.0]+ def change+ add_index :discourse_blog_publications,+ :scheduled_at,+ where: "scheduled_at IS NOT NULL",+ name: "idx_discourse_blog_publications_scheduled_at"+ end+enddiff --git a/plugins/blog/db/migrate/20260914051629_remove_blog_theme_site_setting.rb b/plugins/blog/db/migrate/20260914051629_remove_blog_theme_site_setting.rbnew file mode 100644index 00000000000..5723a737db5--- /dev/null+++ b/plugins/blog/db/migrate/20260914051629_remove_blog_theme_site_setting.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class RemoveBlogThemeSiteSetting < ActiveRecord::Migration[8.0]+ def up+ execute "DELETE FROM site_settings WHERE name = 'discourse_blog_theme'"+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/blog/db/migrate/20260915045302_remove_legacy_blog_appearance_settings.rb b/plugins/blog/db/migrate/20260915045302_remove_legacy_blog_appearance_settings.rbnew file mode 100644index 00000000000..82e1aba8363--- /dev/null+++ b/plugins/blog/db/migrate/20260915045302_remove_legacy_blog_appearance_settings.rb@@ -0,0 +1,94 @@+# frozen_string_literal: true++# Blog designs own their palette and code now. A site that only ever configured the+# old appearance settings keeps that design as an activated theme, which is how+# readers keep seeing it.+class RemoveLegacyBlogAppearanceSettings < ActiveRecord::Migration[8.0]+ STORE = "discourse-blog-themes"+ THEME_NAME = "Current appearance"++ # Theme field => legacy site setting, with the setting's old default.+ LEGACY_SETTINGS = {+ "accent_color" => %w[discourse_blog_accent_color d64b2a],+ "paper_color" => %w[discourse_blog_paper_color f5f0e6],+ "ink_color" => %w[discourse_blog_ink_color 19382d],+ "css" => ["discourse_blog_custom_css", ""],+ "javascript" => ["discourse_blog_custom_js", ""],+ }.freeze++ # Mirrors the reader's Liquid pages; a missing key means "use the built-in".+ TEMPLATE_FIELDS = %w[+ template_layout+ template_index+ template_article+ template_about+ template_not_found+ ].freeze++ def up+ carry_over_legacy_appearance if Migration::Helpers.existing_site?++ names = LEGACY_SETTINGS.values.map { |setting_name, _| "'#{setting_name}'" }.join(", ")+ execute "DELETE FROM site_settings WHERE name IN (#{names})"+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end++ private++ def carry_over_legacy_appearance+ return if theme_exists?++ values = legacy_values+ return if values.all? { |field, value| value == LEGACY_SETTINGS[field][1] }++ theme = theme_for(values)+ insert_row("theme:#{theme["id"]}", theme)+ insert_row("snapshot:#{theme["snapshot"]}", theme)+ insert_row("active", theme)+ end++ def theme_exists?+ DB.query_single(+ "SELECT 1 FROM plugin_store_rows WHERE plugin_name = :store AND key LIKE 'theme:%' LIMIT 1",+ store: STORE,+ ).present?+ end++ def legacy_values+ LEGACY_SETTINGS.to_h do |field, (setting_name, default)|+ # Only customized settings have a row; a missing one still means its default.+ value =+ DB.query_single(+ "SELECT value FROM site_settings WHERE name = :name",+ name: setting_name,+ ).first+ [field, value.nil? ? default : value.to_s]+ end+ end++ def theme_for(values)+ {+ "id" => SecureRandom.uuid,+ "name" => THEME_NAME,+ "revision" => 1,+ "accent_color" => values["accent_color"],+ "paper_color" => values["paper_color"],+ "ink_color" => values["ink_color"],+ "css" => values["css"],+ "javascript" => values["javascript"],+ "source" => nil,+ "locally_modified" => false,+ "snapshot" => SecureRandom.uuid,+ }.merge(TEMPLATE_FIELDS.to_h { |field| [field, ""] })+ end++ def insert_row(key, theme)+ DB.exec(<<~SQL, store: STORE, key: key, value: theme.to_json)+ INSERT INTO plugin_store_rows (plugin_name, key, type_name, value)+ VALUES (:store, :key, 'JSON', :value)+ SQL+ end+enddiff --git a/plugins/blog/db/migrate/20260915075800_add_token_to_blog_reviews.rb b/plugins/blog/db/migrate/20260915075800_add_token_to_blog_reviews.rbnew file mode 100644index 00000000000..76cde78e50a--- /dev/null+++ b/plugins/blog/db/migrate/20260915075800_add_token_to_blog_reviews.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++class AddTokenToBlogReviews < ActiveRecord::Migration[8.0]+ def up+ add_column :discourse_blog_reviews, :token, :string, limit: 64+ add_index :discourse_blog_reviews, :token, unique: true++ # Existing rows stored only a digest, so their links can no longer be resolved.+ execute <<~SQL+ UPDATE discourse_blog_reviews+ SET revoked_at = NOW(), updated_at = NOW()+ WHERE token IS NULL+ AND revoked_at IS NULL+ SQL++ change_column_null :discourse_blog_reviews, :token_digest, true+ end++ def down+ change_column_null :discourse_blog_reviews, :token_digest, false+ remove_index :discourse_blog_reviews, :token+ remove_column :discourse_blog_reviews, :token+ end+enddiff --git a/plugins/blog/db/migrate/20260915075802_drop_blog_review_token_digest.rb b/plugins/blog/db/migrate/20260915075802_drop_blog_review_token_digest.rbnew file mode 100644index 00000000000..62fa5b82ae2--- /dev/null+++ b/plugins/blog/db/migrate/20260915075802_drop_blog_review_token_digest.rb@@ -0,0 +1,18 @@+# frozen_string_literal: true++# Promoted from a post-deploy migration so the drop runs before+# RenameDiscourseBlogToBlog turns discourse_blog_reviews into a view.+class DropBlogReviewTokenDigest < ActiveRecord::Migration[8.0]+ DROPPED_COLUMNS = { discourse_blog_reviews: %i[token_digest] }++ def up+ Migration::SafeMigrate.disable!+ DROPPED_COLUMNS.each { |table, columns| Migration::ColumnDropper.execute_drop(table, columns) }+ ensure+ Migration::SafeMigrate.enable!+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/blog/db/migrate/20261008205400_retain_blog_review_uploads.rb b/plugins/blog/db/migrate/20261008205400_retain_blog_review_uploads.rbnew file mode 100644index 00000000000..85deaca8c80--- /dev/null+++ b/plugins/blog/db/migrate/20261008205400_retain_blog_review_uploads.rb@@ -0,0 +1,65 @@+# frozen_string_literal: true++class RetainBlogReviewUploads < ActiveRecord::Migration[8.0]+ disable_ddl_transaction!++ BATCH_SIZE = 100+ BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"++ def up+ return unless Migration::Helpers.existing_site?++ last_id = 0+ loop do+ reviews = DB.query(<<~SQL, last_id: last_id, batch_size: BATCH_SIZE)+ SELECT id, cooked+ FROM discourse_blog_reviews+ WHERE id > :last_id AND revoked_at IS NULL AND expires_at > CURRENT_TIMESTAMP+ ORDER BY id+ LIMIT :batch_size+ SQL+ break if reviews.empty?++ reviews.each do |review|+ sha1s = review.cooked.scan(%r{/([0-9a-f]{40})(?:[_./"?#]|$)}).flatten+ review+ .cooked+ .scan(%r{/uploads/short-url/([a-zA-Z0-9]+)})+ .flatten+ .each do |encoded|+ next if encoded.length > 27+ value =+ encoded+ .each_char+ .reduce(0) { |number, character| number * 62 + BASE62_ALPHABET.index(character) }+ hex = value.to_s(16)+ sha1s << hex.rjust(40, "0") if hex.length <= 40+ end+ next if sha1s.empty?++ DB.exec(<<~SQL, review_id: review.id, sha1s: sha1s.uniq)+ INSERT INTO upload_references (upload_id, target_type, target_id, created_at, updated_at)+ SELECT upload_id, 'DiscourseBlog::Review', :review_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP+ FROM (+ SELECT id AS upload_id FROM uploads WHERE sha1 IN (:sha1s)+ UNION+ SELECT optimized_images.upload_id+ FROM optimized_images+ JOIN uploads ON uploads.id = optimized_images.upload_id+ WHERE optimized_images.sha1 IN (:sha1s)+ ) snapshot_uploads+ WHERE EXISTS (+ SELECT 1 FROM discourse_blog_reviews+ WHERE id = :review_id AND revoked_at IS NULL AND expires_at > CURRENT_TIMESTAMP+ )+ ON CONFLICT (upload_id, target_type, target_id) DO NOTHING+ SQL+ end+ last_id = reviews.last.id+ end+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/blog/db/migrate/20261028093146_rename_discourse_blog_to_blog.rb b/plugins/blog/db/migrate/20261028093146_rename_discourse_blog_to_blog.rbnew file mode 100644index 00000000000..19ad0e90d88--- /dev/null+++ b/plugins/blog/db/migrate/20261028093146_rename_discourse_blog_to_blog.rb@@ -0,0 +1,134 @@+# frozen_string_literal: true++# The plugin was renamed from "discourse-blog" to "blog". The historical+# migrations still create the discourse_blog_* schema; this converts it, along+# with every persisted reference to the old name.+class RenameDiscourseBlogToBlog < ActiveRecord::Migration[8.1]+ RENAMED_TABLES = {+ discourse_blog_publications: :blog_publications,+ discourse_blog_paths: :blog_paths,+ discourse_blog_revisions: :blog_revisions,+ discourse_blog_reviews: :blog_reviews,+ discourse_blog_review_feedback: :blog_review_feedback,+ }++ RENAMED_SETTINGS =+ %w[+ discourse_blog_enabled+ discourse_blog_url+ discourse_blog_category+ discourse_blog_drafts_category+ discourse_blog_title+ discourse_blog_description+ discourse_blog_about+ discourse_blog_posts_per_page+ discourse_blog_contributor_groups+ discourse_blog_editor_groups+ discourse_blog_publisher_groups+ ].to_h { |name| [name, name.delete_prefix("discourse_")] }++ RENAMED_TYPES = {+ "DiscourseBlog::Review" => "Blog::Review",+ "DiscourseBlog::Revision" => "Blog::Revision",+ }++ def up+ Migration::SafeMigrate.disable!++ renamed_tables =+ RENAMED_TABLES.select do |old_name, new_name|+ table_exists?(old_name) && !table_exists?(new_name)+ end+ renamed_tables.each { |old_name, new_name| rename_table(old_name, new_name) }++ RENAMED_TABLES.each do |old_name, new_name|+ rename_table_objects(old_name.to_s, new_name.to_s) if table_exists?(new_name)+ end++ # App servers still running the old code read these until FinishRenameDiscourseBlogToBlog runs.+ renamed_tables.each do |old_name, new_name|+ execute "CREATE VIEW #{old_name} AS SELECT * FROM #{new_name}"+ end++ Migration::SafeMigrate.enable!++ RENAMED_SETTINGS.each do |old_name, new_name|+ DB.exec(<<~SQL, old_name:, new_name:)+ UPDATE site_settings+ SET name = :new_name+ WHERE name = :old_name+ AND NOT EXISTS (SELECT 1 FROM site_settings WHERE name = :new_name)+ SQL++ DB.exec(<<~SQL, old_name:, new_name:)+ UPDATE site_setting_groups+ SET name = :new_name+ WHERE name = :old_name+ AND NOT EXISTS (SELECT 1 FROM site_setting_groups WHERE name = :new_name)+ SQL++ DB.exec(<<~SQL, old_name:, new_name:)+ UPDATE site_setting_localizations+ SET setting_name = :new_name+ WHERE setting_name = :old_name+ SQL+ end++ RENAMED_TYPES.each { |old_type, new_type| DB.exec(<<~SQL, old_type:, new_type:) }+ UPDATE upload_references old+ SET target_type = :new_type+ WHERE old.target_type = :old_type+ AND NOT EXISTS (+ SELECT 1 FROM upload_references+ WHERE upload_id = old.upload_id AND target_type = :new_type AND target_id = old.target_id+ )+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end++ private++ # rename_table only renames conventionally named indexes and sequences, so+ # rename the table's remaining objects that still embed its old name.+ # Index-backed constraints follow their indexes.+ def rename_table_objects(old_name, new_name)+ rename = ->(name) { name.sub(old_name, new_name) }+ table = quote_table_name(new_name)++ DB+ .query_single(<<~SQL, new_name, old_name)+ SELECT i.relname+ FROM pg_index x+ JOIN pg_class i ON i.oid = x.indexrelid+ WHERE x.indrelid = ?::regclass AND strpos(i.relname, ?) > 0+ SQL+ .each do |name|+ execute "ALTER INDEX #{quote_table_name(name)} RENAME TO #{quote_table_name(rename[name])}"+ end++ DB+ .query_single(<<~SQL, new_name, old_name)+ SELECT s.relname+ FROM pg_class s+ JOIN pg_depend d ON d.objid = s.oid AND d.classid = 'pg_class'::regclass+ WHERE s.relkind = 'S' AND d.refobjid = ?::regclass AND d.deptype IN ('a', 'i')+ AND strpos(s.relname, ?) > 0+ SQL+ .each do |name|+ execute "ALTER SEQUENCE #{quote_table_name(name)} RENAME TO #{quote_table_name(rename[name])}"+ end++ DB+ .query_single(<<~SQL, new_name, old_name)+ SELECT conname+ FROM pg_constraint+ WHERE conrelid = ?::regclass AND contype IN ('c', 'f', 'n') AND strpos(conname, ?) > 0+ SQL+ .each do |name|+ execute "ALTER TABLE #{table} RENAME CONSTRAINT #{quote_column_name(name)} TO #{quote_column_name(rename[name])}"+ end+ end+enddiff --git a/plugins/blog/db/post_migrate/20261028093149_finish_rename_discourse_blog_to_blog.rb b/plugins/blog/db/post_migrate/20261028093149_finish_rename_discourse_blog_to_blog.rbnew file mode 100644index 00000000000..f000b1c5d3f--- /dev/null+++ b/plugins/blog/db/post_migrate/20261028093149_finish_rename_discourse_blog_to_blog.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++class FinishRenameDiscourseBlogToBlog < ActiveRecord::Migration[8.1]+ RENAMED_TYPES = {+ "DiscourseBlog::Review" => "Blog::Review",+ "DiscourseBlog::Revision" => "Blog::Revision",+ }++ def up+ execute <<~SQL+ DROP VIEW IF EXISTS+ discourse_blog_publications,+ discourse_blog_paths,+ discourse_blog_revisions,+ discourse_blog_reviews,+ discourse_blog_review_feedback+ SQL++ # The old code keeps writing these until its app servers restart.+ RENAMED_TYPES.each do |old_type, new_type|+ DB.exec(<<~SQL, old_type:, new_type:)+ UPDATE upload_references old+ SET target_type = :new_type+ WHERE old.target_type = :old_type+ AND NOT EXISTS (+ SELECT 1 FROM upload_references+ WHERE upload_id = old.upload_id AND target_type = :new_type AND target_id = old.target_id+ )+ SQL++ # Anything left duplicates a reference that already uses the new name.+ DB.exec("DELETE FROM upload_references WHERE target_type = :old_type", old_type:)+ end+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/blog/lib/blog/blog_theme.rb b/plugins/blog/lib/blog/blog_theme.rbnew file mode 100644index 00000000000..8995f5778f6--- /dev/null+++ b/plugins/blog/lib/blog/blog_theme.rb@@ -0,0 +1,193 @@+# frozen_string_literal: true++module ::Blog+ class BlogTheme+ STORE = "discourse-blog-themes"+ MAX_THEMES = 30+ MAX_CODE_BYTES = 65_536+ TEMPLATE_FIELDS = TemplateRenderer::PAGES.map { |page| "template_#{page}" }.freeze+ FIELDS = (%w[name accent_color paper_color ink_color css javascript] + TEMPLATE_FIELDS).freeze++ # Readers fall back to this until a theme is activated.+ BUILT_IN_PALETTE = {+ "accent_color" => "d64b2a",+ "paper_color" => "f5f0e6",+ "ink_color" => "19382d",+ }.freeze++ def self.defaults+ {+ "name" => I18n.t("blog.themes.current"),+ **BUILT_IN_PALETTE,+ "css" => "",+ "javascript" => "",+ }.merge(TEMPLATE_FIELDS.to_h { |field| [field, ""] })+ end++ def self.all+ PluginStoreRow+ .where(plugin_name: STORE)+ .where("key LIKE 'theme:%'")+ .order(:id)+ .map { |row| PluginStore.cast_value(row.type_name, row.value) }+ end++ def self.find(id)+ PluginStore.get(STORE, "theme:#{id}") || raise(Discourse::NotFound)+ end++ def self.active+ PluginStore.get(STORE, "active") || defaults+ end++ def self.snapshot(id)+ PluginStore.get(STORE, "snapshot:#{id}") || raise(Discourse::NotFound)+ end++ def self.save(attributes, user:, id: nil, revision: nil, source: nil)+ values = TEMPLATE_FIELDS.to_h { |field| [field, ""] }.merge(attributes.slice(*FIELDS))+ validate!(values)+ mutate do+ previous = id ? find(id) : nil+ check_revision!(previous, revision) if previous+ if !previous && all.size >= MAX_THEMES+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.limit"))+ end+ theme =+ values.merge(+ "id" => previous&.fetch("id") || SecureRandom.uuid,+ "revision" => previous ? previous["revision"] + 1 : 1,+ "source" => source || previous&.dig("source"),+ "locally_modified" => source.nil? && previous&.dig("source").present?,+ )+ PluginStore.set(STORE, "theme:#{theme["id"]}", theme)+ audit(user, "save", theme)+ theme+ end+ end++ def self.activate(id, revision:, user:)+ mutate do+ theme = find(id)+ check_revision!(theme, revision)+ # Readers use a copy, never the mutable editor or Git source.+ theme = theme.merge("snapshot" => SecureRandom.uuid)+ PluginStore.set(STORE, "snapshot:#{theme["snapshot"]}", theme)+ PluginStore.set(STORE, "active", theme)+ PluginStoreRow+ .where(plugin_name: STORE)+ .where("key LIKE 'snapshot:%'")+ .order(id: :desc)+ .offset(20)+ .destroy_all+ audit(user, "activate", theme)+ theme+ end+ end++ def self.destroy(id, revision:, user:)+ mutate do+ theme = find(id)+ check_revision!(theme, revision)+ if active["id"] == id+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.active_delete"))+ end+ PluginStore.remove(STORE, "theme:#{id}")+ audit(user, "delete", theme)+ end+ end++ def self.preview_token(theme)+ verifier.generate(+ { "id" => theme["id"], "revision" => theme["revision"] },+ expires_in: 1.hour,+ )+ end++ def self.from_preview(token)+ data = verifier.verified(token)+ raise Discourse::NotFound unless data.is_a?(Hash)+ if data["working"]+ stored = Discourse.redis.get("blog-theme-preview:#{data["working"]}")+ raise Discourse::NotFound unless stored+ return JSON.parse(stored)+ end+ theme = find(data["id"])+ raise Discourse::NotFound unless theme["revision"] == data["revision"]+ theme+ end++ def self.working_preview(attributes, user:)+ values = TEMPLATE_FIELDS.to_h { |field| [field, ""] }.merge(attributes.slice(*FIELDS))+ # Keep ordinary validation, but allow syntax errors to be inspected in the preview.+ validate!(values.merge(TEMPLATE_FIELDS.to_h { |field| [field, ""] }))+ TEMPLATE_FIELDS.each do |field|+ unless values[field].is_a?(String) && values[field].valid_encoding? &&+ values[field].bytesize <= TemplateRenderer::MAX_TEMPLATE_BYTES+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.template_invalid"))+ end+ end+ key = SecureRandom.hex(32)+ DistributedMutex.synchronize("blog-theme-preview-#{user.id}") do+ index = "blog-theme-preview-index:#{user.id}"+ keys = JSON.parse(Discourse.redis.get(index) || "[]")+ keys << key+ if keys.length > 3+ keys+ .shift(keys.length - 3)+ .each { |old_key| Discourse.redis.del("blog-theme-preview:#{old_key}") }+ end+ Discourse.redis.setex("blog-theme-preview:#{key}", 15.minutes.to_i, values.to_json)+ Discourse.redis.setex(index, 15.minutes.to_i, keys.to_json)+ end+ verifier.generate({ "working" => key }, expires_in: 15.minutes)+ end++ def self.validate!(values)+ valid = FIELDS.all? { |field| values[field].is_a?(String) }+ valid &&= values["name"].strip.present? && values["name"].length <= 100+ valid &&=+ %w[accent_color paper_color ink_color].all? do |field|+ values[field].match?(/\A[0-9a-fA-F]{6}\z/)+ end+ valid &&=+ %w[css javascript].all? do |field|+ values[field].valid_encoding? && values[field].bytesize <= MAX_CODE_BYTES+ end+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.invalid")) unless valid+ TEMPLATE_FIELDS.each do |field|+ TemplateRenderer.validate!(values[field], page: field.delete_prefix("template_"))+ end+ end+ private_class_method :validate!++ def self.check_revision!(theme, revision)+ unless theme["revision"].to_s == revision.to_s+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.stale"))+ end+ end+ private_class_method :check_revision!++ def self.mutate(&block)+ DistributedMutex.synchronize("discourse-blog-themes") { PluginStoreRow.transaction(&block) }+ end+ private_class_method :mutate++ def self.audit(user, action, theme)+ StaffActionLogger.new(user).log_custom(+ "blog_theme_#{action}",+ theme_id: theme["id"],+ name: theme["name"],+ revision: theme["revision"],+ )+ end+ private_class_method :audit++ def self.verifier+ Rails.application.message_verifier(+ "discourse-blog-theme-#{RailsMultisite::ConnectionManagement.current_db}",+ )+ end+ private_class_method :verifier+ end+enddiff --git a/plugins/blog/lib/blog/configuration.rb b/plugins/blog/lib/blog/configuration.rbnew file mode 100644index 00000000000..13df7b59941--- /dev/null+++ b/plugins/blog/lib/blog/configuration.rb@@ -0,0 +1,146 @@+# frozen_string_literal: true++module ::Blog+ module Configuration+ ASSET_PREFIXES = %w[+ plugins+ uploads+ assets+ stylesheets+ javascripts+ font+ images+ extra-locales+ svg-sprite+ ].freeze+ PATH_PREFIX = "/blog"++ def self.asset_path?(path)+ ASSET_PREFIXES.include?(path.split("/")[1])+ end++ # Without a custom domain the blog lives under PATH_PREFIX on the forum.+ def self.custom_domain?+ SiteSetting.blog_url.present? && URI(SiteSetting.blog_url).host != Discourse.current_hostname+ rescue URI::InvalidURIError+ false+ end++ def self.origin+ custom_domain? ? SiteSetting.blog_url : Discourse.base_url_no_prefix+ end++ def self.base_url+ custom_domain? ? SiteSetting.blog_url : "#{Discourse.base_url}#{PATH_PREFIX}"+ end++ # The reader keeps the prefix on a custom domain too, so one client route serves both modes.+ def self.review_url+ "#{custom_domain? ? origin : Discourse.base_url}#{PATH_PREFIX}/review"+ end++ def self.blog_host?(request)+ UpcomingChanges.enabled?(:blog_enabled) && custom_domain? && request.host == URI(origin).host+ end++ # Whether a public blog page may be served for this request in the current mode.+ def self.blog_request?(request)+ public_enabled? && (!custom_domain? || blog_host?(request))+ end++ # The request path relative to the blog root, matching stored article paths.+ def self.relative_path(request)+ return request.path_info if custom_domain?+ request.path_info.delete_prefix(PATH_PREFIX).presence || "/"+ end++ def self.public_enabled?+ UpcomingChanges.enabled?(:blog_enabled) && !SiteSetting.login_required &&+ !SiteSetting.secure_uploads && !SiteSetting.prevent_anons_from_downloading_files+ end++ def self.error+ if SiteSetting.login_required || SiteSetting.secure_uploads+ return I18n.t("blog.errors.private_site")+ elsif SiteSetting.prevent_anons_from_downloading_files+ return I18n.t("blog.errors.anonymous_uploads")+ end++ category = Category.find_by(id: SiteSetting.blog_category)+ drafts = Category.find_by(id: SiteSetting.blog_drafts_category)++ return I18n.t("blog.errors.category") if !category || category.read_restricted?++ if !drafts || !drafts.read_restricted? || category.id == drafts.id ||+ drafts.id == SiteSetting.shared_drafts_category.to_i ||+ drafts.category_groups.where.not(group_id: editorial_group_ids).exists?+ return I18n.t("blog.errors.drafts_category")+ end+ nil+ end++ def self.ensure_ready!+ raise Discourse::InvalidParameters.new(error) if error+ end++ def self.publisher?(user)+ role_user?(user) &&+ (user.admin? || in_role_groups?(user, SiteSetting.blog_publisher_groups_map))+ end++ def self.editor?(user)+ publisher?(user) ||+ (role_user?(user) && in_role_groups?(user, SiteSetting.blog_editor_groups_map))+ end++ def self.contributor?(user)+ editor?(user) ||+ (role_user?(user) && in_role_groups?(user, SiteSetting.blog_contributor_groups_map))+ end++ def self.in_role_groups?(user, groups)+ return true if groups.include?(Group::AUTO_GROUPS[:staff]) && user.staff?+ return true if groups.include?(Group::AUTO_GROUPS[:admins]) && user.admin?+ return true if groups.include?(Group::AUTO_GROUPS[:moderators]) && user.moderator?+ user.in_any_groups?(+ groups -+ [+ Group::AUTO_GROUPS[:staff],+ Group::AUTO_GROUPS[:admins],+ Group::AUTO_GROUPS[:moderators],+ ],+ )+ end+ private_class_method :in_role_groups?++ def self.editorial_group_ids+ (+ [Group::AUTO_GROUPS[:admins], Group::AUTO_GROUPS[:moderators], Group::AUTO_GROUPS[:staff]] ++ SiteSetting.blog_contributor_groups_map + SiteSetting.blog_editor_groups_map ++ SiteSetting.blog_publisher_groups_map+ ).uniq+ end++ def self.role_user?(user)+ UpcomingChanges.enabled?(:blog_enabled) && user&.active? && !user.suspended? &&+ !user.silenced?+ end+ private_class_method :role_user?++ def self.ensure_publisher!(user, topic)+ raise Discourse::InvalidAccess unless publisher?(user)+ ensure_editor!(user, topic)+ end++ def self.ensure_editor!(user, topic)+ raise Discourse::InvalidAccess unless contributor?(user)+ user.guardian.ensure_can_see!(topic)+ raise Discourse::InvalidAccess unless editor?(user) || topic.user_id == user.id+ categories = [SiteSetting.blog_category.to_i, SiteSetting.blog_drafts_category.to_i]+ if topic.private_message? || topic.shared_draft? || !categories.include?(topic.category_id) ||+ topic.category&.topic_id == topic.id || topic.deleted_at || !topic.visible+ raise Discourse::InvalidAccess+ end+ end+ end+enddiff --git a/plugins/blog/lib/blog/editor_query.rb b/plugins/blog/lib/blog/editor_query.rbnew file mode 100644index 00000000000..211c046e72e--- /dev/null+++ b/plugins/blog/lib/blog/editor_query.rb@@ -0,0 +1,86 @@+# frozen_string_literal: true++module ::Blog+ class EditorQuery+ FILTERS = %w[all drafts published unpublished].freeze+ MAX_QUERY_LENGTH = 100++ def self.call(guardian, filter: "all", query: "")+ raise Discourse::InvalidParameters.new(:filter) if FILTERS.exclude?(filter)+ if !query.is_a?(String) || query.length > MAX_QUERY_LENGTH+ raise Discourse::InvalidParameters.new(:q)+ end++ topics =+ Topic+ .secured(guardian)+ .listable_topics+ .where(+ category_id: [SiteSetting.blog_category.to_i, SiteSetting.blog_drafts_category.to_i],+ )+ .where.not(id: Category.where.not(topic_id: nil).select(:topic_id))++ topics =+ topics.where.not(+ id:+ Publication+ .where.not(draft_topic_id: nil)+ .where("draft_topic_id <> topic_id")+ .select(:draft_topic_id),+ )+ topics =+ topics.where.not(+ id:+ Publication+ .where.not(discussion_topic_id: nil)+ .where("discussion_topic_id <> topic_id")+ .select(:discussion_topic_id),+ )+ visible_sources = Topic.secured(guardian).select(:id)+ topics =+ topics.where.not(+ id:+ Publication+ .where.not(draft_topic_id: nil)+ .where.not(draft_topic_id: visible_sources)+ .select(:topic_id),+ )+ topics = topics.where(user_id: guardian.user.id) unless Configuration.editor?(guardian.user)++ live_ids = Publication.publicly_visible.select("blog_publications.topic_id")+ topics =+ case filter+ when "drafts"+ topics+ .where(category_id: SiteSetting.blog_drafts_category.to_i)+ .where.not(id: Publication.where(published: true).select(:topic_id))+ when "published"+ topics.where(id: live_ids)+ when "unpublished"+ topics.where(category_id: SiteSetting.blog_category.to_i).where.not(id: live_ids)+ else+ topics+ end++ if query.strip.present?+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(query.strip)}%"+ path_matches =+ Publication+ .where("path ILIKE ? OR draft_metadata->>'path' ILIKE ?", pattern, pattern)+ .or(+ Publication.where(+ draft_topic_id:+ Topic.where("title ILIKE ? OR slug ILIKE ?", pattern, pattern).select(:id),+ ),+ )+ .select(:topic_id)+ topics =+ topics.where("topics.title ILIKE ? OR topics.slug ILIKE ?", pattern, pattern).or(+ topics.where(id: path_matches),+ )+ end++ topics.order(updated_at: :desc, id: :desc)+ end+ end+enddiff --git a/plugins/blog/lib/blog/enforce_hostname_extension.rb b/plugins/blog/lib/blog/enforce_hostname_extension.rbnew file mode 100644index 00000000000..a51344956d4--- /dev/null+++ b/plugins/blog/lib/blog/enforce_hostname_extension.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++module ::Blog+ module EnforceHostnameExtension+ def call(env)+ if blog_http_host?(env[Rack::HTTP_HOST])+ env[Rack::Request::HTTP_X_FORWARDED_HOST] = nil+ return @app.call(env)+ end++ super+ end++ private++ def blog_http_host?(http_host)+ return false unless UpcomingChanges.enabled?(:blog_enabled) && Configuration.custom_domain?++ origin = URI(Configuration.origin)+ return http_host == "#{origin.host}:#{origin.port}" if origin.port != origin.default_port++ http_host == origin.host || http_host == "#{origin.host}:#{origin.default_port}"+ rescue URI::InvalidURIError+ false+ end+ end+enddiff --git a/plugins/blog/lib/blog/engine.rb b/plugins/blog/lib/blog/engine.rbnew file mode 100644index 00000000000..7f8e1122447--- /dev/null+++ b/plugins/blog/lib/blog/engine.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++module ::Blog+ class Engine < ::Rails::Engine+ engine_name PLUGIN_NAME+ isolate_namespace Blog+ # The plugin loader already registers these tasks.+ paths["lib/tasks"] = []+ config.autoload_paths << File.join(config.root, "lib")+ end+enddiff --git a/plugins/blog/lib/blog/guardian_extensions.rb b/plugins/blog/lib/blog/guardian_extensions.rbnew file mode 100644index 00000000000..721e75ac60a--- /dev/null+++ b/plugins/blog/lib/blog/guardian_extensions.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++module ::Blog+ module GuardianExtensions+ def can_edit_post?(post)+ if post.is_first_post? && blog_public_topic?(post.topic)+ return(+ Thread.current[:blog_publishing_topic] == post.topic_id &&+ Configuration.publisher?(user) && can_see?(post.topic)+ )+ end+ if post.is_first_post? && blog_editorial_topic?(post.topic) && !post.hidden? &&+ !post.deleted_at && (!post.locked? || is_staff?)+ return true+ end+ super+ end++ def can_edit_topic?(topic)+ if blog_public_topic?(topic)+ return(+ Thread.current[:blog_publishing_topic] == topic.id && Configuration.publisher?(user) &&+ can_see?(topic)+ )+ end+ return true if blog_editorial_topic?(topic) && (!topic.first_post&.locked? || is_staff?)+ super+ end++ private++ def blog_public_topic?(topic)+ UpcomingChanges.enabled?(:blog_enabled) &&+ topic&.category_id == SiteSetting.blog_category.to_i &&+ Publication+ .where(discussion_topic_id: topic.id)+ .where.not(published_revision_id: nil)+ .exists?+ end++ def blog_editorial_topic?(topic)+ UpcomingChanges.enabled?(:blog_enabled) && topic &&+ topic.category_id == SiteSetting.blog_drafts_category.to_i && !topic.deleted_at &&+ !topic.archived? && !topic.private_message? && topic.category&.topic_id != topic.id &&+ Configuration.contributor?(user) &&+ (Configuration.editor?(user) || topic.user_id == user.id) && can_see?(topic)+ end+ end+enddiff --git a/plugins/blog/lib/blog/publication_entry.rb b/plugins/blog/lib/blog/publication_entry.rbnew file mode 100644index 00000000000..8c0209848a3--- /dev/null+++ b/plugins/blog/lib/blog/publication_entry.rb@@ -0,0 +1,107 @@+# frozen_string_literal: true++module ::Blog+ # The editorial view of one article, shared by the editor endpoints and the topic page.+ class PublicationEntry+ def self.for_viewer(topic, user)+ return unless UpcomingChanges.enabled?(:blog_enabled)+ return if topic.private_message?+ categories = [SiteSetting.blog_category.to_i, SiteSetting.blog_drafts_category.to_i]+ return if categories.exclude?(topic.category_id)+ return unless Configuration.contributor?(user)++ publication = Publication.for_topic(topic)+ Configuration.ensure_editor!(user, publication.editorial_topic || publication.topic)+ new(publication, user: user, viewed_topic: topic).to_h+ rescue Discourse::InvalidAccess+ nil+ end++ def initialize(publication, user:, topic: nil, viewed_topic: nil, live: nil)+ @publication = publication+ @user = user+ @topic = topic || publication.topic+ @viewed_topic = viewed_topic+ @live = live+ end++ def to_h+ source = publication.editorial_topic+ metadata = publication.editorial_metadata+ changes = publication.pending_changes+ {+ id: topic.id,+ role: role,+ status: status(changes),+ title: source&.title || topic.title,+ public_title: publication.published_revision&.title,+ public_excerpt: publication.published_revision&.data&.[]("excerpt"),+ public_path: publication.published_revision&.data&.[]("path"),+ draft_correction: changes.any?,+ changes: changes,+ edits_since_publish: publication.edits_since_publish,+ draft_updated_at: source&.first_post&.updated_at,+ topic_url: source&.url || topic.url,+ source_topic_id: source&.id,+ source_url: source&.url,+ discussion_url: publication.discussion_topic&.url,+ preview_url: publication.preview_url,+ url: publication.url,+ path: metadata["path"],+ excerpt: metadata["excerpt"],+ featured: metadata["featured"],+ published_at: metadata["published_at"],+ last_published_at: publication.last_published_at,+ published: publication.published?,+ published_revision_id: publication.published_revision_id,+ live: live.nil? ? publication.publicly_visible? : live,+ draft: !publication.published? && source.present?,+ replies: [publication.discussion_topic&.posts_count.to_i - 1, 0].max,+ can_publish: Configuration.publisher?(user),+ review_feedback_count: source ? feedback_count(source) : 0,+ active_review_links: source ? Review.where(topic_id: source.id).unexpired.count : 0,+ submitted_revision: revision_entry(publication.submitted_revision),+ approved_revision: revision_entry(publication.approved_revision),+ scheduled_revision: revision_entry(publication.scheduled_revision),+ scheduled_at: publication.scheduled_at,+ schedule_error: publication.schedule_error,+ }+ end++ private++ attr_reader :publication, :user, :topic, :viewed_topic, :live++ def role+ return "source" unless viewed_topic+ return "draft" if viewed_topic.id == publication.editorial_topic&.id+ # Any public Blog-category topic is a discussion, whether or not it has been published yet.+ if viewed_topic.id == publication.discussion_topic_id ||+ viewed_topic.category_id == SiteSetting.blog_category.to_i+ return "discussion"+ end+ "source"+ end++ def status(changes)+ return "scheduled" if publication.scheduled_at+ return "unpublished" if !publication.published? && publication.published_revision_id+ return "changes_pending" if publication.published? && changes.any?+ publication.published? ? "live" : "draft"+ end++ def feedback_count(source)+ ReviewFeedback.joins(:review).where(blog_reviews: { topic_id: source.id }).count+ end++ def revision_entry(revision)+ return nil unless revision+ {+ id: revision.id,+ title: revision.title,+ approved_by: revision.approver&.username,+ preview_url: "#{publication.preview_url}?revision_id=#{revision.id}",+ }+ end+ end+enddiff --git a/plugins/blog/lib/blog/syntax_highlighter.rb b/plugins/blog/lib/blog/syntax_highlighter.rbnew file mode 100644index 00000000000..d6596fba65f--- /dev/null+++ b/plugins/blog/lib/blog/syntax_highlighter.rb@@ -0,0 +1,17 @@+# frozen_string_literal: true++module ::Blog+ module SyntaxHighlighter+ def self.source+ @source ||= File.read(File.expand_path("../../vendor/highlightjs/core.min.js", __dir__))+ end++ def self.version+ @version ||= Digest::SHA256.hexdigest(source)+ end++ def self.path+ "/blog-highlight/#{version}.js"+ end+ end+enddiff --git a/plugins/blog/lib/blog/template_renderer.rb b/plugins/blog/lib/blog/template_renderer.rbnew file mode 100644index 00000000000..7956987fbc0--- /dev/null+++ b/plugins/blog/lib/blog/template_renderer.rb@@ -0,0 +1,120 @@+# frozen_string_literal: true++require "liquid"++module ::Blog+ class TemplateRenderer+ PAGES = %w[layout index article about not_found].freeze+ MAX_TEMPLATE_BYTES = 65_536+ TEMPLATE_ROOT = File.expand_path("../../templates", __dir__)++ # Only server-produced fragments may bypass variable escaping.+ class Html < String+ end++ class Context < Liquid::Context+ def evaluate(object)+ value = super+ # Loop tags materialize ranges before the normal render accounting runs.+ raise Liquid::MemoryError, "Range limit exceeded" if value.is_a?(Range) && value.size > 1000+ value+ end+ end++ ENVIRONMENT =+ Liquid::Environment.build(+ tags:+ Liquid::Tags::STANDARD_TAGS.slice(+ "if",+ "unless",+ "case",+ "for",+ "break",+ "continue",+ "assign",+ "capture",+ "comment",+ "raw",+ "cycle",+ "increment",+ "decrement",+ ),+ file_system: Liquid::BlankFileSystem.new,+ error_mode: :strict2,+ ) do |environment|+ environment.default_resource_limits = {+ render_length_limit: 2.megabytes,+ render_score_limit: 100_000,+ assign_score_limit: 256.kilobytes,+ cumulative_render_score_limit: 100_000,+ cumulative_assign_score_limit: 256.kilobytes,+ }+ end++ def self.validate!(source, page: nil)+ unless source.is_a?(String) && source.valid_encoding? && source.bytesize <= MAX_TEMPLATE_BYTES+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.template_invalid"))+ end+ parse(source)+ rescue Liquid::Error => error+ raise Discourse::InvalidParameters.new(+ I18n.t(+ "blog.themes.template_parse_error",+ error: [page, error.message].compact.join(": "),+ ),+ )+ end++ def self.render(page, assigns, theme:, custom: true, diagnostics: false)+ raise ArgumentError if PAGES.exclude?(page)+ override = custom && theme["template_#{page}"].presence+ source = override || builtin(page)+ if diagnostics+ begin+ return render_source(source, assigns, strict_variables: true)+ rescue Liquid::UndefinedVariable => error+ return(diagnostic(page, error, warning: true) + render_source(source, assigns))+ end+ end+ render_source(source, assigns)+ rescue Liquid::Error => error+ return diagnostic(page, error) if diagnostics+ raise unless override+ Rails.logger.warn("Blog template #{page} failed: #{error.class}")+ render_source(builtin(page), assigns)+ end++ def self.diagnostic(page, error, warning: false)+ message =+ I18n.t(+ "blog.themes.preview_diagnostic",+ template: page,+ line: error.line_number || "?",+ message: error.message,+ )+ "<section class=\"blog__preview\" role=\"alert\" data-template-diagnostic=\"#{warning ? "warning" : "error"}\"><p>#{ERB::Util.html_escape(message)}</p></section>"+ end+ private_class_method :diagnostic++ def self.builtin(page)+ raise ArgumentError if PAGES.exclude?(page)+ File.read(File.join(TEMPLATE_ROOT, "#{page}.liquid"))+ end++ def self.parse(source)+ Liquid::Template.parse(source, environment: ENVIRONMENT, line_numbers: true)+ end+ private_class_method :parse++ def self.render_source(source, assigns, strict_variables: false)+ context = Context.build(environment: ENVIRONMENT, environments: assigns, rethrow_errors: true)+ parse(source).render!(+ context,+ strict_filters: true,+ strict_variables: strict_variables,+ global_filter: ->(value) { value.is_a?(Html) ? value : ERB::Util.html_escape(value.to_s) },+ )+ end+ private_class_method :render_source+ end+enddiff --git a/plugins/blog/lib/blog/theme_exporter.rb b/plugins/blog/lib/blog/theme_exporter.rbnew file mode 100644index 00000000000..d7dc1c9b53c--- /dev/null+++ b/plugins/blog/lib/blog/theme_exporter.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++require "zip"++module ::Blog+ class ThemeExporter+ def self.export(theme)+ files = {+ "blog-theme.json" =>+ JSON.pretty_generate(+ theme.slice("name", "accent_color", "paper_color", "ink_color").merge("version" => 2),+ ),+ "blog.css" => theme["css"],+ "blog.js" => theme["javascript"],+ }+ TemplateRenderer::PAGES.each do |page|+ files["templates/#{page}.liquid"] = theme["template_#{page}"]+ end++ Zip::OutputStream+ .write_buffer do |archive|+ files.each do |name, content|+ archive.put_next_entry(name)+ archive.write(content.to_s)+ end+ end+ .string+ end+ end+enddiff --git a/plugins/blog/lib/blog/theme_importer.rb b/plugins/blog/lib/blog/theme_importer.rbnew file mode 100644index 00000000000..6452a2ab23c--- /dev/null+++ b/plugins/blog/lib/blog/theme_importer.rb@@ -0,0 +1,126 @@+# frozen_string_literal: true++require "compression/safe_zip_reader"++module ::Blog+ class ThemeImporter+ class GitSource < ThemeStore::GitImporter+ def import!+ # Blog sources do not use framework compatibility refs or additional fetches.+ clone!+ end++ protected++ def redirected_uri+ uri = super+ raise_import_error! unless uri.scheme == "https"+ uri+ end++ def clone_args(url, config = {})+ super(+ url,+ config.merge(+ "protocol.allow" => "never",+ "protocol.https.allow" => "always",+ "http.sslVerify" => "true",+ ),+ )+ end+ end++ def self.import(repository:, branch:, user:, id: nil, revision: nil)+ if !repository.is_a?(String) || (!branch.nil? && !branch.is_a?(String))+ raise Discourse::InvalidParameters.new(:repository)+ end+ uri = URI.parse(repository)+ unless repository.length <= 1000 && uri.is_a?(URI::HTTPS) && uri.host.present? &&+ !uri.userinfo && !uri.query && !uri.fragment+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.repository_invalid"))+ end+ branch = branch.presence+ if branch && (branch.length > 200 || branch.start_with?("-") || branch.match?(/[\x00-\x20]/))+ raise Discourse::InvalidParameters.new(:branch)+ end+ user.guardian.ensure_allowed_theme_repo_import!(repository)+ importer = GitSource.new(repository, branch: branch)+ begin+ importer.import!+ values =+ read_values do |name, limit, required: false|+ read_file(importer, name, limit, required: required)+ end+ BlogTheme.save(+ values,+ user: user,+ id: id,+ revision: revision,+ source: {+ "repository" => repository,+ "branch" => branch,+ "commit" => importer.version,+ },+ )+ ensure+ importer.cleanup!+ end+ rescue JSON::ParserError, URI::InvalidURIError+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.manifest_invalid"))+ end++ def self.import_file(file:, user:)+ unless file.is_a?(ActionDispatch::Http::UploadedFile) &&+ File.extname(file.original_filename).downcase == ".zip" && file.size <= 2.megabytes+ raise Discourse::InvalidParameters.new(:file)+ end++ Compression::SafeZipReader.open(file.path, max_entries: 1000) do |reader|+ values =+ read_values do |name, limit, required: false|+ reader.read_entry(name, max_bytes: limit, required: required)&.force_encoding(+ Encoding::UTF_8,+ ) || ""+ end+ BlogTheme.save(values, user: user)+ end+ rescue Compression::SafeZipReader::Error, Zip::Error, Zlib::Error+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.archive_invalid"))+ end++ def self.read_values+ manifest = JSON.parse(yield("blog-theme.json", 4096, required: true))+ unless manifest.is_a?(Hash) && [1, 2].include?(manifest["version"])+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.manifest_invalid"))+ end+ values = manifest.slice("name", "accent_color", "paper_color", "ink_color")+ values["css"] = yield("blog.css", BlogTheme::MAX_CODE_BYTES)+ values["javascript"] = yield("blog.js", BlogTheme::MAX_CODE_BYTES)+ if manifest["version"] == 2+ TemplateRenderer::PAGES.each do |page|+ values["template_#{page}"] = yield(+ "templates/#{page}.liquid",+ TemplateRenderer::MAX_TEMPLATE_BYTES+ )+ end+ end+ values+ rescue JSON::ParserError+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.manifest_invalid"))+ end+ private_class_method :read_values++ def self.read_file(importer, name, limit, required: false)+ path = importer.real_path(name)+ unless path && path.start_with?("#{importer.temp_folder}/") && File.file?(path)+ return "" unless required+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.manifest_invalid"))+ end+ if importer.file_size(name) > limit+ raise Discourse::InvalidParameters.new(I18n.t("blog.themes.file_too_large", file: name))+ end+ importer[name]+ end+ private_class_method :read_file+ end+enddiff --git a/plugins/blog/lib/blog/topic_extensions.rb b/plugins/blog/lib/blog/topic_extensions.rbnew file mode 100644index 00000000000..dfa0b2258f1--- /dev/null+++ b/plugins/blog/lib/blog/topic_extensions.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++module ::Blog+ module TopicExtensions+ def duplicate_title_candidates+ candidates = super+ return candidates unless UpcomingChanges.enabled?(:blog_enabled)++ publication =+ Blog::Publication+ .where(draft_topic_id: id)+ .or(Blog::Publication.where(discussion_topic_id: id))+ .first if persisted?+ if publication+ candidates =+ candidates.where.not(+ id: [publication.draft_topic_id, publication.discussion_topic_id].compact,+ )+ end+ copy = Thread.current[:blog_copy]+ if new_record? && copy && category_id == copy[:category_id]+ candidates = candidates.where.not(id: copy[:source_id])+ end+ candidates+ end+ end+enddiff --git a/plugins/blog/lib/blog/topic_view_extension.rb b/plugins/blog/lib/blog/topic_view_extension.rbnew file mode 100644index 00000000000..e7a8169db21--- /dev/null+++ b/plugins/blog/lib/blog/topic_view_extension.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++module ::Blog+ module TopicViewExtension+ def canonical_path+ if Configuration.public_enabled? && @page.to_i <= 1 &&+ topic.category_id == SiteSetting.blog_category.to_i+ publication = Publication.publicly_visible.find_by(discussion_topic_id: topic.id)+ return publication.url if publication+ end+ super+ end+ end+enddiff --git a/plugins/blog/lib/tasks/demo.rake b/plugins/blog/lib/tasks/demo.rakenew file mode 100644index 00000000000..943e7b6ae4e--- /dev/null+++ b/plugins/blog/lib/tasks/demo.rake@@ -0,0 +1,302 @@+# frozen_string_literal: true++module Blog+ module DemoUsers+ def self.admin+ User.real.where(admin: true).order(:id).first || abort("Create an admin user first")+ end++ def self.members(limit)+ User+ .real+ .activated+ .not_suspended+ .not_silenced+ .not_staged+ .where(admin: false)+ .order("RANDOM()")+ .limit(limit)+ .to_a+ end+ end+end++namespace :blog do+ desc "Set up an editorial demo on the local development site"+ task demo: :environment do+ abort "Demo content is only available in development" unless Rails.env.development?+ admin = Blog::DemoUsers.admin+ blog = Category.find_by(id: SiteSetting.blog_category) || Category.find_by(slug: "blog")+ unless blog+ blog = Category.new(name: "Blog", slug: "blog", user: admin)+ blog.set_permissions(everyone: :create_post, staff: :full)+ blog.save!+ end+ drafts =+ Category.find_by(id: SiteSetting.blog_drafts_category) ||+ Category.find_by(slug: "blog-drafts")+ unless drafts+ drafts = Category.new(name: "Blog editorial", slug: "blog-drafts", user: admin)+ drafts.set_permissions(staff: :full)+ drafts.save!+ end+ SiteSetting.blog_category = blog.id+ SiteSetting.blog_drafts_category = drafts.id+ SiteSetting.blog_title = "Fieldnotes"+ SiteSetting.blog_description =+ "Ideas in progress, things we’ve learned, and conversations worth having."+ SiteSetting.blog_about = <<~MD+ A little space for longer thoughts, built right into our community.++ **Fieldnotes** is a working demonstration of Discourse Blog. Every article starts as a topic, and every conversation stays connected to the story that started it.++ ## A place to think out loud++ We believe the interesting part often happens after you press publish. Ask a question, share an experience, or offer a different perspective in the discussion beneath each article.++ These sample articles are demo content. Replace them with your own when you are ready.+ MD+ SiteSetting.blog_enabled = true+ Blog::Configuration.ensure_ready!+ SiteSetting.embed_full_app = true+ SiteSetting.embed_full_app_signin_flow = true+ blog_uri = URI(Blog::Configuration.origin)+ embed_host =+ blog_uri.port == blog_uri.default_port ? blog_uri.host : "#{blog_uri.host}:#{blog_uri.port}"+ EmbeddableHost.find_or_create_by!(host: embed_host) do |host|+ host.category_id = blog.id+ # Under /blog the embedding host is the forum itself, so only blog pages may embed.+ if !Blog::Configuration.custom_domain?+ host.allowed_paths = "^#{Discourse.base_path}#{Blog::Configuration::PATH_PREFIX}(/|$)"+ end+ end++ examples = [+ {+ path: "/a-small-home-for-big-ideas",+ title: "A small home for big ideas",+ excerpt:+ "A blog should feel like a quiet place to read, with an open door to the conversation. This is our first step toward that.",+ featured: true,+ raw: <<~MD,+ *This is a demo article. Make yourself at home and try the conversation below.*++ There is something satisfying about a page that gets out of your way. A title, a little context, and room for an idea to develop.++ That is the starting point for this blog: **a calm reading experience, connected to a living community.** No separate publishing system. No comments database drifting away from the article. Just one place to write, and two good ways to experience it.++ ## Write where the conversation happens++ Every article begins as a Discourse topic. Before it is ready, it lives in a private drafts category. You can revise it, add images, ask fellow editors for feedback, and preview the finished page.++ Publishing is an explicit decision. It gives the story a permanent address and opens the discussion to everyone.++ > The article is the beginning of the conversation, not the end of it.++ ## Small by default++ The words arrive as ordinary HTML. You do not need to load an application to read them. When you reach the discussion, Discourse joins you there: real accounts, live replies, and the moderation tools the community already knows.++ A few things we care about:++ - Links that keep working when a title changes.+ - A feed you can subscribe to in your favorite reader.+ - Drafts that stay out of the public archive.+ - Space for thoughtful responses, not just a reaction count.++ ## An invitation++ This is a working first version, not a finished manifesto. Scroll down, say hello, and tell us what a good community blog should feel like.+ MD+ },+ {+ path: "/the-case-for-writing-in-public",+ title: "The case for writing in public",+ excerpt:+ "Useful writing doesn’t have to be definitive. Sometimes the most valuable thing you can share is the question you are still working through.",+ raw: <<~MD,+ *Demo content for exploring the blog.*++ A polished answer is useful. But a well-framed question can be even more useful, especially when it reaches people who have been thinking about the same thing from another direction.++ ## Leave a little room++ We tend to imagine publishing as the final step: research, draft, polish, publish. In a community, it is often better understood as a midpoint.++ You bring what you have learned. Someone else brings the exception. A third person supplies the example that makes the whole thing click.++ That does not mean publishing carelessly. It means being honest about what is settled and what is still an experiment.++ ## Three questions before publishing++ 1. What is the one idea I want a reader to take away?+ 2. What would help someone disagree constructively?+ 3. Where should the conversation go next?++ The last question is why the replies belong alongside the article. Context matters, and the best follow-up should not disappear into a different system.++ **What have you learned by sharing an unfinished idea?**+ MD+ },+ {+ path: "/keeping-the-web-readable",+ title: "Keeping the web readable",+ excerpt:+ "Permanent links, readable pages, and a good RSS feed are small features with a surprisingly long life.",+ raw: <<~MD,+ *Demo content for exploring the blog.*++ Some web features age beautifully. A link you bookmarked years ago still opens. An RSS reader quietly brings you a new article. A page prints without losing the thing you came to read.++ None of these needs to be complicated.++ ## Start with the document++ The simplest useful representation of an article is still a document: a heading, some paragraphs, and meaningful links.++ ```html+ <article>+ <h1>An idea worth sharing</h1>+ <p>Start with the words.</p>+ </article>+ ```++ Add interaction where it helps, rather than making the words depend on it.++ ## Respect the address++ Titles evolve. Categories change. A permanent link should survive both. If an address really must change, leave a redirect behind for the people who trusted the old one.++ ## Let readers choose++ Visit the site, subscribe to the feed, or join the discussion. A good publication does not insist that everyone reads in the same way.+ MD+ },+ ]+ examples.each_with_index do |example, index|+ next if Blog::Path.exists?(path: example[:path])+ post =+ PostCreator.create!(+ admin,+ title: example[:title],+ raw: example[:raw],+ category: drafts.id,+ skip_rate_limits: true,+ )+ publication = Blog::Publication.for_topic(post.topic)+ publication.save_metadata!(+ admin,+ path: example[:path],+ excerpt: example[:excerpt],+ featured: example[:featured] || false,+ published_at: index.days.ago,+ )+ publication.publish!(admin)+ end+ unless Topic.where(category_id: drafts.id, title: "Draft: what we are building next").exists?+ PostCreator.create!(+ admin,+ category: drafts.id,+ title: "Draft: what we are building next",+ skip_rate_limits: true,+ raw: <<~MD,+ This is a private demo draft. It is not listed on the public blog.++ ## The next chapter++ Use the edit button to make this your own. The normal Discourse composer provides uploads, Markdown, rich text, revisions, and autosave.++ When you are ready, use the publication panel above this post. Open **Article settings** to give the article a short excerpt and a permanent path, preview it, then choose **Publish**.++ Publishing copies the approved article into a new public discussion in the blog category. This topic and its replies stay private, so editorial notes here are never published.+ MD+ )+ end+ replies = {+ "/a-small-home-for-big-ideas" => [+ [+ :first_reader,+ "The separation feels right: a quiet article first, then a real conversation. I would love to see more behind-the-scenes posts here.",+ ],+ [+ :admin,+ "Exactly the idea. Try replying here from the blog — this is the same discussion you can open in the community.",+ ],+ [+ :first_reader,+ "The quiet reading experience is what sold me. I like being able to finish an article before seeing the conversation, rather than having a sidebar compete for attention.",+ ],+ [+ :second_reader,+ "One thing I would love to see here: follow-up posts that collect what people learned in the comments. Sometimes the best example arrives a week after the original article.",+ ],+ [+ :admin,+ "That is exactly the kind of loop we want: publish an idea, listen, then write something better. A monthly roundup of community discoveries would be a good place to start.",+ ],+ ],+ "/the-case-for-writing-in-public" => [+ [+ :first_reader,+ "The hardest part for me is deciding when something is ready to share. I have started calling my early posts field notes rather than guides. That small change makes it much easier to admit what I do not know yet.",+ ],+ [+ :second_reader,+ "I tried this with a project journal last month. A short post about a failed approach got more useful responses than my polished launch announcement. People could actually see where help was needed.",+ ],+ [+ :admin,+ "A useful rule of thumb: share one concrete observation and one honest question. It gives readers something to respond to without making the post feel unfinished. What did you change after that feedback?",+ ],+ [+ :second_reader,+ "We simplified the onboarding flow instead of adding another help page. Someone pointed out that our instructions were explaining a problem we could just remove. I would not have spotted that on my own.",+ ],+ ],+ "/keeping-the-web-readable" => [+ [+ :second_reader,+ "Thank you for keeping RSS in the picture. My feed reader is still the only place where I get to choose what to read without an algorithm rearranging everything.",+ ],+ [+ :first_reader,+ "Readable also means usable on a slow connection. I opened this on the train and the article was there before the discussion loaded. That is a small detail that makes a big difference.",+ ],+ [+ :admin,+ "The article should never have to wait for the comments application. The same goes for permanent links: changing a headline should not break a bookmark someone saved six months ago.",+ ],+ [+ :first_reader,+ "My other vote is for descriptive links. A sentence that tells me where a link goes is much more useful than a row of identical read-more buttons, especially with a screen reader.",+ ],+ ],+ }++ first_reader, second_reader = Blog::DemoUsers.members(2)+ first_reader ||= admin+ second_reader ||= first_reader+ authors = { admin:, first_reader:, second_reader: }++ replies.each do |path, conversation|+ discussion = Blog::Publication.publicly_visible.find_by(path: path)&.discussion_topic+ next if !discussion+ conversation.each do |role, text|+ raw = "#{text}\n\n*Sample conversation for the demo blog.*"+ # Authors are random on each run, so match on the text alone.+ next if discussion.posts.exists?(raw: raw)++ PostCreator.create!(+ authors.fetch(role),+ topic_id: discussion.id,+ raw: raw,+ skip_rate_limits: true,+ )+ end+ end++ puts "Blog: #{Blog::Configuration.base_url}"+ puts "Editor: #{Discourse.base_url}/blog-editor"+ puts "Categories: Blog=#{blog.id}, private drafts=#{drafts.id}"+ end+enddiff --git a/plugins/blog/package.json b/plugins/blog/package.jsonnew file mode 100644index 00000000000..5baab56b131--- /dev/null+++ b/plugins/blog/package.json@@ -0,0 +1,6 @@+{+ "private": true,+ "dependencies": {+ "discourse": "workspace:@discourse/types@*"+ }+}diff --git a/plugins/blog/plugin.rb b/plugins/blog/plugin.rbnew file mode 100644index 00000000000..328a0308b5e--- /dev/null+++ b/plugins/blog/plugin.rb@@ -0,0 +1,184 @@+# frozen_string_literal: true++# name: blog+# about: A lightweight publication with Discourse authoring and live discussion.+# version: 0.1.0+# authors: Discourse+# url: https://github.com/discourse/discourse/tree/main/plugins/blog+# required_version: 3.6.0++enabled_site_setting :blog_enabled+register_asset "stylesheets/blog-editor.scss"+register_asset "stylesheets/blog-publication-panel.scss"+register_asset "stylesheets/blog-review.scss"+register_asset "stylesheets/blog-post-summary.scss"+register_asset "stylesheets/blog-discussion.scss"+register_asset "stylesheets/admin/blog-admin.scss", :admin+register_svg_icon "pen-to-square"+add_admin_route "blog.admin.title", "blog", use_new_show_route: true++module ::Blog+ PLUGIN_NAME = "blog"+end++require_relative "lib/blog/engine"++register_homepage(+ "blog",+ name: "blog.homepage_option",+ path: "/blog",+ route: "blog/articles#index",+ anonymous: true,+ server_side: true,+ enabled: -> { Blog::Configuration.public_enabled? && !Blog::Configuration.custom_domain? },+)++after_initialize do+ if defined?(Rack::MiniProfiler)+ %w[/blog-highlight/ /blog/blog-highlight/].each do |path|+ Rack::MiniProfiler.config.skip_paths << "#{Discourse.base_path}#{path}"+ end+ end++ add_to_serializer(+ :site,+ :blog_base_url,+ include_condition: -> { UpcomingChanges.enabled?(:blog_enabled) },+ ) { Blog::Configuration.base_url }+ add_to_serializer(:current_user, :can_blog_edit) { Blog::Configuration.contributor?(object) }+ reloadable_patch { ::Guardian.prepend(Blog::GuardianExtensions) }+ reloadable_patch { ::Topic.prepend(Blog::TopicExtensions) }+ if defined?(::Middleware::EnforceHostname)+ reloadable_patch { ::Middleware::EnforceHostname.prepend(Blog::EnforceHostnameExtension) }+ end++ Rails.application.config.filter_parameters += [:review_token]++ add_model_callback(:topic, :before_destroy) do+ Blog::Review.where(topic_id: id).find_each(&:destroy!)+ Blog::Publication+ .where(topic_id: id)+ .or(Blog::Publication.where(draft_topic_id: id))+ .or(Blog::Publication.where(discussion_topic_id: id))+ .find_each(&:destroy!)+ end++ add_model_callback(:topic, :validate) do+ if category_id_changed? && persisted? &&+ category_id_in_database == SiteSetting.blog_drafts_category.to_i+ errors.add(:category_id, I18n.t("blog.editorial.private_source"))+ end+ end++ add_model_callback(:post, :after_update) do+ if post_number == 1 &&+ ((saved_change_to_hidden? && hidden?) || (saved_change_to_deleted_at? && deleted_at))+ Blog::Review.revoke_for_topic!(topic_id)+ end+ end++ add_model_callback(:topic, :after_update) do+ if saved_change_to_category_id? || saved_change_to_deleted_at? || saved_change_to_archetype? ||+ saved_change_to_visible?+ Blog::Review.revoke_for_topic!(id)+ end+ end++ add_to_serializer(+ :post,+ :blog_article,+ include_condition: -> do+ object.is_first_post? && object.word_count.to_i >= 250 &&+ Blog::Configuration.public_enabled? &&+ object.topic.category_id == SiteSetting.blog_category.to_i+ end,+ ) do+ if publication =+ Blog::Publication.publicly_visible.find_by(discussion_topic_id: object.topic_id)+ {+ url: publication.url,+ excerpt: publication.display_excerpt,+ blog_name: SiteSetting.blog_title,+ }+ end+ end++ add_to_serializer(+ :topic_view,+ :blog_publication,+ include_condition: -> { !blog_publication.nil? },+ ) do+ unless instance_variable_defined?(:@blog_publication)+ @blog_publication = Blog::PublicationEntry.for_viewer(object.topic, scope.user)+ end+ @blog_publication+ end++ blog_routes =+ proc do+ get "/" => "blog/articles#index"+ get "/archive" => "blog/articles#index", :defaults => { archive: true }+ get "/tag/:tag" => "blog/articles#index"+ get "/about" => "blog/articles#about"+ get "/blog-theme.css" => "blog/articles#theme_css", :format => false+ get "/blog-highlight/:version.js" => "blog/articles#highlight_js", :format => false+ get "/blog-custom.js" => "blog/articles#theme_js", :format => false+ get "/feed.xml" => "blog/articles#feed", :defaults => { format: "rss" }, :format => false+ get "/sitemap" => "blog/articles#sitemap", :format => true, :constraints => { format: :xml }+ end++ Discourse::Application.routes.prepend do+ constraints(+ ->(request) do+ Blog::Configuration.blog_host?(request) && !Blog::Configuration.asset_path?(request.path)+ end,+ ) do+ get "/session/csrf" => "blog/review_reader#csrf"+ get "/blog/review" => "blog/review_reader#show"+ post "/blog/review/feedback" => "blog/review_reader#feedback"+ get "/review" => redirect { |_, request| request.fullpath.sub("/review", "/blog/review") },+ :format => false+ get "/posts" => redirect { "#{Blog::Configuration.base_url}/" }, :format => false+ %w[/posts.rss /posts.atom].each do |path|+ get path => redirect { "#{Blog::Configuration.base_url}/feed.xml" }, :format => false+ end+ instance_exec(&blog_routes)+ get "/robots.txt" => "blog/articles#robots", :defaults => { format: "text" }, :format => false+ get "/*path" => "blog/articles#show", :format => false+ end+ scope Blog::Configuration::PATH_PREFIX do+ constraints(+ ->(_) { UpcomingChanges.enabled?(:blog_enabled) && !Blog::Configuration.custom_domain? },+ ) do+ get "/review" => "blog/review_reader#show"+ post "/review/feedback" => "blog/review_reader#feedback"+ instance_exec(&blog_routes)+ get "/*path" => "blog/articles#show", :format => false+ end+ constraints(+ ->(_) { UpcomingChanges.enabled?(:blog_enabled) && Blog::Configuration.custom_domain? },+ ) do+ # Temporary, since a site can drop its custom domain and browsers cache 301s.+ get "/(*path)" =>+ redirect(status: 302) { |_, request|+ path =+ request.path_info.delete_prefix(Blog::Configuration::PATH_PREFIX).presence || "/"+ path += "?#{request.query_string}" if request.query_string.present?+ "#{Blog::Configuration.base_url}#{path}"+ },+ :format => false+ end+ end+ # The themes list is served by Blog::ThemesController, which renders the app for page loads.+ %w[appearance identity themes/new themes/import/new themes/:id/edit].each do |path|+ get "/admin/plugins/blog/#{path}" => "admin/plugins#show",+ :defaults => {+ plugin_id: "blog",+ },+ :constraints => AdminConstraint.new+ end+ mount ::Blog::Engine, at: "/"+ end++ reloadable_patch { ::TopicView.prepend(Blog::TopicViewExtension) }+enddiff --git a/plugins/blog/public/blog.css b/plugins/blog/public/blog.cssnew file mode 100644index 00000000000..04eb0cea1a9--- /dev/null+++ b/plugins/blog/public/blog.css@@ -0,0 +1,1225 @@+html {+ color-scheme: light dark;+ scroll-behavior: smooth;+}++.blog {+ --blog-reading-width: 720px;+ --blog-canvas: light-dark(var(--blog-paper-color), var(--secondary));+ --blog-foreground: light-dark(var(--blog-ink-color), var(--primary));+ --blog-muted: color-mix(+ in srgb,+ var(--blog-foreground) 72%,+ var(--blog-canvas)+ );+ --blog-rule: color-mix(+ in srgb,+ var(--blog-foreground) 23%,+ var(--blog-canvas)+ );+ --blog-tint: color-mix(+ in srgb,+ var(--blog-foreground) 5%,+ var(--blog-canvas)+ );+ --blog-accent-soft: color-mix(+ in srgb,+ var(--blog-accent-color) 12%,+ var(--blog-canvas)+ );+ --blog-link-color: light-dark(+ color-mix(in srgb, var(--blog-accent-color) 85%, var(--blog-ink-color)),+ color-mix(in srgb, var(--blog-accent-color) 35%, var(--primary))+ );+ margin: 0;+ background: var(--blog-canvas);+ color: var(--blog-foreground);+ font-family: system-ui, sans-serif;+ font-size: 16px;+ line-height: 1.65;+}++.blog * {+ box-sizing: border-box;+}++.blog a {+ color: var(--blog-link-color);+ text-decoration: none;+ text-underline-offset: 0.2em;+}++.blog a:hover {+ text-decoration: underline;+}++.blog :focus-visible {+ outline: 2px solid var(--blog-link-color);+ outline-offset: 4px;+}++.blog__skip {+ position: absolute;+ inset-block-start: -100px;+}++.blog__skip:focus {+ inset-block-start: 8px;+ background: var(--blog-canvas);+ z-index: 1;+}++.blog__header,+.blog__footer {+ max-width: 1120px;+ margin-inline: auto;+ padding: 28px 32px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 20px;+ flex-wrap: wrap;+}++.blog__header {+ border-bottom: 1px solid var(--blog-rule);+}++.blog__brand {+ color: var(--blog-foreground) !important;+ font-size: 1.4rem;+ font-weight: 750;+ letter-spacing: -0.04em;+}++.blog__brand-dot {+ color: var(--blog-link-color);+}++.blog__nav {+ display: flex;+ flex-wrap: wrap;+ gap: 24px;+ font-size: 0.9rem;+}++.blog__nav a {+ color: var(--blog-muted);+}++.blog__main {+ max-width: 960px;+ margin: auto;+ padding: 0 32px;+ min-height: 65vh;+}++.blog__intro {+ padding: 72px 0 48px;+ border-bottom: 1px solid var(--blog-rule);+}++.blog__eyebrow {+ font-size: 0.75rem;+ font-weight: 650;+ text-transform: uppercase;+ letter-spacing: 0.13em;+ color: var(--blog-link-color);+}++.blog h1,+.blog h2,+.blog h3 {+ line-height: 1.16;+ text-wrap: balance;+}++.blog__intro h1 {+ font-size: clamp(2.7rem, 7vw, 4.7rem);+ font-weight: 650;+ letter-spacing: -0.055em;+ margin: 20px 0;+}++.blog__description {+ max-width: 600px;+ font-size: 1.2rem;+ color: var(--blog-muted);+}++.blog__meta {+ display: flex;+ align-items: center;+ gap: 10px;+ flex-wrap: wrap;+ font-size: 0.8rem;+ color: var(--blog-muted);+}++.blog__badge {+ background: var(--blog-accent-soft);+ color: var(--blog-link-color);+ border-radius: 4px;+ padding: 2px 8px;+}++.blog-card {+ padding: 40px 0;+ border-bottom: 1px solid var(--blog-rule);+ display: flex;+ gap: 28px;+ align-items: center;+}++.blog-card__content {+ min-width: 0;+ flex: 1;+}++.blog-card__image {+ width: 210px;+ flex-shrink: 0;+}++/* Generated covers are decoration: a design shows them by styling these elements. */+.blog__emblem,+.blog-card__art {+ display: none;+}++.blog-card__image img {+ width: 100%;+ aspect-ratio: 4 / 3;+ object-fit: cover;+ border-radius: 6px;+}++.blog-card h2 {+ font-size: clamp(1.5rem, 4vw, 2rem);+ letter-spacing: -0.025em;+ margin: 14px 0;+}++.blog-card h2 a {+ color: var(--blog-foreground);+}++.blog-card__excerpt {+ color: var(--blog-muted);+ margin: 12px 0 22px;+}++.blog-card__footer {+ display: flex;+ justify-content: space-between;+ gap: 12px;+ font-size: 0.85rem;+}++.blog__footer {+ color: var(--blog-muted);+ border-top: 1px solid var(--blog-rule);+ font-size: 0.8rem;+ margin-top: 64px;+}++.blog__pagination {+ display: flex;+ justify-content: space-between;+ gap: 24px;+ padding-block: 32px;+}++.blog__empty {+ padding-block: 56px;+}++.blog__search {+ display: flex;+ align-items: center;+ gap: 12px;+ padding-block: 28px;+ flex-wrap: wrap;+}++.blog__search input {+ flex: 1;+ min-width: 160px;+}++.blog__search input,+.blog__search button {+ font: inherit;+ padding: 10px 14px;+ border: 1px solid var(--blog-rule);+ border-radius: 4px;+ background: var(--blog-canvas);+ color: var(--blog-foreground);+}++.blog__search button {+ cursor: pointer;+ color: var(--blog-link-color);+}++.blog-article {+ max-width: var(--blog-reading-width);+ margin-inline: auto;+}++.blog-article__header {+ padding: 64px 0 36px;+ border-bottom: 1px solid var(--blog-rule);+ margin-bottom: 36px;+}++.blog-article h1 {+ font-size: clamp(2.25rem, 6vw, 3.7rem);+ letter-spacing: -0.045em;+ margin: 24px 0;+}++.blog-article__standfirst {+ font-size: 1.25rem;+ line-height: 1.55;+ color: var(--blog-muted);+}++.blog-article__body {+ font-family: Georgia, serif;+ font-size: 1.15rem;+ line-height: 1.8;+ overflow-wrap: anywhere;+}++.blog-article__body h2,+.blog-article__body h3,+.blog-article__body h4,+.blog-article__body h5,+.blog-article__body h6 {+ font-family: system-ui, sans-serif;+ letter-spacing: -0.025em;+ margin-block: 1.8em 0.65em;+}++.blog-article__body h4,+.blog-article__body h5,+.blog-article__body h6 {+ line-height: 1.3;+}++.blog-article__body h4 {+ font-size: 1.15em;+}++.blog-article__body h5,+.blog-article__body h6 {+ font-size: 1em;+}++.blog-article__body > :first-child {+ margin-block-start: 0;+}++.blog-article__body > :last-child {+ margin-block-end: 0;+}++.blog-article__body p {+ margin: 1.4em 0;+}++.blog-article__body a {+ text-decoration: underline;+ text-decoration-thickness: 0.08em;+}++.blog-article__body :where(aside.onebox, h2, h3, h4, h5, h6) a,+.blog-article__body a.mention {+ text-decoration: none;+}++.blog-article__body :where(ul, ol) {+ margin-block: 1.4em;+ padding-inline-start: 1.6em;+}++.blog-article__body li + li {+ margin-block-start: 0.4em;+}++.blog-article__body li > :where(ul, ol) {+ margin-block: 0.5em;+}++.blog-article__body li:has(> .chcklst-box:first-child),+.blog-article__body li:has(> p:first-child > .chcklst-box:first-child) {+ list-style: none;+}++.blog-article__body .chcklst-box {+ position: relative;+ top: 0.12em;+ display: inline-block;+ width: 1em;+ height: 1em;+ margin-inline-end: 0.35em;+ border: 1px solid var(--blog-rule);+ border-radius: 3px;+ color: var(--blog-link-color);+ text-align: center;+}++.blog-article__body li > .chcklst-box:first-child,+.blog-article__body li > p:first-child > .chcklst-box:first-child {+ margin-inline-start: -1.35em;+}++.blog-article__body .chcklst-box.checked {+ background: var(--blog-link-color);+ border-color: var(--blog-link-color);+}++.blog-article__body .chcklst-box.checked::after {+ content: "";+ position: absolute;+ inset-block-start: 0.18em;+ inset-inline-start: 0.27em;+ width: 0.38em;+ height: 0.2em;+ border-bottom: 0.12em solid var(--blog-canvas);+ border-left: 0.12em solid var(--blog-canvas);+ transform: rotate(-45deg);+}++.blog-article__body figure {+ margin: 2em 0;+}++.blog-article__body img,+.blog-article__body video,+.blog-article__body iframe {+ max-width: 100%;+}++.blog-article__body img:not(.emoji) {+ height: auto;+ border-radius: 6px;+}++.blog-article__body video {+ height: auto;+}++.blog-article__body :where(.lightbox-wrapper, .image-wrapper),+.blog-article__body :where(.lightbox-wrapper, .image-wrapper) img,+.blog-article__body figure > img:not(.emoji),+.blog-article__body figure > video {+ display: block;+}++.blog-article__body :where(.lightbox-wrapper, .image-wrapper),+.blog-article__body figure > img:not(.emoji),+.blog-article__body figure > video {+ margin-inline: auto;+}++.blog-article__body figcaption {+ margin-block-start: 0.7rem;+ color: var(--blog-muted);+ font-family: system-ui, sans-serif;+ font-size: 0.8em;+ line-height: 1.5;+ text-align: center;+}++.blog-article__body video,+.blog-article__body .video-container,+.blog-article__body .lazy-video-container,+.blog-article__body .youtube-onebox {+ display: block;+ width: 100%;+ margin-block: 1.75em;+ overflow: hidden;+ border-radius: 6px;+}++.blog-article__body+ :where(.video-container, .lazy-video-container, .youtube-onebox)+ iframe {+ display: block;+ width: 100%;+ height: auto;+ aspect-ratio: 16 / 9;+ border: 0;+}++.blog-article__body img.emoji {+ width: 1em;+ height: 1em;+ vertical-align: middle;+}++.blog-article__body .meta {+ display: none;+}++.blog-article__body pre {+ max-width: 100%;+ margin-block: 1.75em;+ overflow: auto;+ padding: 20px;+ background: var(--blog-tint);+ border: 1px solid var(--blog-rule);+ border-radius: 6px;+ font-size: 0.85rem;+ line-height: 1.6;+ tab-size: 2;+}++.blog-article__body code {+ font-family: ui-monospace, monospace;+}++.blog-article__body :not(pre) > code {+ padding: 0.12em 0.35em;+ background: var(--blog-tint);+ border: 1px solid var(--blog-rule);+ border-radius: 4px;+ font-size: 0.9em;+ overflow-wrap: break-word;+}++.blog-article__body pre code {+ padding: 0;+ background: transparent;+ border: 0;+ border-radius: 0;+ color: inherit;+ font-size: inherit;+ overflow-wrap: normal;+}++.blog-article__body pre.onebox code {+ /* The template indents the line list; only individual code lines preserve whitespace. */+ white-space: normal;+}++.blog-article__body pre.onebox ol.lines {+ margin: 0;+ padding-inline-start: 3em;+}++.blog-article__body pre.onebox ol.lines li {+ min-height: 1.6em;+ margin: 0;+ white-space: pre;+}++.blog-article__body .hljs-comment,+.blog-article__body .hljs-doctag,+.blog-article__body .hljs-code,+.blog-article__body .hljs-meta {+ color: var(--blog-muted);+ font-style: italic;+}++.blog-article__body .hljs-keyword,+.blog-article__body .hljs-subst {+ color: var(--hljs-keyword);+}++.blog-article__body .hljs-number {+ color: var(--hljs-number);+}++.blog-article__body .hljs-tag,+.blog-article__body .hljs-tag .hljs-title {+ color: var(--hljs-tag);+ font-weight: normal;+}++.blog-article__body .hljs-string,+.blog-article__body .hljs-tag .hljs-string,+.blog-article__body .hljs-template-tag,+.blog-article__body .hljs-template-variable,+.blog-article__body .hljs-type {+ color: var(--hljs-string);+}++.blog-article__body .hljs-title {+ color: var(--hljs-title);+}++.blog-article__body .hljs-quote,+.blog-article__body .hljs-operator,+.blog-article__body .hljs-selector-pseudo,+.blog-article__body .hljs-selector-tag,+.blog-article__body .hljs-link {+ color: var(--hljs-string);+}++.blog-article__body .hljs-subst {+ font-weight: normal;+}++.blog-article__body .hljs-literal,+.blog-article__body .hljs-class .hljs-title {+ color: var(--hljs-title);+}++.blog-article__body .hljs-name {+ color: var(--hljs-name);+}++.blog-article__body .hljs-punctuation {+ color: var(--hljs-punctuation);+}++.blog-article__body .hljs-attr {+ color: var(--hljs-attr);+}++.blog-article__body .hljs-selector-attr,+.blog-article__body .hljs-selector-class,+.blog-article__body .hljs-selector-id {+ color: var(--hljs-attr);+}++.blog-article__body .hljs-variable {+ color: var(--hljs-variable);+}++.blog-article__body .hljs-attribute {+ color: var(--hljs-attribute);+}++.blog-article__body .hljs-regexp {+ color: var(--success);+}++.blog-article__body .hljs-symbol {+ color: var(--hljs-symbol);+}++.blog-article__body .hljs-built_in {+ color: var(--hljs-name);+}++.blog-article__body .hljs-deletion {+ background: var(--danger-low);+ color: var(--hljs-deletion);+}++.blog-article__body .hljs-addition {+ background: var(--success-low);+ color: var(--hljs-addition);+}++.blog-article__body .hljs-section {+ color: var(--hljs-name);+}++.blog-article__body .hljs-bullet {+ color: var(--hljs-attribute);+}++.blog-article__body .hljs-emphasis {+ color: var(--hljs-comment);+ font-style: italic;+}++.blog-article__body .hljs-strong {+ font-weight: bold;+}++.blog-article__body blockquote {+ margin: 1.75em 0;+ padding: 1em 1.25em;+ background: var(--blog-tint);+ border-inline-start: 3px solid var(--blog-link-color);+ border-radius: 6px;+ color: var(--blog-muted);+}++.blog-article__body blockquote > :first-child {+ margin-block-start: 0;+}++.blog-article__body blockquote > :last-child {+ margin-block-end: 0;+}++.blog-article__body .md-table {+ max-width: 100%;+ margin-block: 1.75em;+ overflow-x: auto;+ border: 1px solid var(--blog-rule);+ border-radius: 6px;+}++.blog-article__body .md-table > table {+ display: table;+ width: 100%;+ min-width: 36rem;+ border-collapse: collapse;+}++.blog-article__body > table {+ display: block;+ max-width: 100%;+ margin-block: 1.75em;+ overflow-x: auto;+ border-collapse: collapse;+}++.blog-article__body th,+.blog-article__body td {+ padding: 0.65em 0.85em;+ border: 0;+ border-inline-end: 1px solid var(--blog-rule);+ border-block-end: 1px solid var(--blog-rule);+ line-height: 1.5;+ text-align: start;+ vertical-align: top;+}++.blog-article__body th {+ background: var(--blog-tint);+ font-family: system-ui, sans-serif;+ font-size: 0.85em;+ white-space: nowrap;+}++.blog-article__body tr:last-child td {+ border-block-end: 0;+}++.blog-article__body :where(th, td):last-child {+ border-inline-end: 0;+}++.blog-article__body aside.onebox {+ margin-block: 1.75em;+ overflow: hidden;+ padding: 0;+ background: var(--blog-tint);+ border: 1px solid var(--blog-rule);+ border-radius: 6px;+ font-family: system-ui, sans-serif;+ font-size: 0.9rem;+ line-height: 1.5;+}++.blog-article__body aside.onebox .source {+ display: flex;+ align-items: center;+ gap: 0.55em;+ min-width: 0;+ padding: 0.7rem 1rem;+ border-block-end: 1px solid var(--blog-rule);+}++.blog-article__body aside.onebox .source a {+ min-width: 0;+ overflow-wrap: anywhere;+}++.blog-article__body aside.onebox .site-icon {+ flex: 0 0 auto;+ width: 1.25rem;+ height: 1.25rem;+ border-radius: 3px;+}++.blog-article__body aside.onebox .onebox-body {+ display: flow-root;+ min-width: 0;+ padding: 1rem;+ overflow-wrap: anywhere;+}++.blog-article__body+ aside.onebox+ :where(.aspect-image, .aspect-image-full-size) {+ overflow: hidden;+ border-radius: 4px;+}++.blog-article__body aside.onebox :where(.thumbnail, .aspect-image) {+ float: inline-start;+ width: auto;+ max-width: min(25%, 7.5rem);+ margin-block: 0 0.5rem;+ margin-inline: 0 1rem;+}++.blog-article__body aside.onebox .thumbnail {+ display: block;+ max-height: 10rem;+ height: auto;+ object-fit: contain;+}++.blog-article__body aside.onebox .onebox-avatar {+ width: 3rem;+ max-width: 100%;+ height: 3rem;+}++.blog-article__body aside.onebox .aspect-image-full-size {+ clear: both;+ max-width: 100%;+ margin-block: 1rem 0;+}++.blog-article__body+ aside.onebox+ :where(.aspect-image, .aspect-image-full-size)+ img {+ float: none;+ width: 100%;+ max-width: 100%;+ max-height: none;+ margin: 0;+}++.blog-article__body aside.onebox :where(h3, h4) {+ margin: 0 0 0.5rem;+ font-size: 1.05rem;+ line-height: 1.4;+}++.blog-article__body aside.onebox :where(.tags, .date) {+ color: var(--blog-muted);+ font-size: 0.85em;+}++.blog-article__body aside.onebox .tags {+ margin-block-end: 0.35rem;+}++.blog-article__body aside.onebox .tags strong {+ font-weight: 500;+}++.blog-article__body aside.onebox p {+ margin-block: 0.75rem 0;+}++.blog-article__body aside.onebox .topic-category {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.5rem;+}++.blog-article__body+ aside.onebox+ :where(.topic-header-extra, .list-tags, .discourse-tags) {+ display: contents;+}++.blog-article__body aside.onebox .badge-wrapper {+ display: inline-flex;+ align-items: center;+ gap: 0.35em;+ padding: 0.2em 0.55em;+ background: var(--blog-canvas);+ border: 1px solid var(--blog-rule);+ border-radius: 1em;+ font-size: 0.82em;+ line-height: 1.4;+}++.blog-article__body aside.onebox .badge-category-bg {+ flex: 0 0 auto;+ width: 0.55em;+ height: 0.55em;+ border-radius: 50%;+}++.blog-article__body aside.onebox .discourse-tags svg {+ display: none;+}++.blog-article__body aside.onebox .discourse-tag {+ padding: 0.2em 0.55em;+ background: var(--blog-accent-soft);+ border-radius: 1em;+ color: var(--blog-link-color);+ font-size: 0.82em;+ line-height: 1.4;+}++.blog-article__body aside.onebox p:has(> .label1) {+ display: flex;+ flex-wrap: wrap;+ gap: 0.35em 0.75em;+ color: var(--blog-muted);+ font-size: 0.85em;+}++.blog-article__body details {+ margin-block: 1.75em;+ background: var(--blog-tint);+ border: 1px solid var(--blog-rule);+ border-radius: 6px;+}++.blog-article__body summary {+ padding: 0.8em 1em;+ font-family: system-ui, sans-serif;+ font-weight: 650;+ cursor: pointer;+}++.blog-article__body details[open] summary {+ border-block-end: 1px solid var(--blog-rule);+}++.blog-article__body details > :not(summary) {+ margin-inline: 1em;+}++.blog-article__body hr {+ height: 0;+ margin-block: 3em;+ overflow: visible;+ border: 0;+ border-block-start: 1px solid var(--blog-rule);+}++.blog-article__body .spoiler {+ filter: blur(0.3em);+}++.blog-article__body .spoiler:hover,+.blog-article__body .spoiler:focus-within {+ filter: none;+}++.blog.has-blog-lightbox {+ overflow: hidden;+}++.blog-lightbox-trigger {+ cursor: zoom-in;+}++.blog-lightbox {+ --blog-lightbox-surface: color-mix(+ in srgb,+ var(--blog-paper-color) 12%,+ transparent+ );+ --blog-lightbox-text: var(--blog-paper-color);+ --blog-lightbox-border: color-mix(+ in srgb,+ var(--blog-paper-color) 20%,+ transparent+ );+ --blog-lightbox-hover: color-mix(+ in srgb,+ var(--blog-paper-color) 20%,+ transparent+ );+ --blog-lightbox-backdrop: rgba(var(--always-black-rgb), 0.82);+ --blog-lightbox-focus: var(--blog-link-color);+ --blog-lightbox-radius: 12px;+ --blog-lightbox-target: 44px;+ --blog-lightbox-gutter: clamp(12px, 2vw, 24px);+ --blog-lightbox-gap: 12px;+ position: fixed;+ inset: 0;+ inline-size: 100%;+ max-inline-size: none;+ block-size: 100vh;+ block-size: 100dvh;+ max-block-size: none;+ margin: 0;+ padding-block-start: calc(+ var(--blog-lightbox-gutter) + env(safe-area-inset-top, 0px)+ );+ padding-inline-end: calc(+ var(--blog-lightbox-gutter) + env(safe-area-inset-right, 0px)+ );+ padding-block-end: calc(+ var(--blog-lightbox-gutter) + env(safe-area-inset-bottom, 0px)+ );+ padding-inline-start: calc(+ var(--blog-lightbox-gutter) + env(safe-area-inset-left, 0px)+ );+ overflow: auto;+ overscroll-behavior: contain;+ background: transparent;+ border: 0;+ color: var(--blog-lightbox-text);+}++.blog-lightbox[open] {+ display: grid;+ grid-template-rows: auto minmax(0, 1fr);+ gap: var(--blog-lightbox-gap);+}++.blog-lightbox::backdrop {+ background: var(--blog-lightbox-backdrop);+}++.blog-lightbox__controls {+ display: flex;+ align-items: stretch;+ justify-self: end;+ min-inline-size: 0;+ max-inline-size: 100%;+ padding: 4px;+ background: var(--blog-lightbox-surface);+ -webkit-backdrop-filter: blur(12px);+ backdrop-filter: blur(12px);+ border: 1px solid var(--blog-lightbox-border);+ border-radius: var(--blog-lightbox-radius);+}++.blog-lightbox__original,+.blog-lightbox__close {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-inline-size: max(44px, var(--blog-lightbox-target));+ min-block-size: max(44px, var(--blog-lightbox-target));+ margin: 0;+ background: transparent;+ border: 0;+ border-radius: max(0px, calc(var(--blog-lightbox-radius) - 4px));+ color: var(--blog-lightbox-text);+ font: inherit;+ font-size: 0.875rem;+ line-height: 1.35;+ cursor: pointer;+}++.blog .blog-lightbox__original {+ flex: 0 1 auto;+ padding: 8px 12px;+ color: var(--blog-lightbox-text);+ font-weight: 600;+ text-align: center;+ text-decoration: none;+ overflow-wrap: anywhere;+}++.blog-lightbox__close {+ flex: 0 0 auto;+ padding: 0;+ margin-inline-start: 4px;+ border-inline-start: 1px solid var(--blog-lightbox-border);+ border-start-start-radius: 0;+ border-end-start-radius: 0;+ appearance: none;+}++.blog-lightbox__close-icon {+ position: relative;+ inline-size: 18px;+ block-size: 18px;+ pointer-events: none;+}++.blog-lightbox__close-icon::before,+.blog-lightbox__close-icon::after {+ content: "";+ position: absolute;+ inset-block-start: calc(50% - 1px);+ inset-inline-start: 0;+ inline-size: 100%;+ border-block-start: 2px solid currentcolor;+ transform: rotate(45deg);+}++.blog-lightbox__close-icon::after {+ transform: rotate(-45deg);+}++.blog .blog-lightbox__original:focus-visible,+.blog .blog-lightbox__close:focus-visible {+ outline: 2px solid var(--blog-lightbox-focus);+ outline-offset: -3px;+}++.blog-lightbox__original:active,+.blog-lightbox__close:active {+ background: var(--blog-lightbox-hover);+}++@media (hover: hover) and (pointer: fine) {+ .blog .blog-lightbox__original:hover,+ .blog .blog-lightbox__close:hover {+ background: var(--blog-lightbox-hover);+ }++ .blog .blog-lightbox__original:hover {+ text-decoration: underline;+ }+}++.blog-lightbox__figure {+ display: grid;+ grid-template-rows: minmax(0, 1fr) auto;+ justify-items: center;+ min-inline-size: 0;+ min-block-size: 0;+ margin: 0;+}++.blog-lightbox__image {+ display: block;+ align-self: center;+ min-inline-size: 0;+ min-block-size: 0;+ inline-size: auto;+ max-inline-size: 100%;+ block-size: auto;+ max-block-size: 100%;+ object-fit: contain;+ border-radius: 6px;+}++.blog-lightbox__caption {+ max-inline-size: min(80ch, 100%);+ max-block-size: 25vh;+ max-block-size: 25dvh;+ margin-block-start: 12px;+ padding: 6px 10px;+ overflow: auto;+ overflow-wrap: anywhere;+ background: var(--blog-lightbox-surface);+ border-radius: 4px;+ color: var(--blog-lightbox-text);+ font:+ 0.9rem / 1.5 system-ui,+ sans-serif;+ text-align: center;+}++.blog-article__footer {+ display: flex;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 20px;+ padding-block: 32px;+ font-size: 0.85rem;+}++.blog__tags {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+}++.blog__tags a {+ background: var(--blog-tint);+ padding: 3px 10px;+ border-radius: 4px;+}++.blog__updated {+ font-size: 0.8rem;+ color: var(--blog-muted);+}++.blog-discussion {+ max-width: var(--blog-reading-width);+ margin-inline: auto;+ border-top: 1px solid var(--blog-rule);+ padding-top: 36px;+ margin-top: 24px;+}++.blog-discussion__heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ flex-wrap: wrap;+}++.blog-discussion__heading h2 {+ margin: 0;+ font-size: 1.6rem;+ letter-spacing: -0.035em;+}++.blog-discussion p {+ color: var(--blog-muted);+ font-size: 0.9rem;+}++.blog-discussion.is-failed #discourse-comments {+ display: none;+}++.blog-discussion.is-loading iframe {+ visibility: hidden;+}++.blog-discussion iframe {+ background: var(--blog-canvas);+ width: 100%;+ border: 0;+ border-radius: 6px;+}++.blog__preview {+ background: var(--highlight-low);+ border-bottom: 1px solid var(--blog-rule);+ padding: 16px 24px;+ text-align: center;+}++.blog__preview a {+ margin-inline-start: 16px;+}++@media (width <= 600px) {+ .blog__header,+ .blog__footer {+ padding: 20px;+ }++ .blog__main {+ padding-inline: 20px;+ }++ .blog__intro {+ padding-block: 40px 28px;+ }++ .blog__nav {+ gap: 16px;+ }++ .blog-card {+ flex-direction: column;+ align-items: stretch;+ padding-block: 28px;+ }++ .blog-card__image {+ width: 100%;+ }++ .blog-article__header {+ padding-top: 40px;+ }++ .blog-article__body {+ font-size: 1.05rem;+ }+}++@media (prefers-reduced-motion: reduce) {+ html {+ scroll-behavior: auto;+ }+}diff --git a/plugins/blog/public/blog.js b/plugins/blog/public/blog.jsnew file mode 100644index 00000000000..6c9c7e1c5e9--- /dev/null+++ b/plugins/blog/public/blog.js@@ -0,0 +1,352 @@+const comments = document.getElementById("discourse-comments");++if (comments) {+ const loadDiscussion = () => {+ const discussion = comments.closest(".blog-discussion");+ discussion.classList.add("is-loading");+ const failure = discussion.querySelector(".blog-discussion__load-error");+ const failDiscussion = () => {+ discussion.classList.remove("is-loading");+ discussion.classList.add("is-failed");+ failure.hidden = false;+ window.removeEventListener("message", handleDiscussionMessage);+ clearTimeout(timeout);+ };+ const discussOrigin = new URL(comments.dataset.discourseUrl).origin;+ // The embed cannot read the reader palette, so send it the colours it needs.+ const sendPalette = () => {+ const styles = getComputedStyle(document.documentElement);+ const frame = document.getElementById("discourse-embed-frame");+ frame?.contentWindow?.postMessage(+ {+ type: "discourse-blog-palette",+ accent: styles.getPropertyValue("--blog-accent-color").trim(),+ paper: styles.getPropertyValue("--blog-paper-color").trim(),+ ink: styles.getPropertyValue("--blog-ink-color").trim(),+ },+ discussOrigin+ );+ };+ const timeout = setTimeout(failDiscussion, 30000);+ const handleDiscussionMessage = (event) => {+ const frame = document.getElementById("discourse-embed-frame");+ if (+ event.origin !== discussOrigin ||+ event.source !== frame?.contentWindow+ ) {+ return;+ }+ if (event.data?.type === "discourse-blog-resize") {+ const height = event.data.height;+ if (+ typeof height === "number" &&+ Number.isFinite(height) &&+ height > 0+ ) {+ // Leave a pixel for fractional layout rounding at non-default zoom levels.+ frame.style.height = `${Math.max(280, Math.ceil(height) + 1)}px`;+ frame.scrolling = "auto";+ }+ } else if (event.data?.type === "discourse-blog-ready") {+ clearTimeout(timeout);+ discussion.classList.remove("is-loading");+ sendPalette();+ }+ };+ window.addEventListener("message", handleDiscussionMessage);++ window.DiscourseEmbed = {+ discourseUrl: comments.dataset.discourseUrl,+ topicId: Number(comments.dataset.topicId),+ fullApp: true,+ className: "discourse-blog-discussion",+ embedHeight: "320px",+ dynamicHeight: false,+ embedMinHeight: 280,+ lazyLoad: false,+ discourseReferrerPolicy: "strict-origin-when-cross-origin",+ };+ const script = document.createElement("script");+ script.src = `${comments.dataset.discourseUrl}javascripts/embed.js`;+ script.onerror = failDiscussion;+ script.onload = () => {+ const frame = document.getElementById("discourse-embed-frame");+ if (frame) {+ frame.title = comments.dataset.title;+ frame.scrolling = "auto";+ }+ };+ document.head.appendChild(script);+ };++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries.some((entry) => entry.isIntersecting)) {+ observer.disconnect();+ loadDiscussion();+ }+ },+ { rootMargin: "300px" }+ );+ observer.observe(comments);+}++const article = document.querySelector?.(".blog-article__body");++if (article && document.body.dataset.blogHighlightCoreUrl) {+ const blocks = [...article.querySelectorAll("pre code")]+ .map((code) => {+ const language = [...code.classList]+ .map((name) => name.match(/^lang(?:uage)?-(.+)$/i)?.[1])+ .find(Boolean)+ ?.toLowerCase();+ return { code, language };+ })+ .filter(({ code, language }) => {+ return (+ !code.dataset.highlighted &&+ !code.closest(".nohighlight, .no-highlight") &&+ !/^(text|plaintext|plain|none|nohighlight|no-highlight)$/.test(+ language+ ) &&+ (language || document.body.dataset.blogHighlightAuto === "true") &&+ code.textContent.length <= 30000+ );+ });++ if (blocks.length) {+ const highlight = async () => {+ try {+ const [{ default: hljs }, { default: registerLanguages }] =+ await Promise.all([+ import(document.body.dataset.blogHighlightCoreUrl),+ import(document.body.dataset.blogHighlightLanguagesUrl),+ ]);+ registerLanguages(hljs);++ for (const { code, language } of blocks) {+ const lines = [...code.querySelectorAll("ol.lines > li")];+ if (!lines.length && code.children.length) {+ continue;+ }++ const text = lines.length+ ? lines.map((line) => line.textContent).join("\n")+ : code.textContent;+ const detected =+ !language || language === "auto"+ ? hljs.highlightAuto(text.trimStart().slice(0, 2000)).language+ : language;+ if (!detected || !hljs.getLanguage(detected)) {+ continue;+ }++ const highlighted = document.createElement("code");+ highlighted.className = `language-${detected}`;+ highlighted.textContent = text;+ hljs.highlightElement(highlighted);++ if (lines.length) {+ // Highlight the whole snippet so multiline tokens retain their context.+ const fragments = lines.map(() =>+ document.createDocumentFragment()+ );+ const walker = document.createTreeWalker(+ highlighted,+ NodeFilter.SHOW_TEXT+ );+ let lineIndex = 0;+ while (walker.nextNode()) {+ const node = walker.currentNode;+ for (const [index, part] of node.textContent+ .split("\n")+ .entries()) {+ if (index) {+ lineIndex++;+ }+ let token = document.createTextNode(part);+ for (+ let parent = node.parentNode;+ parent !== highlighted;+ parent = parent.parentNode+ ) {+ const wrapper = parent.cloneNode(false);+ wrapper.append(token);+ token = wrapper;+ }+ fragments[lineIndex].append(token);+ }+ }+ lines.forEach((line, index) =>+ line.replaceChildren(fragments[index])+ );+ } else {+ code.replaceChildren(...highlighted.childNodes);+ }+ code.classList.add("hljs");+ code.dataset.highlighted = "yes";+ }+ } catch (error) {+ // eslint-disable-next-line no-console+ console.warn("Could not load blog syntax highlighting", error);+ }+ };++ if (window.requestIdleCallback) {+ window.requestIdleCallback(highlight, { timeout: 2000 });+ } else {+ setTimeout(highlight, 0);+ }+ }+}++if (article) {+ const probe = document.createElement("dialog");++ if (typeof probe.showModal === "function") {+ const images = article.querySelectorAll("img");+ const openLabel = document.body.dataset.blogLightboxOpenLabel;+ const openWithDescriptionLabel =+ document.body.dataset.blogLightboxOpenWithDescriptionLabel;+ const closeLabel = document.body.dataset.blogLightboxCloseLabel;+ const dialogLabel = document.body.dataset.blogLightboxDialogLabel;+ const originalLabel = document.body.dataset.blogLightboxOriginalLabel;+ let dialog;+ let dialogCaption;+ let dialogImage;+ let dialogOriginal;+ let lastTrigger;++ const ensureDialog = () => {+ if (dialog) {+ return;+ }++ dialog = probe;+ dialog.className = "blog-lightbox";+ dialog.setAttribute("aria-label", dialogLabel);++ dialogOriginal = document.createElement("a");+ dialogOriginal.className = "blog-lightbox__original";+ dialogOriginal.target = "_blank";+ dialogOriginal.rel = "noopener";+ dialogOriginal.textContent = originalLabel;++ const close = document.createElement("button");+ close.type = "button";+ close.autofocus = true;+ close.className = "blog-lightbox__close";+ close.setAttribute("aria-label", closeLabel);+ const closeIcon = document.createElement("span");+ closeIcon.className = "blog-lightbox__close-icon";+ closeIcon.setAttribute("aria-hidden", "true");+ close.append(closeIcon);+ close.addEventListener("click", () => dialog.close());++ const controls = document.createElement("div");+ controls.className = "blog-lightbox__controls";+ controls.append(dialogOriginal, close);++ const figure = document.createElement("figure");+ figure.className = "blog-lightbox__figure";+ dialogImage = document.createElement("img");+ dialogImage.className = "blog-lightbox__image";+ dialogCaption = document.createElement("figcaption");+ dialogCaption.className = "blog-lightbox__caption";+ figure.append(dialogImage, dialogCaption);+ dialog.append(controls, figure);+ document.body.append(dialog);++ dialog.addEventListener("click", (event) => {+ if (event.target === dialog) {+ dialog.close();+ }+ });+ dialog.addEventListener("close", () => {+ document.body.classList.remove("has-blog-lightbox");+ dialogImage.removeAttribute("src");+ dialogOriginal.removeAttribute("href");+ lastTrigger?.focus();+ });+ };++ const openLightbox = (trigger, image, source) => {+ if (!source) {+ return;+ }++ ensureDialog();+ lastTrigger = trigger;+ dialogImage.src = source;+ dialogImage.alt = image.alt;+ dialogOriginal.href = source;+ const caption = trigger.title || image.title;+ dialogCaption.textContent = caption;+ dialogCaption.hidden = !caption;+ document.body.classList.add("has-blog-lightbox");+ dialog.showModal();+ };++ for (const image of images) {+ if (+ image.matches(".emoji, .avatar, .site-icon") ||+ image.closest("aside.onebox, a.video-thumbnail")+ ) {+ continue;+ }++ const imageLink = image.closest("a");+ if (imageLink && !imageLink.classList.contains("lightbox")) {+ continue;+ }++ const trigger = imageLink || image;+ const source = () => imageLink?.href || image.currentSrc || image.src;+ if (!source()) {+ continue;+ }++ trigger.classList.add("blog-lightbox-trigger");+ trigger.setAttribute("aria-haspopup", "dialog");++ if (!imageLink) {+ trigger.tabIndex = 0;+ trigger.setAttribute("role", "button");+ trigger.setAttribute(+ "aria-label",+ image.alt+ ? openWithDescriptionLabel.replace(+ "__IMAGE_DESCRIPTION__",+ image.alt+ )+ : openLabel+ );+ }++ trigger.addEventListener("click", (event) => {+ if (+ event.defaultPrevented ||+ event.button !== 0 ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey ||+ event.shiftKey+ ) {+ return;+ }++ event.preventDefault();+ openLightbox(trigger, image, source());+ });++ if (!imageLink) {+ trigger.addEventListener("keydown", (event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ openLightbox(trigger, image, source());+ }+ });+ }+ }+ }+}diff --git a/plugins/blog/spec/jobs/clean_up_blog_review_uploads_spec.rb b/plugins/blog/spec/jobs/clean_up_blog_review_uploads_spec.rbnew file mode 100644index 00000000000..d011d61509f--- /dev/null+++ b/plugins/blog/spec/jobs/clean_up_blog_review_uploads_spec.rb@@ -0,0 +1,47 @@+# frozen_string_literal: true++RSpec.describe Jobs::CleanUpBlogReviewUploads do+ fab!(:admin)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) { Fabricate(:post, topic: topic, user: admin) }++ before { enable_blog!(category: category, drafts: drafts) }++ describe "#execute" do+ it "retains expired review uploads while disabled and releases them when enabled" do+ upload = Fabricate(:upload, user: admin, created_at: 3.days.ago)+ first_post.update!(+ raw: "",+ cooked: "<p><img src=\"#{upload.url}\"></p>",+ )+ first_post.link_post_uploads+ expired = Blog::Review.issue!(topic: topic, user: admin)+ active = Blog::Review.issue!(topic: topic, user: admin)+ expired.update!(expires_at: 1.second.ago)+ SiteSetting.blog_enabled = false++ described_class.new.execute(nil)++ expect(UploadReference.where(target: expired).pluck(:upload_id)).to eq([upload.id])++ SiteSetting.blog_enabled = true+ described_class.new.execute(nil)++ expect(UploadReference.where(target: expired)).not_to exist+ expect(UploadReference.where(target: active).pluck(:upload_id)).to eq([upload.id])+ expect(UploadReference.where(target: first_post).pluck(:upload_id)).to eq([upload.id])++ active.update!(expires_at: 1.second.ago)+ first_post.update!(raw: "Image removed", cooked: "<p>Image removed</p>")+ first_post.link_post_uploads+ described_class.new.execute(nil)+ Jobs::CleanUpUploads.new.reset_last_cleanup!+ Jobs::CleanUpUploads.new.execute(nil)++ expect(Upload.where(id: upload.id)).not_to exist+ expect(Blog::Review.where(id: [expired.id, active.id]).count).to eq(2)+ end+ end+enddiff --git a/plugins/blog/spec/jobs/publish_blog_revision_spec.rb b/plugins/blog/spec/jobs/publish_blog_revision_spec.rbnew file mode 100644index 00000000000..32760a66907--- /dev/null+++ b/plugins/blog/spec/jobs/publish_blog_revision_spec.rb@@ -0,0 +1,51 @@+# frozen_string_literal: true++RSpec.describe Jobs::PublishBlogRevision do+ fab!(:admin)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) do+ Fabricate(+ :post,+ topic: topic,+ user: admin,+ raw: "An article ready for a careful editorial review.",+ )+ end++ before { enable_blog!(category: category, drafts: drafts) }++ describe "#execute" do+ it "keeps a due schedule while the plugin is disabled and publishes it once re-enabled" do+ freeze_time+ publication = Blog::Publication.for_topic(topic)+ revision = publication.submit!(admin)+ publication.approve!(admin, revision.id)+ publication.schedule!(admin, revision_id: revision.id, at: 1.hour.from_now.iso8601)+ token = publication.schedule_token+ freeze_time 2.hours.from_now+ SiteSetting.blog_enabled = false++ described_class.new.execute(publication_id: publication.id, token: token)++ publication.reload+ expect(publication).not_to be_published+ expect(publication.schedule_token).to eq(token)+ expect(publication.schedule_error).to be_blank++ SiteSetting.blog_enabled = true+ Jobs::RecoverBlogSchedules.new.execute+ expect_job_enqueued(+ job: :publish_blog_revision,+ args: {+ publication_id: publication.id,+ token: token,+ },+ )+ described_class.new.execute(publication_id: publication.id, token: token)++ expect(publication.reload.published_revision_id).to eq(revision.id)+ end+ end+enddiff --git a/plugins/blog/spec/lib/template_renderer_spec.rb b/plugins/blog/spec/lib/template_renderer_spec.rbnew file mode 100644index 00000000000..7fc0b7ce4ca--- /dev/null+++ b/plugins/blog/spec/lib/template_renderer_spec.rb@@ -0,0 +1,77 @@+# frozen_string_literal: true++RSpec.describe Blog::TemplateRenderer do+ describe ".render" do+ it "escapes dynamic text while allowing only server-produced HTML fragments" do+ output =+ described_class.render(+ "article",+ {+ "title" => '<img src=x onerror="alert(1)">',+ "body" => described_class::Html.new("<p>Safe cooked content</p>"),+ },+ theme: {+ "template_article" => "<h1>{{ title }}</h1><div>{{ body }}</div>",+ },+ )+ document = Nokogiri::HTML5.fragment(output)+ expect(document.at_css("h1").text).to eq('<img src=x onerror="alert(1)">')+ expect(document.css("img")).to be_empty+ expect(document.at_css("div p").text).to eq("Safe cooked content")+ end++ it "does not expose request, session, model methods, or global Liquid registrations" do+ output =+ described_class.render(+ "article",+ { "article" => { "title" => "Public title" } },+ theme: {+ "template_article" =>+ "{{ article.title }}|{{ article.class }}|{{ request }}|{{ session }}|{{ site_settings }}",+ },+ )+ expect(output).to eq("Public title||||")+ expect(described_class::ENVIRONMENT).not_to equal(Liquid::Environment.default)+ end++ it "falls back to the built-in page after resource exhaustion or an unknown filter" do+ assigns = { "site" => {}, "labels" => { "about" => "About fallback" } }+ [+ "{% for item in (1..1000000000) %}x{% endfor %}",+ "{% for a in (1..1000) %}{% for b in (1..1000) %}x{% endfor %}{% endfor %}",+ '{{ "hello" | unsupported_filter }}',+ ].each do |source|+ output = described_class.render("about", assigns, theme: { "template_about" => source })+ expect(output).to include("About fallback")+ end+ end++ it "ignores custom templates when custom rendering is disabled" do+ output =+ described_class.render(+ "not_found",+ { "labels" => { "not_found_title" => "Not found" }, "site" => {} },+ theme: {+ "template_not_found" => "custom markup",+ },+ custom: false,+ )+ expect(output).to include("Not found")+ expect(output).not_to include("custom markup")+ end+ end++ describe ".validate!" do+ it "rejects includes, render tags, invalid syntax, excessive nesting, and oversized sources" do+ [+ '{% include "/etc/passwd" %}',+ '{% render "secret" %}',+ "{% if %}",+ "{% if true %}" * 110 + "{% endif %}" * 110,+ "x" * 65_537,+ ].each do |source|+ expect { described_class.validate!(source) }.to raise_error(Discourse::InvalidParameters)+ end+ end+ end+enddiff --git a/plugins/blog/spec/lib/theme_archive_spec.rb b/plugins/blog/spec/lib/theme_archive_spec.rbnew file mode 100644index 00000000000..2d940b91f2d--- /dev/null+++ b/plugins/blog/spec/lib/theme_archive_spec.rb@@ -0,0 +1,126 @@+# frozen_string_literal: true++RSpec.describe Blog::ThemeImporter do+ fab!(:admin)++ let(:attributes) do+ Blog::BlogTheme.defaults.merge(+ "name" => "Café design",+ "css" => ".blog { color: red; }",+ "javascript" => "window.blogTheme = true;",+ "template_index" => "<h1>{{ site.title }}</h1>",+ )+ end++ def upload_archive(content, filename: "theme.zip")+ Tempfile.create(%w[blog-theme .zip]) do |file|+ file.binmode+ file.write(content)+ file.flush+ yield(ActionDispatch::Http::UploadedFile.new(tempfile: file, filename: filename))+ end+ end++ def archive_with(files)+ Zip::OutputStream+ .write_buffer do |archive|+ files.each do |name, content|+ archive.put_next_entry(name)+ archive.write(content)+ end+ end+ .string+ end++ describe ".import_file" do+ it "round-trips all theme fields into an independent draft without activating it" do+ source = { "repository" => "https://github.com/example/theme", "commit" => "abc" }+ theme = Blog::BlogTheme.save(attributes, user: admin, source: source)+ active = Blog::BlogTheme.activate(theme["id"], revision: 1, user: admin)+ exported = Blog::ThemeExporter.export(theme)++ Zip::File.open_buffer(exported) do |archive|+ expect(archive.entries.map(&:name)).to contain_exactly(+ "blog-theme.json",+ "blog.css",+ "blog.js",+ *Blog::TemplateRenderer::PAGES.map { |page| "templates/#{page}.liquid" },+ )+ expect(JSON.parse(archive.read("blog-theme.json"))).to eq(+ attributes.slice("name", "accent_color", "paper_color", "ink_color").merge(+ "version" => 2,+ ),+ )+ end++ upload_archive(exported) do |file|+ imported = described_class.import_file(file: file, user: admin)+ expect(imported.slice(*Blog::BlogTheme::FIELDS)).to eq(attributes)+ expect(imported["id"]).not_to eq(theme["id"])+ expect(imported["revision"]).to eq(1)+ expect(imported["source"]).to be_nil+ expect(Blog::BlogTheme.active).to eq(active)+ end+ end++ it "accepts a single enclosing directory and legacy manifests" do+ files = {+ "design/blog-theme.json" => attributes.merge("version" => 1).to_json,+ "design/blog.css" => attributes["css"],+ }+ upload_archive(archive_with(files)) do |file|+ imported = described_class.import_file(file: file, user: admin)+ expect(imported["name"]).to eq(attributes["name"])+ expect(imported["css"]).to eq(attributes["css"])+ expect(imported["javascript"]).to eq("")+ expect(imported["template_index"]).to eq("")+ end+ end++ it "rejects invalid archives, unsupported manifests, oversized files, and invalid templates" do+ manifest = attributes.merge("version" => 2).to_json+ [+ "not a zip",+ archive_with("about.json" => "{}"),+ archive_with("blog-theme.json" => "not json"),+ archive_with("blog-theme.json" => attributes.merge("version" => 99).to_json),+ archive_with("blog-theme.json" => " " * 4097),+ archive_with("blog-theme.json" => manifest, "blog.css" => "a" * 65_537),+ archive_with("blog-theme.json" => manifest, "blog.js" => "\xFF".b),+ archive_with(+ "blog-theme.json" => manifest,+ "templates/index.liquid" => '{% include "/etc/passwd" %}',+ ),+ archive_with(+ "blog-theme.json" => manifest,+ "templates/index.liquid" => "a" * (Blog::TemplateRenderer::MAX_TEMPLATE_BYTES + 1),+ ),+ archive_with(1001.times.to_h { |index| ["#{index}.txt", ""] }),+ ].each do |content|+ upload_archive(content) do |file|+ expect { described_class.import_file(file: file, user: admin) }.to raise_error(+ Discourse::InvalidParameters,+ )+ end+ end+ expect(Blog::BlogTheme.all).to be_empty+ end++ it "validates the upload type, extension, and compressed size" do+ expect { described_class.import_file(file: "theme.zip", user: admin) }.to raise_error(+ Discourse::InvalidParameters,+ )+ upload_archive("zip", filename: "theme.json") do |file|+ expect { described_class.import_file(file: file, user: admin) }.to raise_error(+ Discourse::InvalidParameters,+ )+ end+ upload_archive("a" * (2.megabytes + 1)) do |file|+ expect { described_class.import_file(file: file, user: admin) }.to raise_error(+ Discourse::InvalidParameters,+ )+ end+ expect(Blog::BlogTheme.all).to be_empty+ end+ end+enddiff --git a/plugins/blog/spec/lib/theme_importer_spec.rb b/plugins/blog/spec/lib/theme_importer_spec.rbnew file mode 100644index 00000000000..7e6553d9f98--- /dev/null+++ b/plugins/blog/spec/lib/theme_importer_spec.rb@@ -0,0 +1,160 @@+# frozen_string_literal: true++RSpec.describe Blog::ThemeImporter do+ fab!(:admin)++ let(:manifest) do+ {+ version: 1,+ name: "Git design",+ accent_color: "112233",+ paper_color: "fafafa",+ ink_color: "222222",+ }+ end+ let(:repository) { "https://github.com/example/blog-theme" }++ around do |example|+ Dir.mktmpdir do |directory|+ @directory = directory+ example.run+ end+ end++ before do+ File.write(File.join(@directory, "blog-theme.json"), manifest.to_json)+ File.write(File.join(@directory, "blog.css"), ".blog { color: red; }")+ File.write(File.join(@directory, "blog.js"), "window.gitTheme = true;")+ @importer = ThemeStore::DirectoryImporter.new(@directory)+ @importer.stubs(:version).returns("a" * 40)+ described_class::GitSource.stubs(:new).returns(@importer)+ end++ describe ".import" do+ it "imports a versioned draft and refreshes it without changing the active snapshot" do+ theme = described_class.import(repository: repository, branch: "design", user: admin)+ expect(theme["css"]).to eq(".blog { color: red; }")+ expect(theme["javascript"]).to eq("window.gitTheme = true;")+ expect(theme["source"]).to eq(+ "repository" => repository,+ "branch" => "design",+ "commit" => "a" * 40,+ )+ expect(File.exist?(@importer.temp_folder)).to eq(false)+ Blog::BlogTheme.activate(theme["id"], revision: 1, user: admin)+ File.write(File.join(@directory, "blog.css"), ".blog { color: blue; }")+ updated =+ described_class.import(+ repository: repository,+ branch: "design",+ user: admin,+ id: theme["id"],+ revision: 1,+ )+ expect(updated["revision"]).to eq(2)+ expect(updated["css"]).to eq(".blog { color: blue; }")+ expect(Blog::BlogTheme.active["css"]).to eq(theme["css"])+ expect(File.exist?(@importer.temp_folder)).to eq(false)+ end++ it "cleans up and keeps the saved draft when a pull has an invalid or oversized file" do+ theme = described_class.import(repository: repository, branch: nil, user: admin)+ File.write(File.join(@directory, "blog.js"), "a" * 65_537)+ expect do+ described_class.import(+ repository: repository,+ branch: nil,+ user: admin,+ id: theme["id"],+ revision: 1,+ )+ end.to raise_error(Discourse::InvalidParameters)+ expect(Blog::BlogTheme.find(theme["id"])["revision"]).to eq(1)+ expect(File.exist?(@importer.temp_folder)).to eq(false)+ File.write(File.join(@directory, "blog-theme.json"), "not json")+ expect do+ described_class.import(repository: repository, branch: nil, user: admin)+ end.to raise_error(Discourse::InvalidParameters)+ expect(File.exist?(@importer.temp_folder)).to eq(false)+ end++ it "requires the explicit version and prevents out-of-repository symlink reads" do+ File.write(File.join(@directory, "blog-theme.json"), manifest.merge(version: 99).to_json)+ expect do+ described_class.import(repository: repository, branch: nil, user: admin)+ end.to raise_error(Discourse::InvalidParameters)+ File.write(File.join(@directory, "blog-theme.json"), manifest.to_json)+ @importer.stubs(:import!)+ FileUtils.mkdir_p(@importer.temp_folder)+ File.write(File.join(@importer.temp_folder, "blog-theme.json"), manifest.to_json)+ File.symlink("/etc/passwd", File.join(@importer.temp_folder, "blog.js"))+ theme = described_class.import(repository: repository, branch: nil, user: admin)+ expect(theme["javascript"]).to be_empty+ expect(File.exist?(@importer.temp_folder)).to eq(false)+ end++ it "imports bounded version-two templates and rejects invalid Liquid without changing the saved theme" do+ File.write(File.join(@directory, "blog-theme.json"), manifest.merge(version: 2).to_json)+ FileUtils.mkdir_p(File.join(@directory, "templates"))+ File.write(File.join(@directory, "templates/index.liquid"), "<h1>{{ site.title }}</h1>")+ theme = described_class.import(repository: repository, branch: nil, user: admin)+ expect(theme["template_index"]).to eq("<h1>{{ site.title }}</h1>")+ expect(theme["template_article"]).to eq("")+ File.write(File.join(@directory, "templates/index.liquid"), '{% include "/etc/passwd" %}')+ expect do+ described_class.import(+ repository: repository,+ branch: nil,+ user: admin,+ id: theme["id"],+ revision: 1,+ )+ end.to raise_error(Discourse::InvalidParameters)+ expect(Blog::BlogTheme.find(theme["id"])["revision"]).to eq(1)+ expect(File.exist?(@importer.temp_folder)).to eq(false)+ end++ it "rejects unsafe repository protocols, credentials, branch options, and disallowed repositories" do+ %w[+ file:///tmp/repo+ ssh://[email protected]/repo+ http://example.com/repo+ https://[email protected]/repo+ https://example.com/repo?token=secret+ ].each do |url|+ expect do+ described_class.import(repository: url, branch: nil, user: admin)+ end.to raise_error(Discourse::InvalidParameters)+ end+ expect do+ described_class.import(repository: repository, branch: "--upload-pack=evil", user: admin)+ end.to raise_error(Discourse::InvalidParameters)+ GlobalSetting.stubs(:allowed_theme_repos).returns(+ "https://github.com/discourse/another-theme",+ )+ expect do+ described_class.import(repository: repository, branch: nil, user: admin)+ end.to raise_error(Discourse::InvalidAccess)+ expect(Blog::BlogTheme.all).to be_empty+ end+ end+end++RSpec.describe Blog::ThemeImporter::GitSource do+ describe "HTTPS transport" do+ it "rejects an HTTPS discovery endpoint that resolves to plain HTTP" do+ FinalDestination.stubs(:resolve).returns(URI("http://example.com/theme/info/refs"))+ importer = described_class.new("https://example.com/theme")+ expect { importer.import! }.to raise_error(RemoteTheme::ImportError)+ expect(File.exist?(importer.temp_folder)).to eq(false)+ end++ it "rejects destinations without a public IP address" do+ FinalDestination.stubs(:resolve).returns(nil)+ FinalDestination::SSRFDetector.stubs(:lookup_and_filter_ips).returns([])+ importer = described_class.new("https://127.0.0.1/theme")+ expect { importer.import! }.to raise_error(RemoteTheme::ImportError)+ expect(File.exist?(importer.temp_folder)).to eq(false)+ end+ end+enddiff --git a/plugins/blog/spec/migrations/remove_legacy_blog_appearance_settings_spec.rb b/plugins/blog/spec/migrations/remove_legacy_blog_appearance_settings_spec.rbnew file mode 100644index 00000000000..11dd4cb774b--- /dev/null+++ b/plugins/blog/spec/migrations/remove_legacy_blog_appearance_settings_spec.rb@@ -0,0 +1,101 @@+# frozen_string_literal: true++require Rails.root.join(+ "plugins/blog/db/migrate/20260915045302_remove_legacy_blog_appearance_settings.rb",+ )++RSpec.describe RemoveLegacyBlogAppearanceSettings do+ fab!(:admin)++ before do+ @original_verbose = ActiveRecord::Migration.verbose+ ActiveRecord::Migration.verbose = false+ PluginStoreRow.where(plugin_name: "discourse-blog-themes").delete_all+ end++ after { ActiveRecord::Migration.verbose = @original_verbose }++ def set_legacy(name, value)+ DB.exec(<<~SQL, name: name, value: value)+ INSERT INTO site_settings (name, data_type, value, created_at, updated_at)+ VALUES (:name, 1, :value, NOW(), NOW())+ SQL+ end++ def legacy_rows+ DB.query_single(<<~SQL).first.to_i+ SELECT COUNT(*) FROM site_settings+ WHERE name IN (+ 'discourse_blog_accent_color',+ 'discourse_blog_paper_color',+ 'discourse_blog_ink_color',+ 'discourse_blog_custom_css',+ 'discourse_blog_custom_js'+ )+ SQL+ end++ it "keeps a settings-only design as an activated theme, then removes the settings" do+ allow(Migration::Helpers).to receive(:existing_site?).and_return(true)+ set_legacy("discourse_blog_accent_color", "bc4327")+ set_legacy("discourse_blog_custom_css", ".blog { color: red; }")+ set_legacy("discourse_blog_custom_js", "window.blogDemo = true;")++ described_class.new.up++ theme = Blog::BlogTheme.active+ expect(theme["accent_color"]).to eq("bc4327")+ expect(theme["css"]).to eq(".blog { color: red; }")+ expect(theme["javascript"]).to eq("window.blogDemo = true;")+ expect(theme["paper_color"]).to eq("f5f0e6")+ expect(theme["ink_color"]).to eq("19382d")+ expect(Blog::BlogTheme.all.size).to eq(1)+ expect(Blog::BlogTheme.snapshot(theme["snapshot"])).to be_present+ expect(legacy_rows).to eq(0)+ end++ it "adds no theme when the settings still hold the built-in design" do+ allow(Migration::Helpers).to receive(:existing_site?).and_return(true)+ set_legacy("discourse_blog_accent_color", "d64b2a")++ described_class.new.up++ expect(Blog::BlogTheme.all).to be_empty+ expect(legacy_rows).to eq(0)+ end++ it "leaves a site that already has themes untouched" do+ allow(Migration::Helpers).to receive(:existing_site?).and_return(true)+ saved =+ Blog::BlogTheme.save(+ {+ "name" => "Saved design",+ "accent_color" => "16634e",+ "paper_color" => "fcfcfa",+ "ink_color" => "222b28",+ "css" => "",+ "javascript" => "",+ },+ user: admin,+ )+ Blog::BlogTheme.activate(saved["id"], revision: 1, user: admin)+ set_legacy("discourse_blog_custom_css", ".blog { color: red; }")++ described_class.new.up++ expect(Blog::BlogTheme.all.size).to eq(1)+ expect(Blog::BlogTheme.active["accent_color"]).to eq("16634e")+ expect(legacy_rows).to eq(0)+ end++ it "writes nothing on a fresh install" do+ allow(Migration::Helpers).to receive(:existing_site?).and_return(false)+ set_legacy("discourse_blog_accent_color", "bc4327")++ described_class.new.up++ expect(Blog::BlogTheme.all).to be_empty+ expect(PluginStoreRow.where(plugin_name: "discourse-blog-themes").count).to eq(0)+ expect(legacy_rows).to eq(0)+ end+enddiff --git a/plugins/blog/spec/migrations/rename_discourse_blog_to_blog_spec.rb b/plugins/blog/spec/migrations/rename_discourse_blog_to_blog_spec.rbnew file mode 100644index 00000000000..9cb82e413c3--- /dev/null+++ b/plugins/blog/spec/migrations/rename_discourse_blog_to_blog_spec.rb@@ -0,0 +1,109 @@+# frozen_string_literal: true++require Rails.root.join("plugins/blog/db/migrate/20261028093146_rename_discourse_blog_to_blog.rb")+require Rails.root.join(+ "plugins/blog/db/post_migrate/20261028093149_finish_rename_discourse_blog_to_blog.rb",+ )++RSpec.describe RenameDiscourseBlogToBlog do+ fab!(:upload)++ before do+ @original_verbose = ActiveRecord::Migration.verbose+ ActiveRecord::Migration.verbose = false++ # The test schema already uses the new names, so recreate the old one.+ described_class::RENAMED_TABLES.each do |old_name, new_name|+ DB+ .query_single(<<~SQL, new_name.to_s)+ SELECT i.relname+ FROM pg_index x+ JOIN pg_class i ON i.oid = x.indexrelid+ WHERE x.indrelid = ?::regclass+ SQL+ .each do |name|+ DB.exec("ALTER INDEX #{name} RENAME TO #{name.sub(new_name.to_s, old_name.to_s)}")+ end+ DB.exec("ALTER SEQUENCE #{new_name}_id_seq RENAME TO #{old_name}_id_seq")+ DB.exec("ALTER TABLE #{new_name} RENAME TO #{old_name}")+ end+ end++ after do+ ActiveRecord::Migration.verbose = @original_verbose+ Migration::SafeMigrate.disable!+ end++ def relation_names(pattern, kind)+ DB.query_single("SELECT relname FROM pg_class WHERE relname ~ ? AND relkind = ?", pattern, kind)+ end++ def insert_setting(name, value, data_type: SiteSettings::TypeSupervisor.types[:string])+ DB.exec(<<~SQL, name:, value:, data_type:)+ INSERT INTO site_settings (name, data_type, value, created_at, updated_at)+ VALUES (:name, :data_type, :value, NOW(), NOW())+ SQL+ end++ def setting_value(name)+ DB.query_single("SELECT value FROM site_settings WHERE name = ?", name).first+ end++ def insert_reference(target_type, target_id)+ DB.exec(<<~SQL, upload_id: upload.id, target_type:, target_id:)+ INSERT INTO upload_references (upload_id, target_type, target_id, created_at, updated_at)+ VALUES (:upload_id, :target_type, :target_id, NOW(), NOW())+ SQL+ end++ def reference_types+ DB.query_single("SELECT target_type FROM upload_references WHERE upload_id = ?", upload.id)+ end++ it "renames the tables and their objects, keeping views under the old names until after deploy" do+ old_names = described_class::RENAMED_TABLES.keys.map(&:to_s)+ new_names = described_class::RENAMED_TABLES.values.map(&:to_s)++ described_class.new.up++ expect(relation_names("^blog_", "r")).to match_array(new_names)+ expect(relation_names("^discourse_blog_", "v")).to match_array(old_names)+ expect(relation_names("discourse_blog", "i")).to be_empty+ expect(relation_names("discourse_blog", "S")).to be_empty+ expect(relation_names("^idx_blog_publications_scheduled_at$", "i")).to be_present+ expect(DB.query_single("SELECT COUNT(*) FROM discourse_blog_publications")).to eq([0])++ FinishRenameDiscourseBlogToBlog.new.up+ described_class.new.up++ expect(relation_names("^discourse_blog_", "v")).to be_empty+ expect(relation_names("^blog_", "r")).to match_array(new_names)+ end++ it "renames the settings without overwriting values already saved under the new names" do+ insert_setting("discourse_blog_url", "https://blog.example.com")+ insert_setting("discourse_blog_title", "Old title")+ insert_setting("blog_title", "New title")++ described_class.new.up++ expect(setting_value("blog_url")).to eq("https://blog.example.com")+ expect(setting_value("discourse_blog_url")).to be_nil+ expect(setting_value("blog_title")).to eq("New title")+ end++ it "renames stored class names on upload references, including ones written after deploy" do+ insert_reference("DiscourseBlog::Review", 1)++ described_class.new.up++ expect(reference_types).to contain_exactly("Blog::Review")++ insert_reference("DiscourseBlog::Revision", 2)+ insert_reference("DiscourseBlog::Review", 1)++ FinishRenameDiscourseBlogToBlog.new.up++ expect(reference_types).to contain_exactly("Blog::Review", "Blog::Revision")+ end+enddiff --git a/plugins/blog/spec/migrations/retain_blog_review_uploads_spec.rb b/plugins/blog/spec/migrations/retain_blog_review_uploads_spec.rbnew file mode 100644index 00000000000..d4fc6875fff--- /dev/null+++ b/plugins/blog/spec/migrations/retain_blog_review_uploads_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++require Rails.root.join("plugins/blog/db/migrate/20261008205400_retain_blog_review_uploads.rb")++RSpec.describe RetainBlogReviewUploads do+ fab!(:admin)+ fab!(:topic)++ before do+ @original_verbose = ActiveRecord::Migration.verbose+ ActiveRecord::Migration.verbose = false+ allow(Migration::Helpers).to receive(:existing_site?).and_return(true)+ # This migration predates the table rename.+ DB.exec("CREATE VIEW discourse_blog_reviews AS SELECT * FROM blog_reviews")+ end++ after { ActiveRecord::Migration.verbose = @original_verbose }++ def create_snapshot(cooked, **attributes)+ review =+ Blog::Review.create!(+ topic: topic,+ creator: admin,+ title: topic.title,+ cooked: cooked,+ post_version: 1,+ token: SecureRandom.urlsafe_base64(32),+ expires_at: 7.days.from_now,+ **attributes,+ )+ UploadReference.where(target: review).delete_all+ review+ end++ # This migration predates the rename, so it writes the old class name.+ def references(*reviews)+ UploadReference.where(target_type: "DiscourseBlog::Review", target_id: reviews.map(&:id))+ end++ it "backfills original and optimized uploads only for active snapshots, idempotently" do+ upload = Fabricate(:upload, user: admin)+ optimized_upload = Fabricate(:upload, user: admin)+ optimized = Fabricate(:optimized_image, upload: optimized_upload)+ cooked = "<p><img src=\"#{upload.url}\"><img src=\"#{optimized.url}\"></p>"+ active = create_snapshot(cooked)+ expired = create_snapshot(cooked, expires_at: 1.day.ago)+ revoked = create_snapshot(cooked, revoked_at: Time.current)++ 2.times { described_class.new.up }++ expect(references(active).pluck(:upload_id)).to contain_exactly(upload.id, optimized_upload.id)+ expect(references(expired, revoked)).not_to exist+ end++ it "retains attachments whose cooked links use short upload paths" do+ upload = Fabricate(:upload, user: admin)+ path = "/uploads/short-url/#{Upload.base62_sha1(upload.sha1)}.#{upload.extension}"+ cooked = PrettyText.cook("[Attachment](#{path})")+ expect(cooked).to include(path)+ review = create_snapshot(cooked)++ described_class.new.up++ expect(references(review).pluck(:upload_id)).to eq([upload.id])+ end++ it "writes no references on fresh installs" do+ upload = Fabricate(:upload, user: admin)+ review = create_snapshot("<p><img src=\"#{upload.url}\"></p>")+ allow(Migration::Helpers).to receive(:existing_site?).and_return(false)++ described_class.new.up++ expect(references(review)).not_to exist+ end+enddiff --git a/plugins/blog/spec/models/blog/publication_spec.rb b/plugins/blog/spec/models/blog/publication_spec.rbnew file mode 100644index 00000000000..880ec7c7f7d--- /dev/null+++ b/plugins/blog/spec/models/blog/publication_spec.rb@@ -0,0 +1,45 @@+# frozen_string_literal: true++RSpec.describe Blog::Publication do+ fab!(:topic)++ describe "path validation" do+ it "rejects ambiguous paths, traversal, and reserved endpoints" do+ paths = %w[+ //example.com/story+ https://example.com/story+ /story?query=1+ /story#fragment+ /a/../story+ /a/./story+ /a//story+ /a/%2e%2e/story+ /a%2Fstory+ /a%5cstory+ /a%252fstory+ /a%00story+ /a%ZZstory+ /blog/editor+ /blog/other/story+ /blog/archive/../story+ /posts+ /posts.rss+ /posts.atom+ /feed.xml+ /sitemap.xml+ /robots.txt+ /blog-theme.css+ /blog-custom.js+ /blog-highlight/version.js+ /uploads/story+ /archive+ ]++ paths.each do |path|+ publication = described_class.new(topic: topic, path: path)+ expect(publication).not_to be_valid, "Expected #{path.inspect} to be rejected"+ expect(publication.errors[:path]).to be_present+ end+ end+ end+enddiff --git a/plugins/blog/spec/models/review_spec.rb b/plugins/blog/spec/models/review_spec.rbnew file mode 100644index 00000000000..7ee3f5ba236--- /dev/null+++ b/plugins/blog/spec/models/review_spec.rb@@ -0,0 +1,72 @@+# frozen_string_literal: true++RSpec.describe Blog::Review do+ fab!(:admin)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) { Fabricate(:post, topic: topic, user: admin) }++ let(:upload) { Fabricate(:upload, user: admin, created_at: 3.days.ago) }++ before do+ enable_blog!(category: category, drafts: drafts)+ first_post.update!(+ raw: "",+ cooked: "<p><img src=\"#{upload.url}\"></p>",+ )+ first_post.link_post_uploads+ end++ describe ".issue!" do+ it "retains snapshot uploads after the working draft removes them" do+ review = described_class.issue!(topic: topic, user: admin)+ first_post.update!(raw: "Image removed", cooked: "<p>Image removed</p>")+ first_post.link_post_uploads++ Jobs::CleanUpUploads.new.reset_last_cleanup!+ Jobs::CleanUpUploads.new.execute(nil)++ expect(review.reload).to be_accessible+ expect(review.cooked).to include(upload.url)+ expect(Upload.where(id: upload.id)).to exist+ expect(UploadReference.where(target: review).pluck(:upload_id)).to eq([upload.id])+ end+ end++ describe "#revoke!" do+ it "releases snapshot references without removing the draft's references" do+ review = described_class.issue!(topic: topic, user: admin)+ expect(UploadReference.where(target: review)).to exist++ review.revoke!(admin)++ expect(UploadReference.where(target: review)).not_to exist+ expect(UploadReference.where(target: first_post).pluck(:upload_id)).to eq([upload.id])+ end+ end++ describe ".revoke_for_topic!" do+ it "releases references for every revoked snapshot" do+ reviews = 2.times.map { described_class.issue!(topic: topic, user: admin) }+ expect(UploadReference.where(target: reviews).count).to eq(2)++ described_class.revoke_for_topic!(topic.id)++ expect(described_class.where(id: reviews).where(revoked_at: nil)).not_to exist+ expect(UploadReference.where(target: reviews)).not_to exist+ expect(UploadReference.where(target: first_post).pluck(:upload_id)).to eq([upload.id])+ end+ end++ describe "#destroy!" do+ it "releases references when the snapshot is deleted" do+ review = described_class.issue!(topic: topic, user: admin)+ expect(UploadReference.where(target: review)).to exist++ review.destroy!++ expect(UploadReference.where(target: review)).not_to exist+ end+ end+enddiff --git a/plugins/blog/spec/requests/appearance_spec.rb b/plugins/blog/spec/requests/appearance_spec.rbnew file mode 100644index 00000000000..abb4fac4853--- /dev/null+++ b/plugins/blog/spec/requests/appearance_spec.rb@@ -0,0 +1,160 @@+# frozen_string_literal: true++RSpec.describe "Blog appearance", type: :request do+ fab!(:admin)++ before { enable_blog! }++ def activate_theme(css: "", javascript: "", accent_color: "d64b2a")+ theme =+ Blog::BlogTheme.save(+ {+ "name" => "Spec design",+ "accent_color" => accent_color,+ "paper_color" => "f5f0e6",+ "ink_color" => "19382d",+ "css" => css,+ "javascript" => javascript,+ },+ user: admin,+ )+ Blog::BlogTheme.activate(theme["id"], revision: 1, user: admin)+ theme+ end++ describe "GET blog pages" do+ it "shares the configured community favicon with the blog" do+ icon = Fabricate(:upload)+ SiteSetting.favicon = icon++ get "https://blog.example.com/"++ html = Nokogiri.HTML5(response.body)+ expect(html.at_css('link[rel="icon"]')["href"]).to eq(UrlHelper.absolute(icon.url))+ end++ it "serves one built-in reader stylesheet plus the active design" do+ get "https://blog.example.com/"+ html = Nokogiri.HTML5(response.body)+ expect(response.status).to eq(200)+ expect(html.at_css("body")["data-blog-theme"]).to be_nil+ expect(html.at_css('link[href$="/blog.css"]')).to be_present+ expect(html.at_css('link[href*="blog-theme.css"]')).to be_present+ expect(html.at_css('link[href$="/editorial.css"]')).to be_nil+ end++ it "provides lazy highlighter URLs without eagerly loading the modules" do+ get "https://blog.example.com/"++ html = Nokogiri.HTML5(response.body)+ body = html.at_css("body")+ expect(body["data-blog-highlight-core-url"]).to eq(+ "https://blog.example.com#{Blog::SyntaxHighlighter.path}",+ )+ expect(body["data-blog-highlight-languages-url"]).to eq(+ "#{Discourse.base_url}#{HighlightJs.path}",+ )+ expect(body["data-blog-highlight-auto"]).to eq(SiteSetting.autohighlight_all_code.to_s)+ expect(html.css('script[src*="highlight"], link[rel="modulepreload"]')).to be_empty+ end++ it "provides translated lightbox labels to the public script" do+ get "https://blog.example.com/"++ body = Nokogiri.HTML5(response.body).at_css("body")+ expect(+ body+ .attributes+ .slice(+ *%w[+ data-blog-lightbox-close-label+ data-blog-lightbox-dialog-label+ data-blog-lightbox-open-label+ data-blog-lightbox-open-with-description-label+ data-blog-lightbox-original-label+ ],+ )+ .transform_values(&:value),+ ).to eq(+ "data-blog-lightbox-close-label" => I18n.t("blog.lightbox.close"),+ "data-blog-lightbox-dialog-label" => I18n.t("blog.lightbox.dialog"),+ "data-blog-lightbox-open-label" => I18n.t("blog.lightbox.open"),+ "data-blog-lightbox-open-with-description-label" =>+ I18n.t("blog.lightbox.open_with_description", description: "__IMAGE_DESCRIPTION__"),+ "data-blog-lightbox-original-label" => I18n.t("blog.lightbox.original"),+ )+ end++ it "keeps theme code in separate assets rather than inline HTML" do+ css = 'body::after { content: "</style><script>unsafe()</script>"; }'+ javascript = 'window.blogExample = "</script>";'+ activate_theme(css: css, javascript: javascript)++ get "https://blog.example.com/"+ html = Nokogiri.HTML5(response.body)+ expect(response.body).not_to include(css)+ expect(response.body).not_to include(javascript)+ script = html.at_css("script[data-blog-custom-script]")+ expect(script["src"]).to include("https://blog.example.com/blog-custom.js")+ expect(script["src"]).to include("blog_theme_snapshot=")+ expect(script["nonce"]).to be_present+ expect(response.headers["Content-Security-Policy"]).to include("'nonce-")+ end++ it "offers safe mode without custom CSS or JavaScript" do+ activate_theme(+ css: ".blog { display: none; }",+ javascript: 'throw new Error("broken customization");',+ )++ get "https://blog.example.com/?blog_safe_mode=1"+ html = Nokogiri.HTML5(response.body)+ expect(html.at_css("script[data-blog-custom-script]")).to be_nil+ stylesheet = html.at_css('link[href*="blog-theme.css"]')+ expect(stylesheet["href"]).to include("blog_safe_mode=1")+ get "https://blog.example.com/blog-theme.css?blog_safe_mode=1"+ expect(response.body).not_to include(".blog { display: none; }")+ expect(response.body).to include("--blog-accent-color")+ get "https://blog.example.com/blog-custom.js?blog_safe_mode=1"+ expect(response.body).to be_empty+ end+ end++ describe "GET theme assets" do+ it "serves theme code with explicit types and without caching" do+ css = ".blog__brand { letter-spacing: 0.1em; }"+ javascript = 'document.body.dataset.blogDemo = "active";'+ activate_theme(css: css, javascript: javascript)++ get "https://blog.example.com/blog-theme.css"+ expect(response.status).to eq(200)+ expect(response.media_type).to eq("text/css")+ expect(response.body).to include(css)+ expect(response.headers["Cache-Control"]).to include("no-store")++ get "https://blog.example.com/blog-custom.js"+ expect(response.status).to eq(200)+ expect(response.media_type).to eq("application/javascript")+ expect(response.body).to eq(javascript)+ expect(response.headers["X-Content-Type-Options"]).to eq("nosniff")+ end++ it "falls back to the built-in design before any theme is activated" do+ get "https://blog.example.com/blog-theme.css"+ expect(response.status).to eq(200)+ expect(response.body).to include(+ "--blog-accent-color: ##{Blog::BlogTheme::BUILT_IN_PALETTE["accent_color"]}",+ )+ end++ it "does not serve or inject blog JavaScript on the discussion origin" do+ activate_theme(javascript: 'window.blogOnly = "active";')++ get "/blog-custom.js"+ expect(response.status).to eq(404)+ expect(response.body).not_to include("window.blogOnly")+ get "/"+ expect(response.body).not_to include("/blog-custom.js")+ end+ end+enddiff --git a/plugins/blog/spec/requests/article_summary_spec.rb b/plugins/blog/spec/requests/article_summary_spec.rbnew file mode 100644index 00000000000..a4d50dd58e9--- /dev/null+++ b/plugins/blog/spec/requests/article_summary_spec.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++RSpec.describe "Blog article summaries", type: :request do+ fab!(:admin)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) do+ Fabricate(+ :post,+ topic: topic,+ user: admin,+ raw: ("A practical workflow worth explaining. " * 60),+ )+ end++ before do+ enable_blog!(category: category, drafts: drafts)+ @publication = Blog::Publication.for_topic(topic)+ @publication.save_metadata!(admin, path: "/workflow", excerpt: "An editorial summary.")+ end++ it "provides an excerpt and blog link without replacing the full cooked post" do+ @publication.publish!(admin)+ get "/t/#{@publication.discussion_topic_id}.json"++ expect(response.status).to eq(200)+ post = response.parsed_body["post_stream"]["posts"].first+ expect(post["blog_article"]).to eq(+ "url" => @publication.url,+ "excerpt" => @publication.excerpt,+ "blog_name" => SiteSetting.blog_title,+ )+ expect(post["cooked"]).to eq(first_post.reload.cooked)+ end++ it "leaves short published posts uncompressed" do+ first_post.revise(admin, raw: "A short announcement that should remain fully visible.")+ @publication.publish!(admin)+ get "/t/#{@publication.discussion_topic_id}.json"++ expect(response.parsed_body["post_stream"]["posts"].first["blog_article"]).to be_nil+ end++ it "does not offer summaries for private drafts, even to editors" do+ sign_in(admin)+ get "/t/#{topic.id}.json"++ expect(response.status).to eq(200)+ expect(response.parsed_body["post_stream"]["posts"].first["blog_article"]).to be_nil+ end++ it "removes summary metadata when an article is unpublished" do+ @publication.publish!(admin)+ @publication.unpublish!(admin)+ get "/t/#{@publication.discussion_topic_id}.json"++ expect(response.status).to eq(200)+ expect(response.parsed_body["post_stream"]["posts"].first["blog_article"]).to be_nil+ end+enddiff --git a/plugins/blog/spec/requests/blog_path_spec.rb b/plugins/blog/spec/requests/blog_path_spec.rbnew file mode 100644index 00000000000..ea87c4edcfd--- /dev/null+++ b/plugins/blog/spec/requests/blog_path_spec.rb@@ -0,0 +1,118 @@+# frozen_string_literal: true++RSpec.describe "Blog under /blog", type: :request do+ fab!(:admin)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) do+ Fabricate(:post, topic: topic, user: admin, raw: "An article published under the forum.")+ end++ before { enable_blog!(category: category, drafts: drafts, custom_domain: false) }++ let!(:publication) do+ publication = Blog::Publication.for_topic(topic)+ publication.path = "/first-story"+ publication.publish!(admin)+ publication+ end++ it "serves articles, listings and feeds under /blog" do+ get "/blog/first-story"+ expect(response.status).to eq(200)+ html = Nokogiri.HTML5(response.body)+ expect(html.at_css('link[rel="canonical"]')["href"]).to eq(publication.url)+ expect(html.at_css(".blog-article__body").text).to include(first_post.raw)++ %w[/blog /blog/archive /blog/feed.xml /blog/sitemap.xml /blog/about].each do |path|+ get path+ expect(response.status).to eq(200)+ end+ get "/blog/feed.xml"+ expect(response.body).to include(publication.url)+ end++ it "leaves the forum's own paths and robots.txt alone" do+ get "/first-story"+ expect(response.body).not_to include(first_post.raw)++ get "/robots.txt"+ expect(response.body).not_to include("/blog/sitemap.xml")+ get "/blog/robots.txt"+ expect(response.status).to eq(404)+ end++ it "redirects an old article path to its current one" do+ old_url = publication.url+ publication.save_metadata!(admin, path: "/renamed-story")+ publication.publish!(admin)++ get old_url+ expect(response.status).to eq(301)+ expect(response).to redirect_to("#{Discourse.base_url}/blog/renamed-story")+ end++ it "keeps the editor outside the public blog" do+ sign_in(admin)+ get "/blog-editor.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["blog_url"]).to eq("#{Discourse.base_url}/blog")+ end++ it "serves review links from the forum origin" do+ sign_in(admin)+ post "/blog-editor/publications/#{topic.id}/reviews.json"+ expect(response.status).to eq(201)+ url = response.parsed_body.dig("review", "url")+ expect(url).to start_with("#{Discourse.base_url}/blog/review?")+ token = Rack::Utils.parse_query(URI(url).query)["review_token"]++ get "/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(200)+ expect(response.parsed_body["title"]).to eq(topic.title)++ post "/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Looks good",+ },+ },+ headers: {+ "Origin" => Discourse.base_url_no_prefix,+ }+ expect(response.status).to eq(204)+ end++ it "can be chosen as the homepage" do+ SiteSetting.default_homepage = "blog"++ get "/"+ expect(response.status).to eq(200)+ expect(Nokogiri.HTML5(response.body).at_css("body.blog")).to be_present+ expect(response.body).to include(publication.url)+ end++ it "sends the blog's base URL to the client" do+ get "/site.json"+ expect(response.parsed_body["blog_base_url"]).to eq("#{Discourse.base_url}/blog")+ end++ describe "with a custom domain" do+ before { enable_blog!(category: category, drafts: drafts) }++ it "redirects /blog on the forum to the blog's hostname" do+ get "/blog/first-story?ref=1"+ expect(response.status).to eq(302)+ expect(response).to redirect_to("https://blog.example.com/first-story?ref=1")++ get "/blog"+ expect(response).to redirect_to("https://blog.example.com/")+ end++ it "no longer offers the blog as a homepage" do+ expect(HomepageSiteSetting.choices).not_to include("blog")+ end+ end+enddiff --git a/plugins/blog/spec/requests/blog_spec.rb b/plugins/blog/spec/requests/blog_spec.rbnew file mode 100644index 00000000000..8def655d4f1--- /dev/null+++ b/plugins/blog/spec/requests/blog_spec.rb@@ -0,0 +1,527 @@+# frozen_string_literal: true++RSpec.describe "Blog publication", type: :request do+ fab!(:admin)+ fab!(:user)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) do+ Fabricate(+ :post,+ topic: topic,+ user: admin,+ raw: "A private article that is not yet ready for the world.",+ )+ end++ before { enable_blog!(category: category, drafts: drafts) }++ describe "GET /blog-editor.json" do+ it "requires staff access" do+ get "/blog-editor.json"+ expect(response.status).to eq(403)+ sign_in(user)+ get "/blog-editor.json"+ expect(response.status).to eq(403)+ end++ it "serves the blog under /blog when the blog URL is the forum's own hostname" do+ SiteSetting.blog_url = "https://test.localhost"+ sign_in(admin)+ get "/blog-editor.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["blog_url"]).to eq("#{Discourse.base_url}/blog")+ end++ it "renders an anonymous login shell without exposing draft data" do+ get "/blog-editor"+ expect(response.status).to eq(200)+ expect(response.body).not_to include(topic.title)+ get "/blog-editor.json"+ expect(response.status).to eq(403)+ end++ it "reports anonymous upload restrictions without exposing the public blog" do+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)+ SiteSetting.prevent_anons_from_downloading_files = true++ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ expect(publication.reload).not_to be_publicly_visible++ get "https://test.localhost/session/#{admin.encoded_username}/become"+ get "https://test.localhost/blog-editor.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["error"]).to eq(I18n.t("blog.errors.anonymous_uploads"))++ post "https://test.localhost/blog-editor/publications/#{topic.id}/publish.json"+ expect(response.status).to eq(400)+ end++ it "lists only editorial topics" do+ Fabricate(:topic)+ sign_in(admin)+ get "/blog-editor.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to contain_exactly(+ topic.id,+ )+ expect(response.parsed_body["error"]).to be_nil+ end+ end++ describe "PUT /blog-editor/publications/:topic_id" do+ before { sign_in(admin) }++ it "rejects paths reserved by routing" do+ %w[/sitemap /images/story /font/story /plugins/story /about].each do |path|+ put "/blog-editor/publications/#{topic.id}.json", params: { publication: { path: path } }+ expect(response.status).to eq(422)+ end+ expect(Blog::Publication.where(topic_id: topic.id)).not_to exist+ end++ it "rejects null metadata and invalid dates without a database error" do+ [+ { excerpt: nil },+ { featured: nil },+ { published_at: "not-a-date" },+ { published_at: 1.day.from_now.iso8601 },+ ].each do |attributes|+ put "/blog-editor/publications/#{topic.id}.json",+ params: {+ publication: attributes,+ },+ as: :json+ expect(response.status).to eq(422)+ end+ end++ it "rejects drafts categories that ordinary groups can read" do+ group = Fabricate(:group)+ drafts.set_permissions(group.name => :full, :staff => :full)+ drafts.save!+ put "/blog-editor/publications/#{topic.id}.json",+ params: {+ publication: {+ excerpt: "A draft",+ },+ }+ expect(response.status).to eq(400)+ expect(Blog::Publication.where(topic_id: topic.id)).not_to exist+ end+ end++ describe "GET /blog-editor/preview/:topic_id" do+ it "allows a staff-only uncached preview without publishing" do+ design =+ Blog::BlogTheme.save(+ {+ "name" => "Spec design",+ "accent_color" => "d64b2a",+ "paper_color" => "f5f0e6",+ "ink_color" => "19382d",+ "css" => "",+ "javascript" => "window.blogOnly = true;",+ },+ user: admin,+ )+ Blog::BlogTheme.activate(design["id"], revision: 1, user: admin)++ get "/blog-editor/preview/#{topic.id}"+ expect(response.status).to eq(404)+ sign_in(admin)+ get "/blog-editor/preview/#{topic.id}"+ expect(response.status).to eq(200)+ expect(response.body).to include(first_post.cooked)+ expect(Nokogiri.HTML5(response.body).at_css("script[data-blog-custom-script]")).to be_nil+ expect(response.headers["X-Robots-Tag"]).to include("noindex")+ expect(response.headers["Cache-Control"]).to include("no-store")+ expect(Blog::Publication.where(topic_id: topic.id)).not_to exist+ expect(topic.reload.category_id).to eq(drafts.id)+ end+ end++ describe "POST /blog-editor/publications/:topic_id/publish" do+ it "publishes a private draft, serves it on the blog host, and preserves the discussion" do+ sign_in(admin)+ put "/blog-editor/publications/#{topic.id}.json",+ params: {+ publication: {+ path: "/first-story",+ excerpt: "A careful introduction",+ },+ }+ expect(response.status).to eq(200)+ post "/blog-editor/publications/#{topic.id}/submit.json"+ expect(response.status).to eq(200)+ revision_id = response.parsed_body.dig("submitted_revision", "id")+ post "/blog-editor/publications/#{topic.id}/approve.json",+ params: {+ revision_id: revision_id,+ }+ expect(response.status).to eq(200)+ post "/blog-editor/publications/#{topic.id}/publish.json",+ params: {+ revision_id: revision_id,+ }+ expect(response.status).to eq(200)+ publication = Blog::Publication.find_by!(topic_id: topic.id)+ expect(publication.discussion_topic.reload.category_id).to eq(category.id)+ expect(publication).to be_publicly_visible+ expect(TopicView.new(publication.discussion_topic_id).canonical_path).to eq(publication.url)++ get "https://blog.example.com/first-story"+ expect(response.status).to eq(200)+ html = Nokogiri.HTML5(response.body)+ expect(html.at_css('link[rel="canonical"]')["href"]).to eq(publication.url)+ expect(html.at_css("#discourse-comments")["data-topic-id"]).to eq(+ publication.discussion_topic_id.to_s,+ )+ expect(html.at_css(".blog-article__body").text).to include(first_post.raw)+ expect(response.headers["Cache-Control"]).to include("no-store")+ end++ it "rejects unrelated topics and normal users" do+ sign_in(admin)+ other_topic = Fabricate(:topic)+ post "/blog-editor/publications/#{other_topic.id}/publish.json"+ expect(response.status).to eq(403)+ sign_in(user)+ post "/blog-editor/publications/#{topic.id}/publish.json"+ expect(response.status).to eq(403)+ expect(topic.reload.category_id).to eq(drafts.id)+ end++ it "fails closed when the draft category is public" do+ SiteSetting.blog_drafts_category = category.id+ sign_in(admin)+ post "/blog-editor/publications/#{topic.id}/publish.json"+ expect(response.status).to eq(403)+ expect(topic.reload.category_id).to eq(drafts.id)+ end+ end++ describe "GET blog articles and feeds" do+ let!(:publication) do+ publication = Blog::Publication.for_topic(topic)+ publication.path = "/private-to-public"+ publication.publish!(admin)+ publication+ end++ it "preserves historical canonical paths through publishing and corrections" do+ paths = %w[+ /archive/2011/03/30/How+I+learned+to+write+my+own+ORM+ /archive/2009/01/02/My+server+just+died%2C+long+live+my+new+VPS+ /archive/2008/06/06/video_browser_past_present_and_future+ /archive/2011/09/08/Extending+the+ASP.NET+error+page+ /blog/archive/2007/02/16/7.aspx+ ]+ previous_url = publication.url++ paths.each do |path|+ publication.save_metadata!(admin, path: path)+ publication.publish!(admin)++ get "https://blog.example.com#{path}"+ expect(response.status).to eq(200)+ html = Nokogiri.HTML5(response.body)+ expect(html.at_css('link[rel="canonical"]')["href"]).to eq(+ "https://blog.example.com#{path}",+ )+ expect(html.at_css(".blog-article__body").text).to include(first_post.raw)+ expect(html.at_css("#discussion #comments")).to be_present++ get previous_url+ expect(response).to redirect_to("https://blog.example.com#{path}")+ expect(response.status).to eq(301)+ previous_url = publication.url+ end++ publication.unpublish!(admin)+ paths.each do |path|+ get "https://blog.example.com#{path}"+ expect(response.status).to eq(404)+ end+ end++ it "permanently redirects legacy index and feed endpoints on the blog host" do+ {+ "/posts" => "/",+ "/posts.rss" => "/feed.xml",+ "/posts.atom" => "/feed.xml",+ }.each do |path, target|+ get "https://blog.example.com#{path}"+ expect(response.status).to eq(301)+ expect(response).to redirect_to("https://blog.example.com#{target}")+ end+ end++ it "preserves the configured blog host when it is not a database hostname alias" do+ RailsMultisite::ConnectionManagement.stubs(:current_db_hostnames).returns(["test.localhost"])++ get "https://blog.example.com#{publication.path}",+ headers: {+ "X-Forwarded-Host" => "untrusted.example.com",+ }++ expect(request.env["HTTP_HOST"]).to eq("blog.example.com")+ expect(request.env["HTTP_X_FORWARDED_HOST"]).to be_nil+ expect(response.status).to eq(200)+ expect(response.body).to include(publication.url)+ end++ it "supports an explicit default port and rejects other ports" do+ RailsMultisite::ConnectionManagement.stubs(:current_db_hostnames).returns(["test.localhost"])++ get publication.path, headers: { "Host" => "blog.example.com:443" }+ expect(request.env["HTTP_HOST"]).to eq("blog.example.com:443")+ expect(response.body).to include(publication.url)++ get publication.path, headers: { "Host" => "blog.example.com:444" }+ expect(request.env["HTTP_HOST"]).to eq("test.localhost")+ expect(response.body).not_to include(publication.url)+ end++ it "continues rewriting untrusted hosts to the discussion host" do+ RailsMultisite::ConnectionManagement.stubs(:current_db_hostnames).returns(["test.localhost"])++ get "https://untrusted.example.com#{publication.path}",+ headers: {+ "X-Forwarded-Host" => "blog.example.com",+ }++ expect(request.env["HTTP_HOST"]).to eq("test.localhost")+ expect(request.env["HTTP_X_FORWARDED_HOST"]).to be_nil+ expect(response.body).not_to include(publication.url)+ end++ it "exposes only published articles across the homepage, archive, feed and sitemap" do+ unpublished = Fabricate(:topic, category: category)+ %w[/ /archive /feed.xml /sitemap.xml].each do |path|+ get "https://blog.example.com#{path}"+ expect(response.status).to eq(200)+ expect(response.body).to include(publication.url)+ expect(response.body).not_to include(unpublished.title)+ end+ end++ it "serves robots, the About page, and tag pages from the same published set" do+ SiteSetting.blog_about = "We publish **field notes** from the team."+ DiscourseTagging.tag_topic_by_names(+ publication.discussion_topic,+ Guardian.new(admin),+ ["field-notes"],+ )++ get "https://blog.example.com/robots.txt"+ expect(response.status).to eq(200)+ expect(response.body).to include("Sitemap: https://blog.example.com/sitemap.xml")++ get "https://blog.example.com/about"+ expect(response.status).to eq(200)+ expect(response.body).to include("<strong>field notes</strong>")+ expect(response.body).not_to include(publication.url)++ get "https://blog.example.com/tag/field-notes"+ expect(response.status).to eq(200)+ expect(response.body).to include(publication.url)++ get "https://blog.example.com/tag/some-other-tag"+ expect(response.status).to eq(404)+ end++ it "leads the homepage with featured articles" do+ featured_topic = Fabricate(:topic, category: drafts, user: admin)+ Fabricate(+ :post,+ topic: featured_topic,+ user: admin,+ raw: "A featured story for the homepage.",+ )+ featured = Blog::Publication.for_topic(featured_topic)+ featured.path = "/featured-story"+ featured.save_metadata!(admin, featured: true)+ featured.publish!(admin)++ get "https://blog.example.com/"++ expect(response.status).to eq(200)+ body = response.body+ expect(body.index(featured.url)).to be < body.index(publication.url)+ expect(body).to include("<span class=\"blog__badge\">#{I18n.t("blog.featured")}</span>")+ end++ it "withdraws all public surfaces immediately when the category becomes private" do+ publication.discussion_topic.update!(category: drafts)+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ %w[/ /feed.xml /sitemap.xml].each do |path|+ get "https://blog.example.com#{path}"+ expect(response.body).not_to include(topic.title)+ end+ expect(TopicView.new(topic.id, admin).canonical_path).not_to eq(publication.url)+ end++ it "withdraws a hidden or deleted first post even for an editor" do+ sign_in(admin)+ publication.discussion_topic.first_post.update!(hidden: true)+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ publication.discussion_topic.first_post.update!(hidden: false, deleted_at: Time.current)+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ end++ it "does not publish topics from subcategories" do+ child = Fabricate(:category, parent_category: category)+ publication.discussion_topic.update!(category: child)+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ end++ it "retains old article paths as redirects and prevents taking another article path" do+ publication.save_metadata!(admin, path: "/renamed-story")+ publication.publish!(admin)+ get "https://blog.example.com/private-to-public"+ expect(response.status).to eq(301)+ expect(response.location).to eq(publication.url)+ host! "test.localhost"+ another = Fabricate(:topic, category: drafts)+ Fabricate(:post, topic: another)+ sign_in(admin)+ put "/blog-editor/publications/#{another.id}.json",+ params: {+ publication: {+ path: "/private-to-public",+ },+ }+ expect(response.status).to eq(422)+ end++ it "keeps later draft edits private until an approved revision is published" do+ topic.update!(title: "An article with <script>alert(1)</script>")+ first_post.revise(admin, raw: "An updated article, now ready for everyone to read.")+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(200)+ html = Nokogiri.HTML5(response.body)+ expect(html.at_css(".blog-article__body").text).not_to include(first_post.reload.raw)+ publication.publish!(admin)+ get "https://blog.example.com#{publication.path}"+ html = Nokogiri.HTML5(response.body)+ expect(html.at_css(".blog-article__body").text).to include(first_post.raw)+ expect(html.css("h1 script")).to be_empty+ end++ it "supports stable dated paths, title search, and empty feeds" do+ publication.save_metadata!(admin, path: "/archive/2026/09/08/a-story")+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(200)+ get "https://blog.example.com/archive", params: { q: topic.title }+ expect(response.status).to eq(200)+ expect(response.body).to include(publication.url)+ expect(response.headers["X-Robots-Tag"]).to eq("noindex")+ publication.unpublish!(admin)+ get "https://blog.example.com/feed.xml"+ expect(response.status).to eq(200)+ expect(Nokogiri.XML(response.body).xpath("//item")).to be_empty+ end++ it "keeps core shared drafts private even if moved into the blog category" do+ SharedDraft.create!(topic: publication.discussion_topic, category: category)+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ expect(response.body).not_to include(topic.title)+ end++ it "avoids prompting for the first reply on a closed empty discussion" do+ publication.discussion_topic.update!(closed: true)+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(200)+ expect(response.body).to include(I18n.t("blog.discussion_closed"))+ expect(Nokogiri.HTML5(response.body).at_css("#discourse-comments")).to be_nil+ end++ it "preserves page-specific discussion canonicals" do+ expect(TopicView.new(publication.discussion_topic_id, nil, page: 2).canonical_path).not_to eq(+ publication.url,+ )+ get publication.discussion_topic.relative_url+ expect(response.status).to eq(200)+ expect(Nokogiri.HTML5(response.body).at_css('link[rel="canonical"]')["href"]).to eq(+ publication.url,+ )+ end++ it "keeps drafts off normal anonymous discussion endpoints" do+ topic.update!(category: drafts)+ get "/t/#{topic.slug}/#{topic.id}.json"+ expect(response.status).to eq(404)+ get "/latest.json"+ expect(+ response.parsed_body["topic_list"]["topics"].map { |entry| entry["id"] },+ ).not_to include(topic.id)+ end++ it "keeps core routes on the discussion host" do+ get "/about.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body).to have_key("about")+ get "/blog-editor.json"+ expect(response.status).to eq(403)+ get "https://blog.example.com/blog-editor.json"+ expect(response.status).to eq(404)+ end++ it "fails closed on private sites and secure uploads" do+ setup_s3+ SiteSetting.secure_uploads = true+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ expect(publication.reload).not_to be_publicly_visible+ end+ end++ describe "DELETE /blog-editor/publications/:topic_id" do+ it "withdraws the blog without privatizing the discussion" do+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)+ sign_in(admin)+ delete "/blog-editor/publications/#{topic.id}.json"+ expect(response.status).to eq(204)+ expect(publication.discussion_topic.reload.category_id).to eq(category.id)+ expect(publication.reload).not_to be_publicly_visible+ expect(TopicView.new(publication.discussion_topic_id).canonical_path).not_to eq(+ publication.url,+ )+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(404)+ end+ end++ describe "POST /blog-editor/publications/:topic_id/return-to-drafts" do+ it "returns an article without replies to private drafts" do+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)+ sign_in(admin)+ post "/blog-editor/publications/#{topic.id}/return-to-drafts.json"+ expect(response.status).to eq(204)+ expect(topic.reload.category_id).to eq(drafts.id)+ expect(publication.reload).not_to be_published+ end++ it "preserves public access to other people's replies" do+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)+ reply = Fabricate(:post, topic: publication.discussion_topic, user: user)+ sign_in(admin)+ post "/blog-editor/publications/#{topic.id}/return-to-drafts.json"+ expect(response.status).to eq(204)+ expect(publication.discussion_topic.reload.category_id).to eq(category.id)+ expect(reply.reload.topic_id).to eq(publication.discussion_topic_id)+ end+ end+enddiff --git a/plugins/blog/spec/requests/editor_filtering_spec.rb b/plugins/blog/spec/requests/editor_filtering_spec.rbnew file mode 100644index 00000000000..ac81272c879--- /dev/null+++ b/plugins/blog/spec/requests/editor_filtering_spec.rb@@ -0,0 +1,84 @@+# frozen_string_literal: true++RSpec.describe "Blog editor filtering", type: :request do+ fab!(:admin)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:published_topic) do+ Fabricate(:topic, category: category, user: admin, title: "Published workflow")+ end+ fab!(:published_post) { Fabricate(:post, topic: published_topic, user: admin) }+ fab!(:publication) do+ Blog::Publication.create!(+ topic: published_topic,+ discussion_topic: published_topic,+ path: "/special-workflow",+ excerpt: "A summary",+ published: true,+ published_at: 2.days.ago,+ )+ end++ before do+ enable_blog!(category: category, drafts: drafts)+ sign_in(admin)+ end++ it "filters the entire collection before applying the page limit" do+ published_topic.update_column(:updated_at, 3.days.ago)+ Fabricate.times(31, :topic, category: drafts)++ get "/blog-editor.json", params: { filter: "published" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to eq([published_topic.id])+ expect(response.parsed_body["more"]).to eq(false)+ end++ it "paginates search results in a stable order within the selected status" do+ matching =+ 31.times.map { |index| Fabricate(:topic, category: drafts, title: "Needle article #{index}") }+ Topic.where(id: matching.map(&:id)).update_all(updated_at: 1.day.ago)+ Fabricate(:topic, category: drafts, title: "Unrelated newer draft")+ Fabricate(:topic, title: "Needle outside editorial categories")++ get "/blog-editor.json", params: { filter: "drafts", q: "NEEDLE" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to eq(+ matching.reverse.first(30).map(&:id),+ )+ expect(response.parsed_body["more"]).to eq(true)++ get "/blog-editor.json", params: { filter: "drafts", q: "NEEDLE", page: 1 }+ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to eq([matching.first.id])+ expect(response.parsed_body["more"]).to eq(false)+ end++ it "searches stored article paths and treats wildcard characters literally" do+ get "/blog-editor.json", params: { q: "special-workflow" }+ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to eq([published_topic.id])++ literal = Fabricate(:topic, category: drafts, title: "A 100%_literal example")+ Fabricate(:topic, category: drafts, title: "An unrelated example")+ get "/blog-editor.json", params: { q: "%_" }+ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to eq([literal.id])+ end++ it "separates unpublished public topics from private drafts and live articles" do+ unpublished = Fabricate(:topic, category: category)+ Fabricate(:topic, category: drafts)++ get "/blog-editor.json", params: { filter: "unpublished" }++ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to eq([unpublished.id])+ end++ it "rejects invalid filters and oversized or structured search input" do+ get "/blog-editor.json", params: { filter: "invalid" }+ expect(response.status).to eq(400)+ get "/blog-editor.json", params: { q: "a" * 101 }+ expect(response.status).to eq(400)+ get "/blog-editor.json", params: { q: { title: "test" } }+ expect(response.status).to eq(400)+ end+enddiff --git a/plugins/blog/spec/requests/editorial_workflow_spec.rb b/plugins/blog/spec/requests/editorial_workflow_spec.rbnew file mode 100644index 00000000000..67b55803f20--- /dev/null+++ b/plugins/blog/spec/requests/editorial_workflow_spec.rb@@ -0,0 +1,317 @@+# frozen_string_literal: true++RSpec.describe "Blog editorial workflow", type: :request do+ fab!(:admin)+ fab!(:category)+ fab!(:writers, :group)+ fab!(:writer) { Fabricate(:user, groups: [writers], refresh_auto_groups: true) }+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: writer) }+ fab!(:first_post) do+ Fabricate(+ :post,+ topic: topic,+ user: writer,+ raw: "An article ready for a careful editorial review.",+ )+ end++ before do+ enable_blog!(category: category, drafts: drafts)+ SiteSetting.blog_contributor_groups = writers.id.to_s+ drafts.set_permissions(:staff => :full, writers.name => :full)+ drafts.save!+ end++ it "requires explicit approval and copies only the frozen article, keeping editorial replies private" do+ note =+ Fabricate(+ :post,+ topic: topic,+ user: admin,+ raw: "Confidential editorial notes must never become public.",+ )+ sign_in(writer)+ post "/blog-editor/publications/#{topic.id}/submit.json"+ expect(response.status).to eq(200)+ revision_id = response.parsed_body.dig("submitted_revision", "id")+ post "/blog-editor/publications/#{topic.id}/approve.json", params: { revision_id: revision_id }+ expect(response.status).to eq(403)+ post "/blog-editor/publications/#{topic.id}/publish.json", params: { revision_id: revision_id }+ expect(response.status).to eq(403)++ sign_in(admin)+ post "/blog-editor/publications/#{topic.id}/publish.json", params: { revision_id: revision_id }+ expect(response.status).to eq(400)+ post "/blog-editor/publications/#{topic.id}/approve.json", params: { revision_id: revision_id }+ expect(response.status).to eq(200)+ first_post.revise(writer, raw: "A newer private edit that has not been submitted or approved.")+ post "/blog-editor/publications/#{topic.id}/publish.json", params: { revision_id: revision_id }+ expect(response.status).to eq(200)++ publication = Blog::Publication.find_by!(topic: topic)+ discussion = publication.discussion_topic+ expect(discussion.id).not_to eq(topic.id)+ expect(discussion.posts.count).to eq(1)+ expect(discussion.first_post.raw).to eq(publication.published_revision.raw)+ expect(discussion.first_post.raw).not_to eq(first_post.reload.raw)+ expect(note.reload.topic_id).to eq(topic.id)+ expect(topic.reload.category_id).to eq(drafts.id)+ expect(admin.guardian.can_edit_post?(discussion.first_post)).to eq(false)+ expect(writer.guardian.can_edit_post?(first_post)).to eq(true)+ get "https://blog.example.com#{publication.path}"+ expect(response.status).to eq(200)+ expect(response.body).not_to include(first_post.raw, note.raw)+ end++ it "preserves existing discussion IDs and replies while staging a private working copy" do+ topic.update_column(:category_id, category.id)+ topic.reload+ publication =+ Blog::Publication.create!(+ topic: topic,+ discussion_topic: topic,+ path: "/existing",+ published: true,+ published_at: 1.day.ago,+ )+ reply = Fabricate(:post, topic: topic, user: writer)+ source = publication.prepare_draft!(admin)+ expect(source.category_id).to eq(drafts.id)+ expect(source.posts.count).to eq(1)+ expect(source.first_post.raw).to eq(first_post.raw)+ source.first_post.revise(+ admin,+ raw: "A carefully revised article that should only go live after approval.",+ )+ publication.save_metadata!(admin, path: "/updated", excerpt: "A staged introduction")+ expect(publication.reload.path).to eq("/existing")+ expect(publication.published_revision.raw).to eq(first_post.raw)+ publication.publish!(admin)+ expect(publication.discussion_topic_id).to eq(topic.id)+ expect(reply.reload.topic_id).to eq(topic.id)+ expect(first_post.reload.raw).to eq(source.first_post.raw)+ expect(publication.path).to eq("/updated")+ end++ it "denies contributors access to someone else's drafts and frozen revisions" do+ other = Fabricate(:topic, category: drafts, user: admin)+ Fabricate(:post, topic: other, user: admin)+ publication = Blog::Publication.for_topic(other)+ revision = publication.submit!(admin)+ sign_in(writer)+ get "/blog-editor/publications/#{other.id}.json"+ expect(response.status).to eq(403)+ get "/blog-editor/preview/#{other.id}", params: { revision_id: revision.id }+ expect(response.status).to eq(403)+ get "/blog-editor.json"+ expect(response.parsed_body["topics"].map { |entry| entry["id"] }).to contain_exactly(topic.id)+ end++ it "previews the submitted snapshot rather than later edits" do+ publication = Blog::Publication.for_topic(topic)+ revision = publication.submit!(admin)+ first_post.revise(+ writer,+ raw: "Later unpublished article content must stay out of the revision preview.",+ )+ sign_in(admin)+ get "/blog-editor/preview/#{topic.id}", params: { revision_id: revision.id }+ expect(response.status).to eq(200)+ expect(response.body).to include(revision.raw)+ expect(response.body).not_to include(first_post.reload.raw)+ expect(response.headers["Cache-Control"]).to include("no-store")+ end++ it "publishes the scheduled approved revision exactly once even after a newer submission" do+ freeze_time+ publication = Blog::Publication.for_topic(topic)+ revision = publication.submit!(admin)+ publication.approve!(admin, revision.id)+ publication.schedule!(admin, revision_id: revision.id, at: 2.hours.from_now.iso8601)+ token = publication.schedule_token+ first_post.revise(+ writer,+ raw: "Another draft for the next editorial round, not this scheduled release.",+ )+ publication.submit!(writer)+ Jobs::PublishBlogRevision.new.execute(publication_id: publication.id, token: token)+ expect(publication.reload).not_to be_published+ freeze_time 3.hours.from_now+ Jobs::PublishBlogRevision.new.execute(publication_id: publication.id, token: token)+ expect(publication.reload.published_revision_id).to eq(revision.id)+ expect(publication.discussion_topic.first_post.raw).to eq(revision.raw)+ expect {+ Jobs::PublishBlogRevision.new.execute(publication_id: publication.id, token: token)+ }.not_to change(Topic, :count)+ expect(publication.scheduled_at).to be_nil+ end++ it "invalidates canceled schedules and fails closed when publisher access is removed" do+ freeze_time+ publication = Blog::Publication.for_topic(topic)+ revision = publication.submit!(admin)+ publication.approve!(admin, revision.id)+ publication.schedule!(admin, revision_id: revision.id, at: 2.hours.from_now.iso8601)+ canceled_token = publication.schedule_token+ publication.cancel_schedule!(admin)+ publication.schedule!(admin, revision_id: revision.id, at: 2.hours.from_now.iso8601)+ token = publication.schedule_token+ freeze_time 3.hours.from_now+ publication.run_schedule!(canceled_token)+ expect(publication.reload).not_to be_published+ admin.update!(suspended_till: 1.day.from_now)+ publication.run_schedule!(token)+ expect(publication.reload).not_to be_published+ expect(publication.scheduled_at).to be_nil+ expect(publication.schedule_error).to be_present+ end++ it "rejects stale approvals and cross-article revision IDs without altering approval provenance" do+ publication = Blog::Publication.for_topic(topic)+ revision = publication.submit!(admin)+ publication.approve!(admin, revision.id)+ approved_at = revision.reload.approved_at+ freeze_time 1.hour.from_now+ publication.approve!(admin, revision.id)+ expect(revision.reload.approved_at).to eq_time(approved_at)+ publication.submit!(admin)+ expect { publication.approve!(admin, revision.id) }.to raise_error(Discourse::InvalidParameters)+ other = Fabricate(:topic, category: drafts, user: admin)+ Fabricate(:post, topic: other, user: admin)+ other_revision = Blog::Publication.for_topic(other).submit!(admin)+ expect { publication.approve!(admin, other_revision.id) }.to raise_error(+ ActiveRecord::RecordNotFound,+ )+ end++ it "prevents even administrators from moving an untracked editorial topic directly into public view" do+ sign_in(admin)+ put "/t/#{topic.id}.json", params: { category_id: category.id }+ expect(response.status).to eq(422)+ expect(topic.reload.category_id).to eq(drafts.id)+ expect(Blog::Publication.where(topic_id: topic.id)).not_to exist+ end++ it "records a scheduled path collision without leaving an expired schedule behind" do+ freeze_time+ publication = Blog::Publication.for_topic(topic)+ publication.save_metadata!(admin, path: "/contested-path")+ revision = publication.submit!(admin)+ publication.approve!(admin, revision.id)+ publication.schedule!(admin, revision_id: revision.id, at: 2.hours.from_now.iso8601)+ token = publication.schedule_token+ other = Fabricate(:topic, category: drafts, user: admin)+ Fabricate(:post, topic: other, user: admin)+ competitor = Blog::Publication.for_topic(other)+ competitor.save_metadata!(admin, path: "/contested-path")+ competitor.publish!(admin)+ freeze_time 3.hours.from_now+ expect { publication.run_schedule!(token) }.not_to change(Topic, :count)+ expect(publication.reload.scheduled_at).to be_nil+ expect(publication.schedule_error).to be_present+ expect(publication).not_to be_published+ expect(competitor.reload).to be_publicly_visible+ end++ it "recovers overdue schedules and rejects invalid scheduling times" do+ freeze_time+ publication = Blog::Publication.for_topic(topic)+ revision = publication.submit!(admin)+ publication.approve!(admin, revision.id)+ ["invalid", 1.minute.ago.iso8601, 2.years.from_now.iso8601].each do |time|+ expect { publication.schedule!(admin, revision_id: revision.id, at: time) }.to raise_error(+ Discourse::InvalidParameters,+ )+ end+ publication.schedule!(admin, revision_id: revision.id, at: 2.hours.from_now.iso8601)+ freeze_time 3.hours.from_now+ Jobs::RecoverBlogSchedules.new.execute+ expect_job_enqueued(+ job: :publish_blog_revision,+ args: {+ publication_id: publication.id,+ token: publication.schedule_token,+ },+ )+ end++ it "lets a non-staff publisher self-approve and publish within native category permissions" do+ SiteSetting.blog_publisher_groups = writers.id.to_s+ sign_in(writer)+ post "/blog-editor/publications/#{topic.id}/submit.json"+ expect(response.status).to eq(200)+ revision_id = response.parsed_body.dig("submitted_revision", "id")+ post "/blog-editor/publications/#{topic.id}/approve.json", params: { revision_id: revision_id }+ expect(response.status).to eq(200)+ post "/blog-editor/publications/#{topic.id}/publish.json", params: { revision_id: revision_id }+ expect(response.status).to eq(200)+ publication = Blog::Publication.find_by!(topic: topic)+ expect(publication).to be_publicly_visible+ discussion_id = publication.discussion_topic_id+ first_post.revise(+ writer,+ raw: "A revised article released by a non-staff publisher after approval.",+ )+ publication.publish!(writer)+ expect(publication.discussion_topic_id).to eq(discussion_id)+ expect(publication.discussion_topic.first_post.reload.raw).to eq(first_post.reload.raw)+ expect(writer.reload).not_to be_staff+ end++ it "preserves the publication date when correcting an article from a still-open draft form" do+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)+ original_date = publication.published_at+ discussion_id = publication.discussion_topic_id+ first_post.revise(+ writer,+ raw: "The corrected article text is ready for another approved release.",+ )+ sign_in(admin)+ put "/blog-editor/publications/#{topic.id}.json",+ params: {+ publication: {+ published_at: nil,+ },+ },+ as: :json+ expect(response.status).to eq(200)+ expect(response.parsed_body["published_revision_id"]).to eq(publication.published_revision_id)+ post "/blog-editor/publications/#{topic.id}/submit.json"+ expect(response.status).to eq(200)+ revision_id = response.parsed_body.dig("submitted_revision", "id")+ post "/blog-editor/publications/#{topic.id}/approve.json", params: { revision_id: revision_id }+ expect(response.status).to eq(200)+ post "/blog-editor/publications/#{topic.id}/publish.json", params: { revision_id: revision_id }+ expect(response.status).to eq(200)+ expect(response.parsed_body["published_revision_id"]).to eq(revision_id)+ expect(response.parsed_body["live"]).to eq(true)+ expect(publication.reload.published_at).to eq_time(original_date)+ expect(publication.discussion_topic_id).to eq(discussion_id)+ expect(publication.discussion_topic.first_post.raw).to eq(first_post.reload.raw)+ end++ it "distinguishes a published article from its pending private correction in the editor" do+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)+ original_title = topic.title+ sign_in(admin)+ get "/blog-editor/publications/#{topic.id}.json"+ expect(response.parsed_body["draft_correction"]).to eq(false)+ first_post.revise(writer, raw: "A private correction that has not been published yet.")+ topic.update!(title: "A private correction title for review")+ publication.save_metadata!(admin, excerpt: "A private correction introduction")+ get "/blog-editor.json"+ entry = response.parsed_body["topics"].find { |item| item["id"] == topic.id }+ expect(entry["live"]).to eq(true)+ expect(entry["draft_correction"]).to eq(true)+ expect(entry["public_title"]).to eq(original_title)+ expect(entry["source_url"]).to eq(topic.url)+ expect(entry["discussion_url"]).to eq(publication.discussion_topic.url)+ publication.publish!(admin)+ get "/blog-editor/publications/#{topic.id}.json"+ expect(response.parsed_body["draft_correction"]).to eq(false)+ expect(response.parsed_body["public_title"]).to eq(topic.title)+ end+enddiff --git a/plugins/blog/spec/requests/publication_panel_spec.rb b/plugins/blog/spec/requests/publication_panel_spec.rbnew file mode 100644index 00000000000..df348b39cd9--- /dev/null+++ b/plugins/blog/spec/requests/publication_panel_spec.rb@@ -0,0 +1,176 @@+# frozen_string_literal: true++RSpec.describe "Blog publication panel", type: :request do+ fab!(:admin)+ fab!(:user)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) do+ Fabricate(:post, topic: topic, user: admin, raw: "An article ready to publish.")+ end++ before do+ enable_blog!(category: category, drafts: drafts)+ SiteSetting.editing_grace_period = 0+ end++ it "exposes the editorial state of a draft topic to editors" do+ sign_in(admin)+ get "/t/#{topic.id}.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["blog_publication"]).to include(+ "id" => topic.id,+ "role" => "draft",+ "status" => "draft",+ "can_publish" => true,+ "changes" => [],+ "edits_since_publish" => 0,+ "path" => "/#{topic.slug}",+ )++ other = Fabricate(:topic, user: admin)+ Fabricate(:post, topic: other, user: admin)+ get "/t/#{other.id}.json"+ expect(response.parsed_body).not_to have_key("blog_publication")+ end++ it "publishes the current draft in one step and then reports drift from the live revision" do+ sign_in(admin)+ post "/blog-editor/publications/#{topic.id}/publish.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body).to include("status" => "live", "published" => true)++ publication = Blog::Publication.find_by!(topic: topic)+ discussion = publication.discussion_topic+ get "/t/#{discussion.id}.json"+ expect(response.parsed_body["blog_publication"]).to include(+ "role" => "discussion",+ "status" => "live",+ "source_url" => topic.url,+ )++ first_post.revise(admin, raw: "A corrected article body ready for another release.")+ topic.update!(title: "A corrected title for the article")+ get "/t/#{topic.id}.json"+ entry = response.parsed_body["blog_publication"]+ expect(entry).to include("role" => "draft", "status" => "changes_pending")+ expect(entry["changes"]).to contain_exactly("title", "body")+ expect(entry["edits_since_publish"]).to eq(1)++ get "/blog-editor/publications/#{topic.id}/changes.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["diff_html"]).to include("<ins>corrected </ins>", "<del>An </del>")+ expect(response.parsed_body["title_diff_html"]).to include("<ins>corrected </ins>")+ end++ it "surfaces private review feedback on the working copy" do+ sign_in(admin)+ get "/t/#{topic.id}.json"+ expect(response.parsed_body["blog_publication"]).to include(+ "review_feedback_count" => 0,+ "active_review_links" => 0,+ )++ older = Blog::Review.issue!(topic: topic, user: admin, label: "Round one")+ newer = Blog::Review.issue!(topic: topic, user: admin)+ older.submit_feedback!(name: "Ada", message: "Tighten the introduction.")+ newer.submit_feedback!(message: "Loving it but the colours hurt.")+ older.revoke!(admin)++ get "/t/#{topic.id}.json"+ expect(response.parsed_body["blog_publication"]).to include(+ "review_feedback_count" => 2,+ "active_review_links" => 1,+ )++ get "/blog-editor/publications/#{topic.id}/feedback.json"+ expect(response.status).to eq(200)+ feedback = response.parsed_body["feedback"]+ expect(feedback.map { |entry| entry["message"] }).to eq(+ ["Loving it but the colours hurt.", "Tighten the introduction."],+ )+ expect(feedback.last).to include("name" => "Ada")+ expect(feedback.last["review"]).to include("label" => "Round one", "post_version" => 1)+ expect(feedback.last["review"]["revoked_at"]).to be_present+ expect(response.parsed_body["more"]).to be(false)++ sign_in(user)+ get "/blog-editor/publications/#{topic.id}/feedback.json"+ expect(response.status).to eq(403)+ end++ it "keeps editorial state and diffs away from readers and unpublished topics" do+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)+ discussion = publication.discussion_topic++ get "/t/#{discussion.id}.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body).not_to have_key("blog_publication")++ sign_in(user)+ get "/t/#{discussion.id}.json"+ expect(response.parsed_body).not_to have_key("blog_publication")+ get "/blog-editor/publications/#{topic.id}/changes.json"+ expect(response.status).to eq(403)++ sign_in(admin)+ other = Fabricate(:topic, category: drafts, user: admin)+ Fabricate(:post, topic: other, user: admin)+ get "/blog-editor/publications/#{other.id}/changes.json"+ expect(response.status).to eq(404)+ end++ it "treats a Blog-category topic without a publication as an unpublished discussion" do+ sign_in(admin)+ public_topic = Fabricate(:topic, category: category, user: admin)+ Fabricate(:post, topic: public_topic, user: admin)++ get "/t/#{public_topic.id}.json"+ expect(response.parsed_body["blog_publication"]).to include(+ "role" => "discussion",+ "status" => "draft",+ "live" => false,+ "source_url" => nil,+ )+ end++ it "reports withdrawn articles and ignores unchanged re-submissions" do+ sign_in(admin)+ publication = Blog::Publication.for_topic(topic)+ publication.publish!(admin)++ publication.submit!(admin)+ get "/t/#{topic.id}.json"+ expect(response.parsed_body["blog_publication"]).to include("status" => "live", "changes" => [])++ publication.unpublish!(admin)+ get "/t/#{topic.id}.json"+ expect(response.parsed_body["blog_publication"]).to include(+ "status" => "unpublished",+ "published" => false,+ )+ end++ it "reports diffs that are too large instead of failing" do+ sign_in(admin)+ Blog::Publication.for_topic(topic).publish!(admin)+ first_post.revise(admin, raw: "A corrected article body ready for another release.")+ DiscourseDiff+ .any_instance+ .stubs(:inline_html)+ .raises(+ ONPDiff::DiffLimitExceeded.new(+ comparisons_used: 2,+ comparison_budget: 1,+ left_size: 1,+ right_size: 1,+ ),+ )++ get "/blog-editor/publications/#{topic.id}/changes.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body).to include("diff_error" => true, "diff_html" => nil)+ end+enddiff --git a/plugins/blog/spec/requests/reviews_spec.rb b/plugins/blog/spec/requests/reviews_spec.rbnew file mode 100644index 00000000000..a03b041c07e--- /dev/null+++ b/plugins/blog/spec/requests/reviews_spec.rb@@ -0,0 +1,377 @@+# frozen_string_literal: true++RSpec.describe "External draft review", type: :request do+ fab!(:admin)+ fab!(:user)+ fab!(:category)+ fab!(:drafts) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:topic) { Fabricate(:topic, category: drafts, user: admin) }+ fab!(:first_post) do+ Fabricate(+ :post,+ topic: topic,+ user: admin,+ raw: "A private article for external editorial review.",+ )+ end++ before { enable_blog!(category: category, drafts: drafts) }++ def issue_review+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/blog-editor/publications/#{topic.id}/reviews.json",+ params: {+ label: "Editorial round",+ }+ expect(response.status).to eq(201)+ review = response.parsed_body["review"]+ [review, Rack::Utils.parse_query(URI(review["url"]).query)["review_token"]]+ end++ it "rejects account-free reviews when anonymous upload downloads are disabled" do+ review, token = issue_review+ SiteSetting.prevent_anons_from_downloading_files = true++ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)++ post "https://test.localhost/blog-editor/publications/#{topic.id}/reviews.json"+ expect(response.status).to eq(400)+ expect(Blog::Review.where(topic: topic).pluck(:id)).to eq([review["id"]])+ end++ it "requires an authorized editor and keeps issued links readable by editors" do+ post "/blog-editor/publications/#{topic.id}/reviews.json"+ expect(response.status).to eq(403)+ sign_in(user)+ post "/blog-editor/publications/#{topic.id}/reviews.json"+ expect(response.status).to eq(403)+ review, token = issue_review+ stored = Blog::Review.find(review["id"])+ expect(stored.token).to eq(token)+ expect(stored.expires_at).to be_within(2.seconds).of(7.days.from_now)++ # The link stays retrievable, so a lost link does not force a new one.+ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews.json"+ expect(response.parsed_body["reviews"].first["url"]).to eq(review["url"])+ sign_in(user)+ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews.json"+ expect(response.status).to eq(403)+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ expect(topic.reload.category_id).to eq(drafts.id)+ expect(Blog::Publication.where(topic: topic, published: true)).not_to exist+ expect(UserHistory.where(custom_type: "blog_review_create", acting_user_id: admin.id)).to exist+ end++ it "shares a sanitized frozen revision without staff replies or custom code" do+ private_reply =+ Fabricate(+ :post,+ topic: topic,+ user: admin,+ raw: "This internal editorial conversation must not be shared.",+ )+ review, token = issue_review+ snapshot = Blog::Review.find(review["id"]).cooked+ first_post.revise(+ admin,+ raw: "New unpublished changes should not reach the reviewer automatically.",+ )+ theme =+ Blog::BlogTheme.save(+ {+ "name" => "Spec design",+ "accent_color" => "d64b2a",+ "paper_color" => "f5f0e6",+ "ink_color" => "19382d",+ "css" => "",+ "javascript" => "window.privateBlogScript = true;",+ },+ user: admin,+ )+ Blog::BlogTheme.activate(theme["id"], revision: 1, user: admin)++ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(200)+ expect(response.parsed_body["cooked"]).to eq(snapshot)+ expect(response.body).not_to include(private_reply.raw, first_post.reload.raw)+ expect(response.parsed_body.keys).to contain_exactly(+ "title",+ "cooked",+ "post_version",+ "created_at",+ "expires_at",+ )+ expect(response.headers["Cache-Control"]).to include("no-store")+ expect(response.headers["X-Robots-Tag"]).to include("noindex")+ expect(response.headers["Referrer-Policy"]).to eq("no-referrer")+ get "https://blog.example.com/blog/review", params: { review_token: token }+ expect(response.status).to eq(200)+ expect(response.body).not_to include("blog-custom.js", "data-theme-id=", private_reply.raw)+ expect(response.body).to include("no_themes")+ # Review links are blog-origin capabilities; the discussion host keeps core's own /review route.+ get "https://test.localhost/review", params: { review_token: token }+ expect(response.body).not_to include(snapshot)+ expect(Rails.application.routes.recognize_path("/review", method: :get)).to eq(+ controller: "reviewables",+ action: "index",+ )+ end++ it "keeps anonymous feedback private even after publication" do+ review, token = issue_review+ message = "Please reconsider the conclusion before publication."+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ name: "Reviewer",+ email: "[email protected]",+ message: message,+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ }+ expect(response.status).to eq(204)+ expect(topic.posts.count).to eq(1)+ expect(Blog::ReviewFeedback.find_by!(review_id: review["id"]).message).to eq(message)++ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews/#{review["id"]}/feedback.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["feedback"].first["message"]).to eq(message)+ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews.json"+ expect(response.parsed_body["reviews"].first["feedback_count"]).to eq(1)+ Blog::Publication.for_topic(topic).publish!(admin)+ expect(Blog::Review.find(review["id"]).revoked_at).to be_present+ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)+ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews/#{review["id"]}/feedback.json"+ expect(response.parsed_body["feedback"].first["message"]).to eq(message)+ expect(topic.posts.pluck(:raw)).not_to include(message)+ end++ it "revokes links and rejects forged tokens and cross-origin feedback" do+ review, token = issue_review+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Unexpected feedback",+ },+ },+ headers: {+ "Origin" => "https://elsewhere.example",+ }+ expect(response.status).to eq(403)+ get "https://blog.example.com/blog/review.json", params: { review_token: "x" * 43 }+ expect(response.status).to eq(404)+ delete "https://test.localhost/blog-editor/publications/#{topic.id}/reviews/#{review["id"]}.json"+ expect(response.status).to eq(204)+ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Late feedback",+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ }+ expect(response.status).to eq(404)+ expect(Blog::ReviewFeedback.count).to eq(0)+ end++ it "rejects expired links, inaccessible articles, and revoked creator access" do+ review, token = issue_review+ Blog::Review.find(review["id"]).update!(expires_at: 1.minute.ago)+ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)+ _, token = issue_review+ first_post.update!(hidden: true)+ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)+ first_post.update!(hidden: false)+ _, token = issue_review+ admin.update!(admin: false)+ admin.reload.update!(moderator: false)+ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)+ end++ it "validates feedback and scopes management endpoints to their topic" do+ review, token = issue_review+ ["", "x" * 10_001].each do |message|+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: message,+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ }+ expect(response.status).to eq(422)+ end+ other = Fabricate(:topic, category: drafts, user: admin)+ Fabricate(:post, topic: other, user: admin)+ delete "https://test.localhost/blog-editor/publications/#{other.id}/reviews/#{review["id"]}.json"+ expect(response.status).to eq(404)+ get "https://test.localhost/session/#{user.encoded_username}/become"+ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews/#{review["id"]}/feedback.json"+ expect(response.status).to eq(403)+ expect(Blog::ReviewFeedback.count).to eq(0)+ end++ it "requires a real CSRF token for anonymous feedback" do+ _, token = issue_review+ previous = Blog::ReviewReaderController.allow_forgery_protection+ Blog::ReviewReaderController.allow_forgery_protection = true+ begin+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Missing CSRF",+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ }+ expect(response.status).to eq(403)+ get "https://blog.example.com/session/csrf.json"+ expect(response.status).to eq(200)+ csrf = response.parsed_body["csrf"]+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Legitimate anonymous feedback",+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ "X-CSRF-Token" => csrf,+ }+ expect(response.status).to eq(204)+ expect(Blog::ReviewFeedback.count).to eq(1)+ ensure+ Blog::ReviewReaderController.allow_forgery_protection = previous+ end+ end++ it "excludes unrelated plugins, themes, and analytics from the review boot" do+ # Backend CI doesn't build plugin JS, so give every plugin a bundle to filter.+ allow(Plugin::JsManager).to receive(:read_manifest) do |name|+ { "main" => { "fileName" => "#{name}.js", "imports" => [], "externalPluginImports" => [] } }+ end+ _, token = issue_review+ get "https://blog.example.com/blog/review", params: { review_token: token }+ expect(response.status).to eq(200)+ document = Nokogiri.HTML5(response.body)+ plugin_names =+ document.css("[data-plugin-name]").map { |element| element["data-plugin-name"] }.uniq+ expect(plugin_names).to eq(["blog"])+ expect(document.css("[data-theme-id], iframe, script[data-blog-custom-script]")).to be_empty+ expect(document.at_css("#data-discourse-setup")["data-service-worker-url"]).to be_nil+ expect(response.body).not_to include("googletagmanager.com", "google-analytics.com")+ end++ it "revokes grants when a privileged operation moves a topic out of drafts" do+ review, token = issue_review+ topic.category_id = category.id+ topic.save!(validate: false)+ expect(Blog::Review.find(review["id"]).revoked_at).to be_present+ topic.update!(category_id: drafts.id)+ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)+ end++ it "rate-limits anonymous feedback without creating extra entries" do+ _, token = issue_review+ RateLimiter.enable+ 30.times do+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Feedback",+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ }+ expect(response.status).to eq(204)+ end+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Over the limit",+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ }+ expect(response.status).to eq(429)+ expect(Blog::ReviewFeedback.count).to eq(30)+ ensure+ RateLimiter.disable+ end++ it "bounds stored feedback and paginates the private editor view" do+ review, token = issue_review+ now = Time.current+ Blog::ReviewFeedback.insert_all!(+ 200.times.map do |index|+ {+ review_id: review["id"],+ name: "",+ email: "",+ message: "Response #{index}",+ created_at: now,+ updated_at: now,+ }+ end,+ )+ post "https://blog.example.com/blog/review/feedback.json",+ params: {+ review_token: token,+ feedback: {+ message: "Too many responses",+ },+ },+ headers: {+ "Origin" => "https://blog.example.com",+ }+ expect(response.status).to eq(400)+ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews/#{review["id"]}/feedback.json"+ expect(response.parsed_body["feedback"].length).to eq(30)+ expect(response.parsed_body["more"]).to eq(true)+ first_ids = response.parsed_body["feedback"].map { |entry| entry["id"] }+ get "https://test.localhost/blog-editor/publications/#{topic.id}/reviews/#{review["id"]}/feedback.json",+ params: {+ page: 1,+ }+ expect(response.parsed_body["feedback"].map { |entry| entry["id"] } & first_ids).to be_empty+ end++ it "sanitizes stored markup and deletes snapshots and feedback with a hard-deleted topic" do+ first_post.update_columns(+ cooked:+ '<p>Review text</p><script>alert(1)</script><iframe src="https://example.com"></iframe>',+ )+ review, token = issue_review+ stored = Blog::Review.find(review["id"])+ expect(Nokogiri::HTML5.fragment(stored.cooked).css("script, iframe")).to be_empty+ stored.feedback.create!(message: "A private response", name: nil, email: nil)+ topic.destroy!+ expect(Blog::Review.where(id: review["id"])).not_to exist+ expect(Blog::ReviewFeedback.where(review_id: review["id"])).not_to exist+ get "https://blog.example.com/blog/review.json", params: { review_token: token }+ expect(response.status).to eq(404)+ end+enddiff --git a/plugins/blog/spec/requests/syntax_highlighter_spec.rb b/plugins/blog/spec/requests/syntax_highlighter_spec.rbnew file mode 100644index 00000000000..1be9e4834cb--- /dev/null+++ b/plugins/blog/spec/requests/syntax_highlighter_spec.rb@@ -0,0 +1,55 @@+# frozen_string_literal: true++RSpec.describe "Blog syntax highlighter", type: :request do+ before do+ enable_blog!+ Blog::SyntaxHighlighter.instance_variable_set(:@source, nil)+ end++ around do |example|+ stub_const(VendoredAssets, :DIRECTORY, "tmp/missing-blog-runtime-assets") { example.run }+ end++ it "serves the minified module with immutable caching and CORS for previews" do+ get "https://blog.example.com#{Blog::SyntaxHighlighter.path}",+ headers: {+ "Cookie" => "__profilin=p%3Dt",+ }++ expect(response.status).to eq(200)+ expect(response.media_type).to eq("application/javascript")+ packaged_source = File.read(File.expand_path("../../vendor/highlightjs/core.min.js", __dir__))+ expect(response.body).to eq(packaged_source)+ expect(response.headers["Cache-Control"]).to include("immutable", "public")+ expect(response.headers["Cache-Control"]).not_to include("no-store", "private", "no-cache")+ expect(response.headers["Access-Control-Allow-Origin"]).to eq("*")+ expect(response.headers["Set-Cookie"]).to be_nil+ end++ it "rejects an unknown asset version" do+ get "https://blog.example.com/blog-highlight/unknown.js"++ expect(response.status).to eq(404)+ expect(response.headers["Cache-Control"]).to include("no-store")+ end++ it "serves the immutable module under the blog path without setting cookies" do+ SiteSetting.blog_url = ""++ get "/blog#{Blog::SyntaxHighlighter.path}", headers: { "Cookie" => "__profilin=p%3Dt" }++ expect(response.status).to eq(200)+ expect(response.headers["Cache-Control"]).to include("immutable", "public")+ expect(response.headers["Cache-Control"]).not_to include("no-store", "private", "no-cache")+ expect(response.headers["Set-Cookie"]).to be_nil+ end++ it "keeps the asset unavailable when public blogging is disabled" do+ SiteSetting.login_required = true++ get "https://blog.example.com#{Blog::SyntaxHighlighter.path}"++ expect(response.status).not_to eq(200)+ expect(response.body).not_to eq(Blog::SyntaxHighlighter.source)+ end+enddiff --git a/plugins/blog/spec/requests/theme_authoring_spec.rb b/plugins/blog/spec/requests/theme_authoring_spec.rbnew file mode 100644index 00000000000..73bea6d5933--- /dev/null+++ b/plugins/blog/spec/requests/theme_authoring_spec.rb@@ -0,0 +1,145 @@+# frozen_string_literal: true++RSpec.describe "Blog theme authoring", type: :request do+ fab!(:admin)+ fab!(:user)+ fab!(:category)+ fab!(:topic) { Fabricate(:topic, category: category) }+ fab!(:first_post) { Fabricate(:post, topic: topic) }+ fab!(:publication) do+ Blog::Publication.create!(+ topic: topic,+ discussion_topic: topic,+ path: "/sample",+ published: true,+ published_at: 1.day.ago,+ )+ end+ fab!(:publication_path) { Blog::Path.create!(publication: publication, path: "/sample") }+ fab!(:private_category) { Fabricate(:private_category, group: Group[:staff]) }+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }+ fab!(:private_post) do+ Fabricate(+ :post,+ topic: private_topic,+ raw: "Confidential editorial material that must never enter template previews.",+ )+ end++ let(:attributes) do+ Blog::BlogTheme.defaults.merge(+ "name" => "Unsaved working design",+ "template_index" => "<h1 data-working>{{ site.title }}</h1>",+ )+ end++ before do+ enable_blog!(category: category)+ https!+ SiteSetting.force_https = true+ end++ it "requires administrators and serves only public samples" do+ get "https://test.localhost/admin/plugins/blog/theme-authoring.json"+ expect(response.status).to eq(403)+ get "https://test.localhost/session/#{user.encoded_username}/become"+ get "https://test.localhost/admin/plugins/blog/theme-authoring.json"+ expect(response.status).to eq(403)+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ get "https://test.localhost/admin/plugins/blog/theme-authoring.json"+ expect(response.status).to eq(200)+ data = response.parsed_body+ expect(data["templates"]["template_layout"]).to include("{{ content_html }}")+ expect(data["articles"].map { |article| article["id"] }).to eq([publication.id])+ expect(data.dig("variables", "article", "title")).to eq(publication.article.title)+ expect(response.body).not_to include(private_post.raw, private_topic.title)+ get "https://blog.example.com/admin/plugins/blog/theme-authoring.json"+ expect(response.status).to eq(404)+ end++ it "previews unsaved changes without saving or activating and expires the capability" do+ freeze_time+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/theme-authoring/preview.json",+ params: {+ theme: attributes,+ page: "index",+ }+ expect(response.status).to eq(201)+ url = response.parsed_body["url"]+ expect(Blog::BlogTheme.all).to be_empty+ expect(Blog::BlogTheme.active["name"]).not_to eq(attributes["name"])+ get url+ expect(response.status).to eq(200)+ expect(response.body).to include("data-working")+ expect(response.headers["Cache-Control"]).to include("no-store")+ expect(response.headers["Content-Security-Policy"]).to include(+ "frame-ancestors https://test.localhost",+ )+ expect(response.headers["X-Frame-Options"]).to be_nil+ get "https://blog.example.com/"+ expect(response.body).not_to include("data-working")+ freeze_time 16.minutes.from_now+ get url+ expect(response.status).to eq(404)+ end++ it "shows syntax errors with template and line instead of silently substituting live output" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/theme-authoring/preview.json",+ params: {+ theme: attributes.merge("template_index" => "<h1>Broken</h1>\n{% unknown_tag %}"),+ page: "index",+ }+ expect(response.status).to eq(201)+ get response.parsed_body["url"]+ expect(response.body).to include('data-template-diagnostic="error"', "index, line 2")+ expect(Blog::BlogTheme.all).to be_empty+ end++ it "warns about undefined variables while rendering the rest of the working page" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/theme-authoring/preview.json",+ params: {+ theme:+ attributes.merge(+ "template_index" => "<h1 data-working>{{ site.title }}</h1>\n{{ missing_value }}",+ ),+ page: "index",+ }+ expect(response.status).to eq(201)+ get response.parsed_body["url"]+ expect(response.body).to include(+ 'data-template-diagnostic="warning"',+ "missing_value",+ "data-working",+ )+ end++ it "selects public article previews and keeps only three working snapshots per editor" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ urls =+ 4.times.map do+ post "https://test.localhost/admin/plugins/blog/theme-authoring/preview.json",+ params: {+ theme: attributes,+ page: "article",+ article_id: publication.id,+ }+ expect(response.status).to eq(201)+ response.parsed_body["url"]+ end+ get urls.first+ expect(response.status).to eq(404)+ get urls.last+ expect(response.status).to eq(200)+ expect(response.body).to include(first_post.cooked)+ post "https://test.localhost/admin/plugins/blog/theme-authoring/preview.json",+ params: {+ theme: attributes,+ page: "article",+ article_id: -1,+ }+ expect(response.status).to eq(404)+ end+enddiff --git a/plugins/blog/spec/requests/themes_spec.rb b/plugins/blog/spec/requests/themes_spec.rbnew file mode 100644index 00000000000..65b8e33a6a1--- /dev/null+++ b/plugins/blog/spec/requests/themes_spec.rb@@ -0,0 +1,528 @@+# frozen_string_literal: true++RSpec.describe "Blog themes", type: :request do+ fab!(:admin)+ fab!(:moderator)+ fab!(:category)+ fab!(:topic) { Fabricate(:topic, category: category) }+ fab!(:first_post) { Fabricate(:post, topic: topic) }++ let(:attributes) do+ {+ name: "Quiet draft",+ accent_color: "112233",+ paper_color: "fafafa",+ ink_color: "222222",+ css: ".blog { letter-spacing: 0.1px; }",+ javascript: 'document.body.dataset.themePreview = "yes";',+ }+ end++ before do+ enable_blog!(category: category)+ https!+ end++ it "previews custom templates, freezes activation, and retains the safe-mode escape hatch" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ custom =+ attributes.merge(+ template_index: "<h1 data-custom-liquid>{{ site.title }}</h1>",+ template_layout: "<div data-custom-layout>{{ content_html }}</div>",+ )+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: custom }+ expect(response.status).to eq(201)+ draft = response.parsed_body+ get "https://blog.example.com/"+ expect(response.body).not_to include("data-custom-liquid")+ get draft["preview_url"]+ expect(response.body).to include("data-custom-liquid", "data-custom-layout")+ expect(response.headers["Cache-Control"]).to include("no-store")+ post "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}/activate.json",+ params: {+ revision: 1,+ }+ expect(response.status).to eq(200)+ put "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ theme: custom.merge(template_index: "Changed draft only"),+ revision: 1,+ }+ expect(response.status).to eq(200)+ get "https://blog.example.com/"+ expect(response.body).to include("data-custom-liquid")+ expect(response.body).not_to include("Changed draft only")+ get "https://blog.example.com/", params: { blog_safe_mode: 1 }+ expect(response.body).not_to include("data-custom-liquid", "data-custom-layout")+ expect(response.body).to include('class="blog__header"')+ end++ it "keeps authenticated editorial previews and feeds independent of custom templates" do+ drafts = Fabricate(:private_category, group: Group[:staff])+ SiteSetting.blog_drafts_category = drafts.id+ private_topic = Fabricate(:topic, category: drafts, user: admin)+ private_post = Fabricate(:post, topic: private_topic, user: admin)+ theme =+ Blog::BlogTheme.save(+ attributes.stringify_keys.merge(+ "template_article" => "CUSTOM ARTICLE",+ "template_layout" => "CUSTOM LAYOUT",+ ),+ user: admin,+ )+ Blog::BlogTheme.activate(theme["id"], revision: 1, user: admin)+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ get "https://test.localhost/blog-editor/preview/#{private_topic.id}"+ expect(response.status).to eq(200)+ expect(response.body).to include(private_post.cooked)+ expect(response.body).not_to include("CUSTOM ARTICLE", "CUSTOM LAYOUT")+ get "https://blog.example.com/feed.xml"+ expect(response.status).to eq(200)+ expect(Nokogiri.XML(response.body).at_xpath("/rss/channel")).to be_present+ end++ it "exposes only public frozen articles to a custom listing template" do+ publication =+ Blog::Publication.create!(+ topic: topic,+ discussion_topic: topic,+ published: true,+ published_at: 1.day.ago,+ path: "/public-story",+ )+ private_category = Fabricate(:private_category, group: Group[:staff])+ private_topic =+ Fabricate(+ :topic,+ category: private_category,+ user: admin,+ title: "Private draft title not for readers",+ )+ Fabricate(:post, topic: private_topic, user: admin)+ theme =+ Blog::BlogTheme.save(+ attributes.stringify_keys.merge(+ "template_index" =>+ "{% for article in articles %}<h2>{{ article.title }}</h2>{{ article.raw }}{{ article.source_topic_id }}{% endfor %}",+ ),+ user: admin,+ )+ Blog::BlogTheme.activate(theme["id"], revision: 1, user: admin)+ get "https://blog.example.com/"+ expect(response.status).to eq(200)+ expect(response.body).to include(publication.published_revision.title)+ expect(response.body).not_to include(private_topic.title, first_post.raw)+ end++ describe "Discourse Blog reference theme" do+ let(:reference_theme) do+ root = Rails.root.join("plugins/blog/branding/discourse-blog")+ values =+ JSON.parse(File.read(root.join("blog-theme.json"))).merge(+ "css" => File.read(root.join("blog.css")),+ "javascript" => "",+ )+ Blog::TemplateRenderer::PAGES.each do |page|+ values["template_#{page}"] = File.read(root.join("templates/#{page}.liquid"))+ end+ Blog::BlogTheme.save(values, user: admin)+ end++ it "previews each page with the local identity and preserves the discussion and live theme" do+ publication =+ Blog::Publication.create!(+ topic: topic,+ discussion_topic: topic,+ published: true,+ published_at: 1.day.ago,+ path: "/reference-story",+ )+ Blog::Path.create!(publication: publication, path: publication.path)+ active = Blog::BlogTheme.active+ token = Blog::BlogTheme.preview_token(reference_theme)++ {+ "/" => 200,+ "/archive" => 200,+ publication.path => 200,+ "/about" => 200,+ "/missing-reference-page" => 404,+ }.each do |path, status|+ get "https://blog.example.com#{path}", params: { blog_theme_preview: token }+ expect(response.status).to eq(status)+ document = Nokogiri.HTML5(response.body)+ expect(document.css(".discourse-journal #main").size).to eq(1)+ expect(document.at_css(".discourse-journal__brand").text).to include(SiteSetting.blog_title)+ expect(document.css("[data-template-diagnostic]")).to be_empty+ if path == publication.path+ expect(document.css("#discussion").size).to eq(1)+ expect(document.at_css(".blog-article__body").inner_html).to include(first_post.cooked)+ end+ end+ expect(Blog::BlogTheme.active).to eq(active)+ end++ it "renders an empty listing and carries the preview through archive searches" do+ token = Blog::BlogTheme.preview_token(reference_theme)+ get "https://blog.example.com/archive",+ params: {+ blog_theme_preview: token,+ q: "No matching article",+ }++ expect(response.status).to eq(200)+ document = Nokogiri.HTML5(response.body)+ expect(document.at_css(".discourse-journal__empty").text).to include(+ I18n.t("blog.empty_title"),+ )+ expect(document.at_css('input[name="blog_theme_preview"]')["value"]).to eq(token)+ expect(document.at_css('input[name="q"]')["value"]).to eq("No matching article")+ expect(document.css("[data-template-diagnostic]")).to be_empty+ end+ end++ describe "management" do+ it "requires administrators and rejects the public blog origin" do+ get "https://test.localhost/admin/plugins/blog/themes.json"+ expect(response.status).to eq(403)+ get "https://test.localhost/session/#{moderator.encoded_username}/become"+ get "https://test.localhost/admin/plugins/blog/themes.json"+ expect(response.status).to eq(403)+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: attributes }+ expect(response.status).to eq(403)+ expect(Blog::BlogTheme.all).to be_empty+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ get "https://test.localhost/admin/plugins/blog/themes.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["themes"]).to be_empty+ get "https://blog.example.com/admin/plugins/blog/themes.json"+ expect(response.status).to eq(404)+ end++ it "serves focused theme data and supports direct loading of all admin pages" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: attributes }+ draft = response.parsed_body+ get "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("theme", "id")).to eq(draft["id"])+ expect(response.parsed_body.dig("theme", "css")).to eq(attributes[:css])+ expect(response.parsed_body.dig("theme", "preview_url")).to be_present+ %W[+ themes+ themes/new+ themes/import/new+ themes/#{draft["id"]}/edit+ identity+ appearance+ ].each do |path|+ get "https://test.localhost/admin/plugins/blog/#{path}"+ expect(response.status).to eq(200)+ end+ get "https://test.localhost/admin/plugins/blog/themes/missing.json"+ expect(response.status).to eq(404)+ get "https://test.localhost/session/#{moderator.encoded_username}/become"+ get "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json"+ expect(response.status).to eq(403)+ end++ it "saves multiple drafts without changing readers, then explicitly activates a snapshot" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: attributes }+ expect(response.status).to eq(201)+ draft = response.parsed_body+ expect(draft["preview_url"]).to start_with("https://blog.example.com/?blog_theme_preview=")+ get "https://blog.example.com/blog-theme.css"+ expect(response.body).not_to include(attributes[:css])+ get "https://blog.example.com/"+ expect(Nokogiri.HTML5(response.body).at_css('link[href*="blog-theme.css"]')).to be_present++ post "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}/activate.json",+ params: {+ revision: draft["revision"],+ }+ expect(response.status).to eq(200)+ get "https://blog.example.com/"+ html = Nokogiri.HTML5(response.body)+ css_url = html.at_css('link[href*="blog-theme.css"]')["href"]+ js_url = html.at_css("script[data-blog-custom-script]")["src"]++ changed =+ attributes.merge(css: ".blog { font-size: 42px; }", javascript: "window.changed = true;")+ put "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ theme: changed,+ revision: 1,+ }+ expect(response.status).to eq(200)+ expect(response.parsed_body["revision"]).to eq(2)+ get "https://blog.example.com/blog-theme.css"+ expect(response.body).to include(attributes[:css])+ expect(response.body).not_to include(changed[:css])++ post "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}/activate.json",+ params: {+ revision: 2,+ }+ get "https://blog.example.com/blog-theme.css"+ expect(response.body).to include(changed[:css])+ get css_url+ expect(response.body).to include(attributes[:css])+ get js_url+ expect(response.body).to eq(attributes[:javascript])+ expect(+ UserHistory.where(acting_user_id: admin.id, custom_type: "blog_theme_activate").count,+ ).to eq(2)++ post "https://test.localhost/admin/plugins/blog/themes.json",+ params: {+ theme: attributes.merge(name: "Another design"),+ }+ expect(response.status).to eq(201)+ get "https://test.localhost/admin/plugins/blog/themes.json"+ expect(response.parsed_body["themes"].map { |theme| theme["name"] }).to contain_exactly(+ "Quiet draft",+ "Another design",+ )+ expect(response.parsed_body["active"]["revision"]).to eq(2)+ end++ it "rejects stale changes and activation, and protects the active theme from deletion" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: attributes }+ draft = response.parsed_body+ put "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ theme: attributes.merge(name: "Updated"),+ revision: 1,+ }+ put "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ theme: attributes,+ revision: 1,+ }+ expect(response.status).to eq(400)+ post "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}/activate.json",+ params: {+ revision: 1,+ }+ expect(response.status).to eq(400)+ delete "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ revision: 1,+ }+ expect(response.status).to eq(400)+ post "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}/activate.json",+ params: {+ revision: 2,+ }+ expect(response.status).to eq(200)+ delete "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ revision: 2,+ }+ expect(response.status).to eq(400)+ expect(Blog::BlogTheme.find(draft["id"])["name"]).to eq("Updated")+ end++ it "validates bounded theme content and permits deleting unused drafts" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ [+ { name: "" },+ { accent_color: "red; }" },+ { css: "a" * 65_537 },+ { javascript: "ü" * 32_769 },+ ].each do |invalid|+ post "https://test.localhost/admin/plugins/blog/themes.json",+ params: {+ theme: attributes.merge(invalid),+ }+ expect(response.status).to eq(400)+ end+ expect(Blog::BlogTheme.all).to be_empty+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: attributes }+ draft = response.parsed_body+ delete "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ revision: 1,+ }+ expect(response.status).to eq(204)+ get draft["preview_url"]+ expect(response.status).to eq(404)+ end+ end++ describe "ZIP endpoints" do+ it "exports the saved draft and imports the download as a new inactive draft" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ theme = Blog::BlogTheme.save(attributes.stringify_keys, user: admin)++ get "https://test.localhost/admin/plugins/blog/themes/#{theme["id"]}/export"++ expect(response.status).to eq(200)+ expect(response.media_type).to eq("application/zip")+ expect(response.headers["Content-Disposition"]).to include(+ "attachment",+ "blog-theme-quiet-draft.zip",+ )+ Tempfile.create(%w[blog-theme .zip]) do |file|+ file.binmode+ file.write(response.body)+ file.flush+ post "https://test.localhost/admin/plugins/blog/themes/import.json",+ params: {+ file: Rack::Test::UploadedFile.new(file.path, "application/zip"),+ }+ end++ expect(response.status).to eq(201)+ expect(response.parsed_body["name"]).to eq(theme["name"])+ expect(response.parsed_body["id"]).not_to eq(theme["id"])+ expect(response.parsed_body["source"]).to be_nil+ expect(Blog::BlogTheme.active["id"]).to be_nil+ end++ it "restricts imports and exports to admins on the discussion host" do+ theme = Blog::BlogTheme.save(attributes.stringify_keys, user: admin)+ get "https://test.localhost/admin/plugins/blog/themes/#{theme["id"]}/export"+ expect(response.status).to eq(403)+ post "https://test.localhost/admin/plugins/blog/themes/import.json",+ params: {+ file: "theme.zip",+ }+ expect(response.status).to eq(403)++ get "https://test.localhost/session/#{moderator.encoded_username}/become"+ get "https://test.localhost/admin/plugins/blog/themes/#{theme["id"]}/export"+ expect(response.status).to eq(403)+ post "https://test.localhost/admin/plugins/blog/themes/import.json",+ params: {+ file: "theme.zip",+ }+ expect(response.status).to eq(403)++ get "https://test.localhost/session/#{admin.encoded_username}/become"+ get "https://blog.example.com/admin/plugins/blog/themes/#{theme["id"]}/export"+ expect(response.status).to eq(404)+ get "https://test.localhost/admin/plugins/blog/themes/missing/export"+ expect(response.status).to eq(404)+ post "https://test.localhost/admin/plugins/blog/themes/import.json",+ params: {+ file: "theme.zip",+ }+ expect(response.status).to eq(400)+ end+ end++ describe "Git endpoints" do+ it "imports and pulls the configured source without activating it" do+ Dir.mktmpdir do |directory|+ File.write(+ File.join(directory, "blog-theme.json"),+ attributes.except(:css, :javascript).merge(version: 1).to_json,+ )+ File.write(File.join(directory, "blog.css"), attributes[:css])+ importer = ThemeStore::DirectoryImporter.new(directory)+ importer.stubs(:version).returns("a" * 40)+ Blog::ThemeImporter::GitSource.stubs(:new).returns(importer)+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/themes/import.json",+ params: {+ repository: "https://github.com/example/theme",+ branch: "design",+ }+ expect(response.status).to eq(201)+ draft = response.parsed_body+ expect(draft.dig("source", "branch")).to eq("design")+ File.write(File.join(directory, "blog.css"), ".blog { color: blue; }")+ post "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}/pull.json",+ params: {+ revision: 1,+ }+ expect(response.status).to eq(200)+ expect(response.parsed_body["revision"]).to eq(2)+ expect(response.parsed_body["css"]).to eq(".blog { color: blue; }")+ get "https://blog.example.com/blog-theme.css"+ expect(response.body).not_to include(attributes[:css], ".blog { color: blue; }")+ expect(File.exist?(importer.temp_folder)).to eq(false)+ end+ end+ end++ describe "preview" do+ it "previews only public content and carries the capability through navigation and assets" do+ publication =+ Blog::Publication.create!(+ topic: topic,+ path: "/a-story",+ published: true,+ published_at: 1.day.ago,+ )+ publication.paths.create!(path: publication.path)+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: attributes }+ draft = response.parsed_body+ get draft["preview_url"]+ expect(response.status).to eq(200)+ expect(response.headers["Cache-Control"]).to include("no-store")+ expect(response.headers["X-Robots-Tag"]).to include("noindex")+ expect(response.headers["Referrer-Policy"]).to eq("no-referrer")+ html = Nokogiri.HTML5(response.body)+ expect(html.at_css("body")["data-blog-theme"]).to be_nil+ expect(html.at_css('link[href$="/editorial.css"]')).to be_nil+ expect(html.at_css(".blog__preview").text).to include(attributes[:name])+ expect(html.at_css('link[rel="canonical"]')).to be_nil+ expect(html.at_css(".blog-card h2 a")["href"]).to include(+ "#{publication.path}?blog_theme_preview=",+ )+ expect(html.at_css(".blog__nav a")["href"]).to include("blog_theme_preview=")+ get html.at_css('link[href*="blog-theme.css"]')["href"]+ expect(response.body).to include(attributes[:css], "#112233")+ get html.at_css("script[data-blog-custom-script]")["src"]+ expect(response.body).to eq(attributes[:javascript])+ get "https://blog.example.com/blog-custom.js"+ expect(response.body).not_to include(attributes[:javascript])+ get "https://test.localhost/blog-custom.js",+ params: {+ blog_theme_preview:+ URI.decode_www_form(URI(draft["preview_url"]).query).to_h["blog_theme_preview"],+ }+ expect(response.status).to eq(404)+ get "#{draft["preview_url"]}&blog_safe_mode=1"+ expect(Nokogiri.HTML5(response.body).at_css("script[data-blog-custom-script]")).to be_nil++ get html.at_css(".blog-card h2 a")["href"]+ expect(response.status).to eq(200)+ get html.at_css(".blog__nav a")["href"]+ expect(+ Nokogiri.HTML5(response.body).at_css('input[name="blog_theme_preview"]')["value"],+ ).to be_present++ topic.update!(category: Fabricate(:private_category, group: Group[:staff]))+ get html.at_css(".blog-card h2 a")["href"]+ expect(response.status).to eq(404)+ end++ it "rejects tampered, expired, and superseded preview links" do+ get "https://test.localhost/session/#{admin.encoded_username}/become"+ post "https://test.localhost/admin/plugins/blog/themes.json", params: { theme: attributes }+ draft = response.parsed_body+ get "#{draft["preview_url"]}tampered"+ expect(response.status).to eq(404)+ freeze_time 61.minutes.from_now+ get draft["preview_url"]+ expect(response.status).to eq(404)+ get "https://test.localhost/admin/plugins/blog/themes.json"+ url = response.parsed_body["themes"].first["preview_url"]+ get url+ expect(response.status).to eq(200)+ put "https://test.localhost/admin/plugins/blog/themes/#{draft["id"]}.json",+ params: {+ theme: attributes,+ revision: 1,+ }+ get url+ expect(response.status).to eq(404)+ end+ end+enddiff --git a/plugins/blog/spec/support/blog_spec_helpers.rb b/plugins/blog/spec/support/blog_spec_helpers.rbnew file mode 100644index 00000000000..3355afbb092--- /dev/null+++ b/plugins/blog/spec/support/blog_spec_helpers.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module BlogSpecHelpers+ BLOG_HOST = "blog.example.com"+ DISCUSSION_HOST = "test.localhost"+ BLOG_HOSTNAMES = [DISCUSSION_HOST, BLOG_HOST].freeze++ # Enables the blog, optionally wiring its categories. A custom domain stubs both+ # hostnames; without one the blog is served under /blog on the forum.+ def enable_blog!(category: nil, drafts: nil, custom_domain: true)+ SiteSetting.blog_enabled = true+ if custom_domain+ RailsMultisite::ConnectionManagement.stubs(:current_db_hostnames).returns(BLOG_HOSTNAMES)+ SiteSetting.blog_url = "https://#{BLOG_HOST}"+ end+ SiteSetting.blog_category = category.id if category+ SiteSetting.blog_drafts_category = drafts.id if drafts+ end+end++RSpec.configure { |config| config.include(BlogSpecHelpers) }diff --git a/plugins/blog/templates/about.liquid b/plugins/blog/templates/about.liquidnew file mode 100644index 00000000000..d10ac04ccbe--- /dev/null+++ b/plugins/blog/templates/about.liquid@@ -0,0 +1,5 @@+<article class="blog-article">+ <header class="blog-article__header"><p class="blog__eyebrow">{{ site.title }}</p><h1>{{ labels.about }}</h1></header>+ <div class="blog-article__body cooked">{{ site.about_html }}</div>+ <p><a href="{{ site.community_url }}">{{ labels.join_community }} ↗</a></p>+</article>diff --git a/plugins/blog/templates/article.liquid b/plugins/blog/templates/article.liquidnew file mode 100644index 00000000000..a73eae9bdf6--- /dev/null+++ b/plugins/blog/templates/article.liquid@@ -0,0 +1,17 @@+<article class="blog-article">+ <header class="blog-article__header">+ <a class="blog__eyebrow" href="{{ site.url }}">← {{ labels.all_articles }}</a>+ <h1>{{ article.title }}</h1>+ {% if article.standfirst %}<p class="blog-article__standfirst">{{ article.standfirst }}</p>{% endif %}+ <div class="blog__meta"><span>{{ article.author }}</span><span>·</span>+ {% if article.published_at %}<time datetime="{{ article.published_at }}">{{ article.date }}</time><span>·</span>{% endif %}+ <span>{{ article.reading_time }}</span>+ </div>+ {% if article.updated_label %}<p class="blog__updated">{{ article.updated_label }}</p>{% endif %}+ </header>+ <div class="blog-article__body cooked">{{ article.body_html }}</div>+ <footer class="blog-article__footer">+ <div class="blog__tags">{% for tag in article.tags %}<a href="{{ tag.url }}">{{ tag.name }}</a>{% endfor %}</div>+ <a href="{{ article.discussion_url }}">{{ labels.view_topic }} ↗</a>+ </footer>+</article>diff --git a/plugins/blog/templates/index.liquid b/plugins/blog/templates/index.liquidnew file mode 100644index 00000000000..f15a2d3510e--- /dev/null+++ b/plugins/blog/templates/index.liquid@@ -0,0 +1,35 @@+<header class="blog__intro">+ <div class="blog__intro-copy">+ <p class="blog__eyebrow">{{ page.eyebrow }}</p>+ <h1>{{ page.heading }}</h1>+ <p class="blog__description">{{ site.description }}</p>+ </div>+ <div class="blog__emblem" aria-hidden="true"><span>✳</span><span class="blog__emblem-orbit"></span></div>+</header>+{% if page.archive %}+<form class="blog__search" action="{{ site.archive_url }}" method="get" role="search">+ {% if page.preview_token %}<input type="hidden" name="blog_theme_preview" value="{{ page.preview_token }}">{% endif %}+ <label for="blog-search">{{ labels.search }}</label>+ <input id="blog-search" name="q" type="search" value="{{ page.query }}" maxlength="100" placeholder="{{ labels.search_placeholder }}">+ <button type="submit">{{ labels.search }}</button>+</form>+{% endif %}+<div class="blog__section-heading"><h2>{{ labels.latest_stories }}</h2><a href="{{ site.archive_url }}">{{ labels.explore_archive }} ↗</a></div>+<div class="blog__articles">+ {% for article in articles %}+ <article class="blog-card">+ {% if article.image_url %}<a class="blog-card__image" href="{{ article.url }}" tabindex="-1" aria-hidden="true"><img src="{{ article.image_url }}" alt="" loading="lazy"></a>+ {% else %}<a class="blog-card__art" href="{{ article.url }}" tabindex="-1" aria-hidden="true"><span class="blog-card__art-index">{{ article.index }}</span><span class="blog-card__art-mark">✳</span><span class="blog-card__art-caption">{{ site.title }}</span></a>{% endif %}+ <div class="blog-card__content">+ <div class="blog__meta"><time datetime="{{ article.published_at }}">{{ article.date }}</time><span>·</span><span>{{ article.reading_time }}</span>{% if article.featured %}<span class="blog__badge">{{ labels.featured }}</span>{% endif %}</div>+ <h2><a href="{{ article.url }}">{{ article.title }}</a></h2>+ <p class="blog-card__excerpt">{{ article.excerpt }}</p>+ <div class="blog-card__footer"><span>{{ article.author }}</span><a href="{{ article.url }}#discussion">{{ article.replies_label }} ↗</a></div>+ </div>+ </article>+ {% else %}<div class="blog__empty"><h2>{{ labels.empty_title }}</h2><p>{{ labels.empty_body }}</p></div>{% endfor %}+</div>+<nav class="blog__pagination" aria-label="{{ labels.pagination }}">+ {% if page.previous_url %}<a rel="prev" href="{{ page.previous_url }}">← {{ labels.newer }}</a>{% endif %}+ {% if page.next_url %}<a rel="next" href="{{ page.next_url }}">{{ labels.older }} →</a>{% endif %}+</nav>diff --git a/plugins/blog/templates/layout.liquid b/plugins/blog/templates/layout.liquidnew file mode 100644index 00000000000..a1048c015c3--- /dev/null+++ b/plugins/blog/templates/layout.liquid@@ -0,0 +1,14 @@+<header class="blog__header">+ <a class="blog__brand" href="{{ site.url }}">{{ site.title }}<span class="blog__brand-dot" aria-hidden="true">.</span></a>+ <nav class="blog__nav" aria-label="{{ labels.navigation }}">+ <a href="{{ site.archive_url }}">{{ labels.archive }}</a>+ <a href="{{ site.about_url }}">{{ labels.about }}</a>+ <a href="{{ site.community_url }}">{{ labels.community }} ↗</a>+ <a href="{{ site.feed_url }}">{{ labels.rss }}</a>+ </nav>+</header>+<main id="main" class="blog__main">{{ content_html }}</main>+<footer class="blog__footer">+ <span>{{ site.title }} · {{ labels.footer }}</span>+ <a href="{{ site.editor_url }}">{{ labels.editor }}</a>+</footer>diff --git a/plugins/blog/templates/not_found.liquid b/plugins/blog/templates/not_found.liquidnew file mode 100644index 00000000000..e9bc22b127c--- /dev/null+++ b/plugins/blog/templates/not_found.liquid@@ -0,0 +1 @@+<section class="blog__empty"><h1>{{ labels.not_found_title }}</h1><p>{{ labels.not_found_body }}</p><a href="{{ site.url }}">{{ labels.all_articles }} →</a></section>diff --git a/plugins/blog/test/browser/blog-highlighting.test.mjs b/plugins/blog/test/browser/blog-highlighting.test.mjsnew file mode 100644index 00000000000..1f26601096d--- /dev/null+++ b/plugins/blog/test/browser/blog-highlighting.test.mjs@@ -0,0 +1,180 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { after, before, test } from "node:test";+import { chromium } from "playwright";++const source = readFileSync(+ new URL("../../public/blog.js", import.meta.url),+ "utf8"+);+const assets = new URL(+ "../../../../frontend/discourse/node_modules/@highlightjs/cdn-assets/",+ import.meta.url+);+const core = readFileSync(+ new URL("../../vendor/highlightjs/core.min.js", import.meta.url),+ "utf8"+);+const languages = `export default function(hljs) {${["ruby", "javascript"]+ .map((language) =>+ readFileSync(new URL(`languages/${language}.min.js`, assets), "utf8")+ )+ .join("\n")}}`;+let browser;++before(async () => {+ browser = await chromium.launch({ args: ["--no-sandbox"] });+});+after(async () => browser?.close());++async function reader(+ t,+ content,+ { auto = false, fail = false, article = true } = {}+) {+ const page = await browser.newPage();+ t.after(() => page.close());+ const requests = [];+ await page.route("https://blog.example.com/**", async (route) => {+ const path = new URL(route.request().url()).pathname;+ if (path === "/blog.js") {+ return route.fulfill({+ contentType: "application/javascript",+ body: source,+ });+ }+ if (path === "/core.js") {+ requests.push("core");+ return fail+ ? route.abort()+ : route.fulfill({ contentType: "application/javascript", body: core });+ }+ return route.fulfill({+ contentType: "text/html",+ headers: {+ "Content-Security-Policy":+ "script-src 'nonce-test' 'strict-dynamic'; object-src 'none'; base-uri 'none'",+ },+ body: `<!doctype html><body data-blog-highlight-core-url="https://blog.example.com/core.js"+ data-blog-highlight-languages-url="https://forum.example.com/languages.js"+ data-blog-highlight-auto="${auto}">+ <script nonce="test">window.requestIdleCallback = callback => { window.runHighlight = callback; };</script>+ <main ${article ? 'class="blog-article__body"' : ""}>${content}</main>+ <script nonce="test" src="/blog.js" defer></script>`,+ });+ });+ await page.route("https://forum.example.com/languages.js", (route) => {+ requests.push("languages");+ return route.fulfill({+ contentType: "application/javascript",+ headers: { "Access-Control-Allow-Origin": "*" },+ body: languages,+ });+ });+ await page.goto("https://blog.example.com/");+ return { page, requests };+}++test("defers modules until idle, highlights aliases, and keeps HTML-shaped code inert", async (t) => {+ const { page, requests } = await reader(+ t,+ `+ <pre><code class="lang-rb">puts "hello"</code></pre>+ <pre><code class="language-js">const html = '<img src=x onerror=alert(1)>';</code></pre>+ `+ );+ assert.deepEqual(requests, []);+ await page.evaluate(() => window.runHighlight());+ assert.deepEqual(requests.sort(), ["core", "languages"]);+ assert.equal(await page.locator("code[data-highlighted=yes]").count(), 2);+ assert.ok(await page.locator(".hljs-string").count());+ assert.equal(await page.locator("code img").count(), 0);+ assert.equal(+ await page.locator("code").nth(1).textContent(),+ "const html = '<img src=x onerror=alert(1)>';"+ );+});++test("preserves numbered onebox lines, blank lines, and multiline token context", async (t) => {+ const { page } = await reader(+ t,+ `<pre class="onebox"><code class="lang-ruby">+ <ol class="lines" start="91"><li>message = "first</li><li></li><li class="selected"> last"</li></ol>+ </code></pre>`+ );+ await page.evaluate(() => window.runHighlight());+ assert.equal(await page.locator("ol").getAttribute("start"), "91");+ assert.deepEqual(await page.locator("li").allTextContents(), [+ 'message = "first',+ "",+ ' last"',+ ]);+ assert.equal(+ await page.locator("li.selected .hljs-string").textContent(),+ ' last"'+ );+});++test("avoids downloads on pages without eligible code", async (t) => {+ for (const options of [+ { content: "<p>No code</p>" },+ {+ content: '<pre><code class="lang-ruby">puts 1</code></pre>',+ article: false,+ },+ { content: "<pre><code>puts 1</code></pre>" },+ { content: '<pre><code class="lang-text">puts 1</code></pre>' },+ {+ content:+ '<pre class="nohighlight"><code class="lang-ruby">puts 1</code></pre>',+ },+ {+ content:+ '<pre><code class="lang-ruby" data-highlighted="yes">puts 1</code></pre>',+ },+ {+ content: `<pre><code class="lang-ruby">${"x".repeat(30001)}</code></pre>`,+ },+ ]) {+ const { page, requests } = await reader(t, options.content, options);+ assert.equal(+ await page.evaluate(() => typeof window.runHighlight),+ "undefined"+ );+ assert.deepEqual(requests, []);+ }+});++test("supports auto detection without changing unknown languages or embedded markup", async (t) => {+ const { page } = await reader(+ t,+ `+ <pre><code>const message = "hello"; console.log(message);</code></pre>+ <pre><code class="lang-auto">const greeting = "hello"; console.log(greeting);</code></pre>+ <pre><code class="lang-unknown">leave me alone</code></pre>+ <pre><code class="lang-ruby"><a href="/example">puts</a> 1</code></pre>+ `,+ { auto: true }+ );+ await page.evaluate(() => window.runHighlight());+ assert.equal(await page.locator("code[data-highlighted=yes]").count(), 2);+ assert.equal(+ await page.locator(".lang-unknown").textContent(),+ "leave me alone"+ );+ assert.equal(await page.locator("code a").getAttribute("href"), "/example");+});++test("leaves readable code when the highlighter cannot be loaded", async (t) => {+ const { page } = await reader(+ t,+ '<pre><code class="lang-ruby">puts "hello"</code></pre>',+ { fail: true }+ );+ const errors = [];+ page.on("pageerror", (error) => errors.push(error.message));+ await page.evaluate(() => window.runHighlight());+ assert.equal(await page.locator("code").textContent(), 'puts "hello"');+ assert.equal(await page.locator("code[data-highlighted]").count(), 0);+ assert.deepEqual(errors, []);+});diff --git a/plugins/blog/test/browser/blog-lightbox.test.mjs b/plugins/blog/test/browser/blog-lightbox.test.mjsnew file mode 100644index 00000000000..7fdbabb1a9b--- /dev/null+++ b/plugins/blog/test/browser/blog-lightbox.test.mjs@@ -0,0 +1,188 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { test } from "node:test";+import vm from "node:vm";++const source = readFileSync(+ new URL("../../public/blog.js", import.meta.url),+ "utf8"+);++class Element {+ constructor(tagName) {+ this.tagName = tagName;+ this.attributes = new Map();+ this.children = [];+ this.className = "";+ this.hidden = false;+ this.listeners = new Map();+ this.classList = {+ values: new Set(),+ add: (name) => this.classList.values.add(name),+ contains: (name) => this.classList.values.has(name),+ remove: (name) => this.classList.values.delete(name),+ };+ }++ addEventListener(name, callback) {+ this.listeners.set(name, callback);+ }++ append(...children) {+ this.children.push(...children);+ }++ close() {+ this.open = false;+ this.listeners.get("close")?.({ target: this });+ }++ dispatch(name, attributes = {}) {+ const event = {+ target: this,+ button: 0,+ defaultPrevented: false,+ preventDefault() {+ this.defaultPrevented = true;+ },+ ...attributes,+ };+ this.listeners.get(name)?.(event);+ return event;+ }++ focus() {+ this.focused = true;+ }++ removeAttribute(name) {+ this.attributes.delete(name);+ if (name === "src") {+ this.src = "";+ } else if (name === "href") {+ this.href = "";+ }+ }++ setAttribute(name, value) {+ this.attributes.set(name, value);+ }++ showModal() {+ this.open = true;+ }+}++function buildImage({ alt, link, sourceUrl, title = "", excluded = false }) {+ const image = new Element("img");+ image.alt = alt;+ image.currentSrc = sourceUrl;+ image.src = sourceUrl;+ image.title = title;+ image.matches = () => false;+ image.closest = (selector) => {+ if (selector === "aside.onebox, a.video-thumbnail") {+ return excluded ? {} : null;+ }+ if (selector === "a") {+ return link;+ }+ };+ return image;+}++function loadLightbox(images) {+ const body = new Element("body");+ body.dataset = {+ blogLightboxCloseLabel: "Close translated",+ blogLightboxDialogLabel: "Dialog translated",+ blogLightboxOpenLabel: "Open translated",+ blogLightboxOpenWithDescriptionLabel:+ "Translated description __IMAGE_DESCRIPTION__",+ blogLightboxOriginalLabel: "Original translated",+ };+ const article = { querySelectorAll: () => images };+ const document = {+ body,+ createElement: (tagName) => new Element(tagName),+ getElementById: () => null,+ querySelector: (selector) =>+ selector === ".blog-article__body" ? article : null,+ };++ vm.runInNewContext(source, { document });++ return { body };+}++test("opens bare article images in a translated accessible dialog", () => {+ const image = buildImage({+ alt: "A useful diagram",+ sourceUrl: "https://example.com/diagram.jpg",+ });+ const excluded = buildImage({+ alt: "Preview thumbnail",+ excluded: true,+ sourceUrl: "https://example.com/preview.jpg",+ });+ const { body } = loadLightbox([image, excluded]);++ assert.equal(image.attributes.get("role"), "button");+ assert.equal(+ image.attributes.get("aria-label"),+ "Translated description A useful diagram"+ );+ assert.ok(image.classList.contains("blog-lightbox-trigger"));+ assert.ok(!excluded.classList.contains("blog-lightbox-trigger"));++ image.currentSrc = "https://example.com/responsive-diagram.jpg";+ image.dispatch("click");+ const dialog = body.children[0];+ const [controls, figure] = dialog.children;+ const [original, close] = controls.children;+ const [largeImage, caption] = figure.children;+ assert.ok(dialog.open);+ assert.equal(dialog.attributes.get("aria-label"), "Dialog translated");+ assert.equal(original.href, image.currentSrc);+ assert.equal(original.textContent, "Original translated");+ assert.equal(original.target, "_blank");+ assert.equal(original.rel, "noopener");+ assert.equal(close.attributes.get("aria-label"), "Close translated");+ assert.ok(close.autofocus);+ assert.equal(close.children[0].attributes.get("aria-hidden"), "true");+ assert.equal(largeImage.src, image.currentSrc);+ assert.equal(largeImage.alt, image.alt);+ assert.ok(caption.hidden);+ assert.ok(body.classList.contains("has-blog-lightbox"));++ dialog.close();+ assert.ok(image.focused);+ assert.ok(!body.classList.contains("has-blog-lightbox"));+ assert.equal(largeImage.src, "");+ assert.equal(original.href, "");+});++test("uses the original cooked upload and treats its caption as text", () => {+ const link = new Element("a");+ link.href = "https://example.com/original.jpg";+ link.title = "<strong>Plain caption</strong>";+ link.classList.add("lightbox");+ const image = buildImage({+ alt: "Uploaded photograph",+ link,+ sourceUrl: "https://example.com/thumbnail.jpg",+ });+ const { body } = loadLightbox([image]);++ const modifiedClick = link.dispatch("click", { ctrlKey: true });+ assert.ok(!modifiedClick.defaultPrevented);+ assert.equal(body.children.length, 0);++ const click = link.dispatch("click");+ assert.ok(click.defaultPrevented);+ const dialog = body.children[0];+ const [largeImage, caption] = dialog.children[1].children;+ assert.equal(largeImage.src, link.href);+ assert.equal(caption.textContent, link.title);+ assert.ok(!caption.hidden);+});diff --git a/plugins/blog/test/browser/discussion-loader.test.mjs b/plugins/blog/test/browser/discussion-loader.test.mjsnew file mode 100644index 00000000000..df595bc9106--- /dev/null+++ b/plugins/blog/test/browser/discussion-loader.test.mjs@@ -0,0 +1,157 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { test } from "node:test";+import vm from "node:vm";++const source = readFileSync(+ new URL("../../public/blog.js", import.meta.url),+ "utf8"+);++function loadDiscussion() {+ const classes = new Set();+ const failure = { hidden: true };+ const frame = { contentWindow: { postMessage() {} }, style: {} };+ let message;+ let script;+ let expired;+ let cleared = false;+ let removed = false;+ const discussion = {+ classList: {+ add: (name) => classes.add(name),+ remove: (name) => classes.delete(name),+ },+ querySelector: () => failure,+ };+ const comments = {+ dataset: {+ discourseUrl: "https://discuss.example.com/",+ topicId: "37",+ title: "Discussion",+ },+ closest: () => discussion,+ };+ const window = {+ addEventListener: (_, handler) => {+ message = handler;+ },+ removeEventListener: () => {+ removed = true;+ },+ };+ vm.runInNewContext(source, {+ window,+ URL,+ setTimeout: (callback) => {+ expired = callback;+ return 1;+ },+ clearTimeout: () => {+ cleared = true;+ },+ getComputedStyle: () => ({ getPropertyValue: () => "" }),+ document: {+ documentElement: {},+ getElementById: (id) => (id === "discourse-comments" ? comments : frame),+ createElement: () => ({}),+ head: {+ appendChild: (element) => {+ script = element;+ },+ },+ },+ IntersectionObserver: class {+ constructor(callback) {+ this.callback = callback;+ }++ observe() {+ this.callback([{ isIntersecting: true }]);+ }++ disconnect() {}+ },+ });+ return {+ embed: window.DiscourseEmbed,+ classes,+ failure,+ frame,+ message: (origin, sender = frame.contentWindow) =>+ message({+ origin,+ source: sender,+ data: { type: "discourse-blog-ready" },+ }),+ expire: () => expired(),+ error: () => script.onerror(),+ loaded: () => script.onload(),+ cleaned: () => cleared && removed,+ ready: () => cleared && !removed,+ resize: (+ height,+ origin = "https://discuss.example.com",+ sender = frame.contentWindow+ ) =>+ message({+ origin,+ source: sender,+ data: { type: "discourse-blog-resize", height },+ }),+ };+}++test("keeps the loading frame hidden until its own trusted readiness message", () => {+ const state = loadDiscussion();+ assert.ok(state.classes.has("is-loading"));+ state.message("https://attacker.example.com");+ assert.ok(state.classes.has("is-loading"));+ state.message("https://discuss.example.com", {});+ assert.ok(state.classes.has("is-loading"));+ state.message("https://discuss.example.com");+ assert.ok(!state.classes.has("is-loading"));+ assert.ok(state.failure.hidden);+ assert.ok(state.ready());+});++for (const event of ["expire", "error"]) {+ test(`${event} replaces the loading frame with the accessible fallback`, () => {+ const state = loadDiscussion();+ state[event]();+ assert.ok(state.classes.has("is-failed"));+ assert.ok(!state.classes.has("is-loading"));+ assert.ok(!state.failure.hidden);+ assert.ok(state.cleaned());+ });+}++test("lets the discussion grow instead of introducing a nested scroll area", () => {+ const { embed } = loadDiscussion();+ assert.equal(embed.dynamicHeight, false);+ assert.equal(embed.embedMinHeight, 280);+ assert.equal(embed.embedMaxHeight, undefined);+});++test("does not force a scrollbar when the frame fits its content", () => {+ const state = loadDiscussion();+ state.loaded();+ assert.equal(state.frame.scrolling, "auto");+});++test("keeps sizing after readiness and rejects unrelated or malformed resize messages", () => {+ const state = loadDiscussion();+ state.message("https://discuss.example.com");+ state.resize(1800.4);+ assert.equal(state.frame.style.height, "1802px");+ state.resize(900);+ assert.equal(state.frame.style.height, "901px");+ for (const height of [null, "800", Infinity, NaN, -1]) {+ state.resize(height);+ assert.equal(state.frame.style.height, "901px");+ }+ state.resize(2000, "https://attacker.example.com");+ state.resize(2000, "https://discuss.example.com", {});+ assert.equal(state.frame.style.height, "901px");+ assert.equal(state.frame.scrolling, "auto");+});diff --git a/plugins/blog/test/javascripts/acceptance/blog-editor-test.js b/plugins/blog/test/javascripts/acceptance/blog-editor-test.jsnew file mode 100644index 00000000000..c9a54cc2a79--- /dev/null+++ b/plugins/blog/test/javascripts/acceptance/blog-editor-test.js@@ -0,0 +1,229 @@+import { click, currentURL, visit } from "@ember/test-helpers";+import { test } from "qunit";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import formKit from "discourse/tests/helpers/form-kit-helper";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Blog editor", function (needs) {+ needs.user({ admin: true, moderator: false });+ needs.settings({+ blog_enabled: true,+ blog_category: 1,+ blog_drafts_category: 2,+ blog_url: "https://blog.example.com",+ });++ let draft;+ let published;++ needs.hooks.beforeEach(() => {+ draft = {+ id: 123,+ can_publish: true,+ source_topic_id: 123,+ source_url: "/t/an-unfinished-story/123",+ title: "An unfinished story",+ path: "/an-unfinished-story",+ url: "https://blog.example.com/an-unfinished-story",+ excerpt: "",+ featured: false,+ draft: true,+ published: false,+ live: false,+ replies: 0,+ topic_url: "/t/an-unfinished-story/123",+ preview_url: "/blog-editor/preview/123",+ };+ published = {+ ...draft,+ id: 124,+ title: "A published story",+ draft: false,+ published: true,+ live: true,+ published_at: "2026-09-01T14:20:00.000Z",+ replies: 2,+ };+ pretender.get("/blog-editor.json", (request) => {+ const status = request.queryParams.filter;+ return response({+ topics: {+ all: [draft, published],+ drafts: [draft],+ published: [published],+ unpublished: [],+ }[status || "all"],+ blog_url: "https://blog.example.com",+ });+ });+ });++ test("filters private drafts and published articles", async function (assert) {+ await visit("/blog-editor");+ assert+ .dom(".blog-dashboard__entry")+ .exists({ count: 2 }, "both editorial states are listed");+ await click(".blog-dashboard__filters button:nth-child(2)");+ assert.dom('[data-topic-id="123"]').exists("private drafts are shown");+ assert+ .dom('[data-topic-id="124"]')+ .doesNotExist("published articles are filtered out");+ await click(".blog-dashboard__filters button:nth-child(3)");+ assert.dom('[data-topic-id="124"]').exists("published articles are shown");+ assert+ .dom('[data-topic-id="123"]')+ .doesNotExist("private drafts are filtered out");+ await click(".blog-dashboard__filters button:nth-child(4)");+ assert+ .dom(".blog-dashboard__entry")+ .doesNotExist("unpublished filtering can return an empty result");+ });++ test("separates published articles from private correction work", async function (assert) {+ published = {+ ...published,+ title: "Private correction title",+ public_title: "The live article title",+ public_excerpt: "The published introduction",+ public_path: "/live-article",+ url: "https://blog.example.com/live-article",+ discussion_url: "/t/live-article/200",+ source_url: "/t/private-correction/201",+ draft_correction: true,+ };+ await visit("/blog-editor");+ assert+ .dom('[data-topic-id="124"] h2 a')+ .hasText(+ "The live article title",+ "published entries use the live title rather than the working copy"+ );+ assert+ .dom('[data-topic-id="124"] h2 a')+ .hasAttribute(+ "href",+ published.url,+ "the main link opens the actual blog article"+ );+ assert+ .dom('[data-topic-id="124"] .blog-dashboard__edit-private')+ .hasAttribute(+ "href",+ published.source_url,+ "the working copy is where publishing happens"+ );+ assert+ .dom('[data-topic-id="124"] a[href="/t/live-article/200"]')+ .hasText(+ "Public discussion",+ "the public forum topic is separately accessible"+ );+ assert+ .dom('[data-topic-id="124"] .blog-dashboard__status')+ .hasText(+ "Published",+ "corrections do not mark a live article unpublished"+ );+ assert+ .dom('[data-topic-id="124"] .blog-dashboard__correction')+ .hasText("Draft correction", "pending editorial changes are identified");+ assert+ .dom('[data-topic-id="123"] .blog-dashboard__status')+ .hasText("Draft", "never-published articles are drafts");+ assert+ .dom('[data-topic-id="123"] .blog-dashboard__correction')+ .doesNotExist("new drafts are not corrections");+ });++ test("creates a private working copy for articles without one", async function (assert) {+ published = { ...published, source_url: null, source_topic_id: null };+ pretender.post("/blog-editor/publications/124/prepare.json", () => {+ assert.step("prepare");+ return response({+ ...published,+ source_url: "/t/internationalization-localization/280",+ });+ });+ await visit("/blog-editor");+ await click('[data-topic-id="124"] .blog-dashboard__edit-private');+ assert.verifySteps(["prepare"], "a working copy is created on demand");+ assert.strictEqual(+ currentURL(),+ "/t/internationalization-localization/280",+ "the editor lands on the new working copy"+ );+ });++ test("marks exactly one article filter as selected", async function (assert) {+ await visit("/blog-editor");+ const filters = ".blog-dashboard__filters";+ assert+ .dom(`${filters} button[aria-pressed="true"]`)+ .hasText("All articles", "all articles is selected initially");++ for (const [index, label] of [+ "Drafts",+ "Published",+ "Not on the blog",+ "All articles",+ ].entries()) {+ const position = index === 3 ? 1 : index + 2;+ await click(`${filters} button:nth-child(${position})`);+ assert+ .dom(`${filters} button[aria-pressed="true"]`)+ .exists({ count: 1 }, "exactly one filter is selected");+ assert+ .dom(`${filters} button[aria-pressed="true"]`)+ .hasText(label, "the clicked filter stays selected");+ assert+ .dom(`${filters} button[aria-pressed="false"]`)+ .exists({ count: 3 }, "the other filters are explicitly unselected");+ }+ });++ test("searches the server and preserves filters through load more and refresh", async function (assert) {+ const requests = [];+ pretender.get("/blog-editor.json", (request) => {+ requests.push({ ...request.queryParams });+ return response({+ topics:+ request.queryParams.page === "1"+ ? [{ ...draft, id: 125, title: "Another matching draft" }]+ : [draft],+ more:+ request.queryParams.q === "workflow" &&+ request.queryParams.page !== "1",+ });+ });+ await visit("/blog-editor");+ await click(".blog-dashboard__filters button:nth-child(2)");+ await formKit(".blog-dashboard__search").field("q").fillIn("workflow");+ await formKit(".blog-dashboard__search").submit();+ assert.deepEqual(+ requests.at(-1),+ { filter: "drafts", q: "workflow" },+ "search is combined with the server-side status filter"+ );+ await click("[data-blog-load-more]");+ assert.deepEqual(+ requests.at(-1),+ { filter: "drafts", q: "workflow", page: "1" },+ "load more preserves the entire query"+ );+ assert+ .dom(".blog-dashboard__entry")+ .exists({ count: 2 }, "additional matching entries are appended");+ assert+ .dom("[data-blog-load-more]")+ .doesNotExist("loading stops when there are no more matches");+ await click(".blog-dashboard__links button");+ assert.deepEqual(+ requests.at(-1),+ { filter: "drafts", q: "workflow" },+ "refresh keeps filters and returns to the first page"+ );+ assert+ .dom(".blog-dashboard__entry")+ .exists({ count: 1 }, "refresh replaces previous pages");+ });+});diff --git a/plugins/blog/test/javascripts/acceptance/blog-post-summary-test.js b/plugins/blog/test/javascripts/acceptance/blog-post-summary-test.jsnew file mode 100644index 00000000000..0698b458920--- /dev/null+++ b/plugins/blog/test/javascripts/acceptance/blog-post-summary-test.js@@ -0,0 +1,105 @@+import { click, visit } from "@ember/test-helpers";+import { test } from "qunit";+import EmbedMode from "discourse/lib/embed-mode";+import { cloneJSON } from "discourse/lib/object";+import topicFixtures from "discourse/tests/fixtures/topic";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Blog article summary", function (needs) {+ needs.settings({ blog_enabled: true });+ let article;+ let originalEmbedMode;++ needs.hooks.beforeEach(() => {+ originalEmbedMode = EmbedMode.enabled;+ article = {+ url: "https://blog.example.com/workflow",+ excerpt: "A useful editorial summary.",+ blog_name: "The blog",+ };+ });+ needs.hooks.afterEach(() => {+ EmbedMode.enabled = originalEmbedMode;+ });++ needs.pretender((server, helper) => {+ server.get("/t/280.json", () => {+ const topic = cloneJSON(topicFixtures["/t/280/1.json"]);+ topic.post_stream.posts[0].blog_article = article;+ topic.post_stream.posts[0].cooked =+ "<p>The complete article is available here.</p><pre><code>bin/rails server</code></pre>";+ return helper.response(topic);+ });+ });++ test("summarizes the first post and expands the native cooked content inline", async function (assert) {+ await visit("/t/internationalization-localization/280");+ assert+ .dom("#post_1 .blog-post-summary__excerpt")+ .hasText(article.excerpt, "the editorial excerpt is displayed");+ assert+ .dom("#post_1 .blog-post-summary a")+ .hasAttribute("href", article.url, "the summary links to the blog");+ assert+ .dom("#post_1 .cooked")+ .doesNotExist("the full article is initially collapsed");+ assert+ .dom("#post_2 .cooked")+ .exists("replies still use the normal renderer");+ assert+ .dom("#post_1 .blog-post-summary button")+ .hasAttribute(+ "aria-expanded",+ "false",+ "the collapsed state is accessible"+ );++ await click("#post_1 .blog-post-summary button");+ assert+ .dom("#post_1 .cooked p")+ .hasText(+ "The complete article is available here.",+ "expansion restores the full article"+ );+ assert+ .dom("#post_1 .cooked pre code")+ .hasText("bin/rails server", "code markup is preserved");+ assert+ .dom("#post_1 .blog-post-summary button")+ .hasAttribute(+ "aria-expanded",+ "true",+ "the expanded state is accessible"+ );++ await click("#post_1 .blog-post-summary button");+ assert+ .dom("#post_1 .cooked")+ .doesNotExist("the article can be collapsed again");+ });++ test("leaves posts without published article metadata alone", async function (assert) {+ article = null;+ await visit("/t/internationalization-localization/280");+ assert+ .dom(".blog-post-summary")+ .doesNotExist("ordinary posts have no summary");+ assert.dom("#post_1 .cooked").exists("the full post remains visible");+ });++ test("keeps article text visible when arriving with search context", async function (assert) {+ await visit("/t/internationalization-localization/280?search=complete");+ assert+ .dom(".blog-post-summary")+ .doesNotExist("search results do not hide their matching text");+ assert.dom("#post_1 .cooked").exists("the complete article is rendered");+ });++ test("does not change the embedded discussion renderer", async function (assert) {+ EmbedMode.enabled = true;+ await visit("/t/internationalization-localization/280");+ assert+ .dom(".blog-post-summary")+ .doesNotExist("embedded discussions keep the existing behavior");+ });+});diff --git a/plugins/blog/test/javascripts/acceptance/blog-publication-panel-test.js b/plugins/blog/test/javascripts/acceptance/blog-publication-panel-test.jsnew file mode 100644index 00000000000..e0fc3edd9c4--- /dev/null+++ b/plugins/blog/test/javascripts/acceptance/blog-publication-panel-test.js@@ -0,0 +1,455 @@+import { click, visit } from "@ember/test-helpers";+import { test } from "qunit";+import { cloneJSON } from "discourse/lib/object";+import topicFixtures from "discourse/tests/fixtures/topic";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import formKit from "discourse/tests/helpers/form-kit-helper";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++const TOPIC_URL = "/t/internationalization-localization/280";+const PANEL = ".blog-publication-panel";++acceptance("Blog publication panel", function (needs) {+ needs.user({ admin: true });+ needs.settings({ blog_enabled: true });++ let publication;++ needs.hooks.beforeEach(() => {+ publication = {+ id: 280,+ role: "draft",+ status: "draft",+ title: "An unfinished story",+ path: "/an-unfinished-story",+ url: "https://blog.example.com/an-unfinished-story",+ excerpt: "",+ featured: false,+ changes: [],+ edits_since_publish: 0,+ draft_updated_at: "2026-09-01T10:00:00Z",+ source_topic_id: 280,+ source_url: TOPIC_URL,+ preview_url: "/blog-editor/preview/280",+ published: false,+ live: false,+ draft: true,+ can_publish: true,+ review_feedback_count: 0,+ active_review_links: 0,+ submitted_revision: null,+ approved_revision: null,+ scheduled_revision: null,+ scheduled_at: null,+ schedule_error: "",+ };+ pretender.get("/t/280.json", () => {+ const topic = cloneJSON(topicFixtures["/t/280/1.json"]);+ topic.blog_publication = publication;+ return response(topic);+ });+ pretender.get("/blog-editor/publications/280.json", () =>+ response(publication)+ );+ });++ test("publishes the current draft in one step", async function (assert) {+ pretender.post("/blog-editor/publications/280/publish.json", (request) => {+ assert.false(+ new URLSearchParams(request.requestBody).has("revision_id"),+ "the current draft is published without a frozen revision id"+ );+ publication = {+ ...publication,+ status: "live",+ published: true,+ live: true,+ published_revision_id: 7,+ last_published_at: "2026-09-02T10:00:00Z",+ };+ return response(publication);+ });+ await visit(TOPIC_URL);+ assert+ .dom(`${PANEL}__badge`)+ .hasText("Draft", "a never-published draft is labelled");+ assert+ .dom(`${PANEL}__meta a`)+ .hasText(+ "blog.example.com/an-unfinished-story",+ "the future article address is shown"+ );+ assert+ .dom(`${PANEL}__publish`)+ .hasText("Publish", "publishing is the primary action");+ await click(`${PANEL}__publish`);+ assert+ .dom(".dialog-body")+ .includesText("stay private", "the privacy boundary is explained");+ await click(".dialog-footer .btn-primary");+ assert+ .dom(`${PANEL}__badge`)+ .hasText("Live", "the panel reflects the release");+ assert+ .dom(`${PANEL}__view-live`)+ .hasAttribute("href", publication.url, "the live article is linked");+ assert+ .dom(`${PANEL}__publish`)+ .doesNotExist("a live article without edits has nothing to publish");+ assert+ .dom(`${PANEL}__options`)+ .exists("withdrawal stays reachable from the live state");+ });++ test("explains pending changes and shows the diff on demand", async function (assert) {+ publication = {+ ...publication,+ status: "changes_pending",+ published: true,+ live: true,+ published_revision_id: 6,+ last_published_at: "2026-09-02T10:00:00Z",+ changes: ["body", "excerpt"],+ edits_since_publish: 3,+ };+ pretender.get("/blog-editor/publications/280/changes.json", () =>+ response({+ title_diff_html: null,+ diff_html:+ '<div class="inline-diff"><p>Hello <ins>world</ins></p></div>',+ })+ );+ await visit(TOPIC_URL);+ assert+ .dom(`${PANEL}__badge`)+ .hasText("Changes pending", "drift from the live revision is flagged");+ assert+ .dom(`${PANEL}__meta`)+ .includesText("3 edits since", "the amount of drift is shown");+ assert+ .dom(`${PANEL}__changed`)+ .hasText("Changed: body, excerpt", "changed fields are listed");+ assert+ .dom(`${PANEL}__publish`)+ .hasText("Publish correction", "corrections are named explicitly");+ await click(`${PANEL}__toggle-diff`);+ assert+ .dom(`${PANEL}__diff ins`)+ .hasText("world", "the server diff is rendered inline");+ await click(`${PANEL}__menu-trigger`);+ assert+ .dom(`${PANEL}__unpublish`)+ .exists("published articles can be withdrawn from the menu");+ });++ test("contributors submit for approval without publisher actions", async function (assert) {+ publication.can_publish = false;+ pretender.post("/blog-editor/publications/280/submit.json", () => {+ publication = {+ ...publication,+ submitted_revision: {+ id: 7,+ preview_url: "/blog-editor/preview/280?revision_id=7",+ },+ };+ return response(publication);+ });+ await visit(TOPIC_URL);+ assert+ .dom(`${PANEL}__publish`)+ .hasText("Submit for approval", "contributors cannot publish");+ assert+ .dom(`${PANEL}__menu-trigger`)+ .doesNotExist("publisher options are not offered");+ await click(`${PANEL}__publish`);+ assert+ .dom(`${PANEL}__pending`)+ .includesText("Revision 7 submitted", "the submission is confirmed");+ assert+ .dom(`${PANEL}__approve`)+ .doesNotExist("approval requires a publisher");+ });++ test("publishers approve and publish a submitted revision", async function (assert) {+ publication.submitted_revision = {+ id: 7,+ preview_url: "/blog-editor/preview/280?revision_id=7",+ };+ pretender.post("/blog-editor/publications/280/approve.json", (request) => {+ assert.step(+ `approve ${new URLSearchParams(request.requestBody).get("revision_id")}`+ );+ publication = {+ ...publication,+ approved_revision: publication.submitted_revision,+ };+ return response(publication);+ });+ pretender.post("/blog-editor/publications/280/publish.json", (request) => {+ assert.step(+ `publish ${new URLSearchParams(request.requestBody).get("revision_id")}`+ );+ publication = {+ ...publication,+ status: "live",+ published: true,+ live: true,+ published_revision_id: 7,+ };+ return response(publication);+ });+ await visit(TOPIC_URL);+ assert+ .dom(`${PANEL}__pending a`)+ .hasAttribute(+ "href",+ "/blog-editor/preview/280?revision_id=7",+ "the frozen revision can be previewed"+ );+ await click(`${PANEL}__approve`);+ assert.verifySteps(+ ["approve 7", "publish 7"],+ "only the submitted revision is approved and published"+ );+ assert+ .dom(`${PANEL}__pending`)+ .doesNotExist("the published revision is no longer pending");+ });++ test("schedules the current draft and allows cancellation", async function (assert) {+ pretender.post("/blog-editor/publications/280/submit.json", () => {+ assert.step("submit");+ publication = {+ ...publication,+ submitted_revision: {+ id: 7,+ preview_url: "/blog-editor/preview/280?revision_id=7",+ },+ };+ return response(publication);+ });+ pretender.post("/blog-editor/publications/280/approve.json", () => {+ assert.step("approve");+ publication = {+ ...publication,+ approved_revision: publication.submitted_revision,+ };+ return response(publication);+ });+ pretender.post("/blog-editor/publications/280/schedule.json", (request) => {+ const data = new URLSearchParams(request.requestBody);+ assert.step(`schedule ${data.get("revision_id")}`);+ assert.strictEqual(+ data.get("scheduled_at"),+ new Date("2030-04-05T14:30").toISOString(),+ "local time is sent as an unambiguous UTC instant"+ );+ publication = {+ ...publication,+ status: "scheduled",+ scheduled_at: data.get("scheduled_at"),+ scheduled_revision: {+ id: 7,+ approved_by: "eviltrout",+ preview_url: "/blog-editor/preview/280?revision_id=7",+ },+ };+ return response(publication);+ });+ pretender.delete("/blog-editor/publications/280/schedule.json", () => {+ assert.step("cancel");+ publication = {+ ...publication,+ status: "draft",+ scheduled_at: null,+ scheduled_revision: null,+ };+ return response(204);+ });+ await visit(TOPIC_URL);+ await click(`${PANEL}__menu-trigger`);+ await click(`${PANEL}__menu-schedule`);+ await formKit(".blog-schedule form")+ .field("scheduled_at")+ .fillIn("2030-04-05T14:30");+ await formKit(".blog-schedule form").submit();+ assert.verifySteps(+ ["submit", "approve", "schedule 7"],+ "scheduling freezes and approves the current draft first"+ );+ assert.dom(".blog-schedule").doesNotExist("the dialog closes on success");+ assert+ .dom(`${PANEL}__badge`)+ .hasText("Scheduled", "the scheduled release is shown");+ assert+ .dom(`${PANEL}__meta`)+ .includesText("approved by eviltrout", "provenance is shown");+ await click(`${PANEL}__cancel-schedule`);+ assert.verifySteps(["cancel"], "the schedule can be cancelled");+ assert+ .dom(`${PANEL}__badge`)+ .hasText("Draft", "cancellation returns to the draft state");+ });++ test("reads private review feedback inline", async function (assert) {+ publication = {+ ...publication,+ review_feedback_count: 2,+ active_review_links: 1,+ };+ pretender.get("/blog-editor/publications/280/feedback.json", () =>+ response({+ feedback: [+ {+ id: 2,+ name: "",+ email: "",+ message: "Loving it but the colours hurt.",+ created_at: "2026-09-03T10:00:00Z",+ review: { id: 9, label: "", post_version: 3, revoked_at: null },+ },+ {+ id: 1,+ name: "Ada",+ email: "[email protected]",+ message: "<script>alert(1)</script> Tighten the introduction.",+ created_at: "2026-09-02T10:00:00Z",+ review: {+ id: 8,+ label: "Round one",+ post_version: 1,+ revoked_at: "2026-09-02T12:00:00Z",+ },+ },+ ],+ more: false,+ })+ );+ await visit(TOPIC_URL);+ assert+ .dom(`${PANEL}__reviews-title`)+ .includesText("2 private feedback", "the feedback count is visible");+ assert+ .dom(`${PANEL}__reviews-title`)+ .includesText("1 active review link", "open links are counted");+ assert.dom(`${PANEL}__feedback`).doesNotExist("feedback loads on demand");+ await click(`${PANEL}__toggle-feedback`);+ assert.dom(`${PANEL}__feedback-entry`).exists({ count: 2 });+ assert+ .dom(`${PANEL}__feedback-entry:first-child`)+ .includesText("Anonymous reviewer", "missing names are labelled");+ assert+ .dom(`${PANEL}__feedback-entry:last-child`)+ .includesText("Ada", "reviewer names are shown")+ .includesText("Round one", "the review label is shown")+ .includesText("Article revision 1", "the reviewed revision is shown");+ assert+ .dom(`${PANEL}__feedback-entry:last-child script`)+ .doesNotExist("feedback is rendered as text");+ await click(`${PANEL}__toggle-feedback`);+ assert.dom(`${PANEL}__feedback`).doesNotExist("feedback collapses again");+ });++ test("saves article settings without publishing", async function (assert) {+ pretender.put("/blog-editor/publications/280.json", (request) => {+ const data = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ data.get("publication[excerpt]"),+ "A revised introduction",+ "the excerpt is saved"+ );+ publication = { ...publication, excerpt: "A revised introduction" };+ return response(publication);+ });+ await visit(TOPIC_URL);+ assert+ .dom(`${PANEL}__form`)+ .isNotVisible("settings are collapsed by default");+ await click(`${PANEL}__settings-toggle`);+ await formKit(`${PANEL}__form`)+ .field("excerpt")+ .fillIn("A revised introduction");+ await formKit(`${PANEL}__form`).submit();+ assert+ .dom(`${PANEL}__badge`)+ .hasText("Draft", "saving settings does not publish");+ });++ test("the public discussion topic points at the private working copy", async function (assert) {+ publication = {+ ...publication,+ role: "discussion",+ status: "changes_pending",+ published: true,+ live: true,+ draft_correction: true,+ changes: ["body"],+ source_url: "/t/private-working-copy/281",+ };+ await visit(TOPIC_URL);+ assert.dom(PANEL).doesNotExist("the full panel stays on the working copy");+ assert+ .dom(".blog-discussion-banner")+ .includesText(+ "which has unpublished changes",+ "pending corrections are mentioned"+ );+ assert+ .dom('.blog-discussion-banner a[href="/t/private-working-copy/281"]')+ .exists("the working copy is linked");+ assert+ .dom(".blog-discussion-banner__edit")+ .hasText("Edit privately", "editing is redirected to the working copy");+ });++ test("a public topic that is not on the blog offers to prepare a working copy", async function (assert) {+ publication = {+ ...publication,+ role: "discussion",+ source_topic_id: null,+ source_url: null,+ };+ await visit(TOPIC_URL);+ assert.dom(PANEL).doesNotExist("no publishing actions on a public topic");+ assert+ .dom(".blog-discussion-banner")+ .includesText("This topic is not on the blog", "the state is explained")+ .includesText("prepare changes", "the next step is explained");+ assert.dom(".blog-discussion-banner__edit").exists();+ });++ test("shows a withdrawn article and lists pending changes while scheduled", async function (assert) {+ publication = {+ ...publication,+ status: "unpublished",+ published: false,+ published_revision_id: 7,+ last_published_at: "2026-09-02T10:00:00Z",+ };+ await visit(TOPIC_URL);+ assert.dom(`${PANEL}__badge`).hasText("Unpublished");+ assert+ .dom(`${PANEL}__meta`)+ .includesText("discussion stays open", "the discussion is unaffected");+ assert.dom(`${PANEL}__changes`).doesNotExist();++ publication = {+ ...publication,+ status: "scheduled",+ published: true,+ changes: ["body"],+ scheduled_at: "2030-01-01T09:00:00Z",+ scheduled_revision: {+ id: 9,+ approved_by: "eviltrout",+ preview_url: "/blog-editor/preview/280?revision_id=9",+ },+ };+ await visit("/");+ await visit(TOPIC_URL);+ assert.dom(`${PANEL}__badge`).hasText("Scheduled");+ assert+ .dom(`${PANEL}__changed`)+ .includesText("body", "drift since the frozen revision is still listed");+ });+});diff --git a/plugins/blog/test/javascripts/acceptance/blog-review-test.js b/plugins/blog/test/javascripts/acceptance/blog-review-test.jsnew file mode 100644index 00000000000..69638ba09e5--- /dev/null+++ b/plugins/blog/test/javascripts/acceptance/blog-review-test.js@@ -0,0 +1,101 @@+import { visit } from "@ember/test-helpers";+import { test } from "qunit";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import formKit from "discourse/tests/helpers/form-kit-helper";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Blog review reader", function (needs) {+ needs.settings({ blog_enabled: true });++ needs.hooks.beforeEach(() => {+ pretender.get("/blog/review.json", (request) =>+ response({+ title: "A frozen draft",+ cooked: "<p>The article selected for review.</p>",+ post_version: request.queryParams.review_token === "new-round" ? 2 : 1,+ expires_at: "2030-01-01T00:00:00Z",+ })+ );+ });++ test("accepts private feedback without an account or forum chrome", async function (assert) {+ pretender.post("/blog/review/feedback.json", (request) => {+ const values = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ values.get("review_token"),+ "reader-capability",+ "submission is scoped to the review capability"+ );+ assert.strictEqual(+ values.get("feedback[message]"),+ "Please clarify the introduction.",+ "the feedback is submitted"+ );+ assert.step("feedback");+ return response(204);+ });+ await visit("/blog/review?review_token=reader-capability");+ assert+ .dom(".blog-review h1")+ .hasText("A frozen draft", "the frozen title is rendered");+ assert+ .dom(".blog-review__article")+ .hasText(+ "The article selected for review.",+ "the frozen body is rendered"+ );+ assert+ .dom(".d-header")+ .doesNotExist("reviewers do not see the forum header");+ assert+ .dom(".sidebar-wrapper")+ .doesNotExist("reviewers do not see the forum sidebar");+ await formKit(".blog-review form")+ .field("message")+ .fillIn("Please clarify the introduction.");+ await formKit(".blog-review form").submit();+ assert.verifySteps(["feedback"], "feedback is submitted once");+ assert+ .dom(".blog-review__feedback")+ .includesText("saved privately", "the reviewer gets confirmation");+ assert+ .dom(".blog-review form")+ .doesNotExist("the submitted form is replaced by confirmation");+ });++ test("clears the reader when access expires before submission", async function (assert) {+ pretender.post("/blog/review/feedback.json", () =>+ response(404, { errors: ["Unavailable"] })+ );+ await visit("/blog/review?review_token=reader-capability");+ await formKit(".blog-review form")+ .field("message")+ .fillIn("A late response");+ await formKit(".blog-review form").submit();+ assert+ .dom(".blog-review__article")+ .doesNotExist("the stale article is removed after access is denied");+ assert+ .dom(".blog-review")+ .includesText(+ "no longer available",+ "expiry is explained without offering submission again"+ );+ });++ test("shows unavailable links without a feedback form", async function (assert) {+ pretender.get("/blog/review.json", () =>+ response(404, { errors: ["Unavailable"] })+ );+ await visit("/blog/review?review_token=missing");+ assert+ .dom(".blog-review form")+ .doesNotExist("unavailable reviews cannot accept feedback");+ assert+ .dom(".alert-error")+ .includesText(+ "Ask the editor",+ "the recipient can request a replacement"+ );+ });+});diff --git a/plugins/blog/test/javascripts/acceptance/blog-reviews-management-test.js b/plugins/blog/test/javascripts/acceptance/blog-reviews-management-test.jsnew file mode 100644index 00000000000..84b3e669da2--- /dev/null+++ b/plugins/blog/test/javascripts/acceptance/blog-reviews-management-test.js@@ -0,0 +1,159 @@+import { click, visit } from "@ember/test-helpers";+import { test } from "qunit";+import { cloneJSON } from "discourse/lib/object";+import topicFixtures from "discourse/tests/fixtures/topic";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import formKit from "discourse/tests/helpers/form-kit-helper";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++const TOPIC_URL = "/t/internationalization-localization/280";++acceptance("Blog review management", function (needs) {+ needs.user({ admin: true });+ needs.settings({ blog_enabled: true });++ let reviews;+ needs.hooks.beforeEach(() => {+ reviews = [];+ const draft = {+ id: 280,+ role: "draft",+ status: "draft",+ source_topic_id: 280,+ source_url: TOPIC_URL,+ title: "Private article",+ draft: true,+ published: false,+ live: false,+ can_publish: true,+ changes: [],+ path: "/private-article",+ url: "https://blog.example.com/private-article",+ excerpt: "",+ featured: false,+ };+ pretender.get("/t/280.json", () => {+ const topic = cloneJSON(topicFixtures["/t/280/1.json"]);+ topic.blog_publication = draft;+ return response(topic);+ });+ pretender.get("/blog-editor/publications/280/reviews.json", () =>+ response({ reviews, more: false })+ );+ });++ test("creates, reads private feedback, and revokes a review link separately from publication", async function (assert) {+ pretender.post("/blog-editor/publications/280/reviews.json", (request) => {+ assert.strictEqual(+ new URLSearchParams(request.requestBody).get("label"),+ "Editorial round",+ "the optional label is saved"+ );+ const review = {+ id: 1,+ label: "Editorial round",+ post_version: 1,+ active: true,+ feedback_count: 1,+ url: "https://blog.example.com/blog/review?review_token=secret",+ };+ reviews = [review];+ return response({ review });+ });+ pretender.get("/blog-editor/publications/280/reviews/1/feedback.json", () =>+ response({+ feedback: [+ {+ id: 1,+ name: "Guest",+ email: "",+ message: "<script>not executable</script>",+ created_at: "2030-01-01T00:00:00Z",+ },+ ],+ more: false,+ })+ );+ pretender.delete("/blog-editor/publications/280/reviews/1.json", () => {+ reviews = [+ {+ ...reviews[0],+ active: false,+ url: null,+ revoked_at: "2030-01-01T00:00:00Z",+ },+ ];+ assert.step("revoked");+ return response(204);+ });+ await visit(TOPIC_URL);+ await click(".blog-publication-panel__reviews");+ assert+ .dom(".blog-reviews")+ .includesText(+ "Anyone with the link",+ "the sharing boundary is explained before creation"+ );+ await formKit(".blog-reviews__create")+ .field("label")+ .fillIn("Editorial round");+ await formKit(".blog-reviews__create").submit();+ assert+ .dom(".blog-reviews__link-url")+ .hasValue(+ "https://blog.example.com/blog/review?review_token=secret",+ "an issued link stays readable instead of being shown once"+ );+ assert+ .dom(".blog-reviews__open")+ .hasAttribute(+ "href",+ "https://blog.example.com/blog/review?review_token=secret"+ );+ await click(".blog-reviews__feedback-toggle");+ assert+ .dom(".blog-reviews__feedback p")+ .hasText(+ "<script>not executable</script>",+ "untrusted feedback is escaped"+ );+ assert+ .dom(".blog-reviews__feedback script")+ .doesNotExist("feedback never becomes executable HTML");+ await click(".blog-reviews__revoke");+ assert.verifySteps([], "revocation requires confirmation");+ await click(".dialog-footer .btn-primary");+ assert.verifySteps(["revoked"], "the selected grant is revoked");+ assert+ .dom(".blog-reviews__link")+ .doesNotExist("a revoked link is no longer offered for sharing");+ assert+ .dom('[data-review-id="1"]')+ .includesText(+ "Expired or revoked",+ "the old review remains available for private feedback"+ );+ });++ test("asks before discarding unsaved publication settings", async function (assert) {+ await visit(TOPIC_URL);+ await click(".blog-publication-panel__settings-toggle");+ await formKit(".blog-publication-panel__form")+ .field("excerpt")+ .fillIn("Unsaved publication excerpt");+ await click(".blog-publication-panel__reviews");+ assert+ .dom(".dialog-body")+ .includesText(+ "Discard unsaved publication settings",+ "sharing does not silently discard metadata edits"+ );+ assert+ .dom(".blog-reviews")+ .doesNotExist("review management waits for confirmation");+ await click(".dialog-footer .btn-primary");+ assert+ .dom(".blog-reviews")+ .exists("confirmation opens the saved-article sharing workflow");+ });+});diff --git a/plugins/blog/test/javascripts/acceptance/blog-themes-test.js b/plugins/blog/test/javascripts/acceptance/blog-themes-test.jsnew file mode 100644index 00000000000..394195ddfad--- /dev/null+++ b/plugins/blog/test/javascripts/acceptance/blog-themes-test.js@@ -0,0 +1,870 @@+import {+ click,+ currentURL,+ fillIn as fillControl,+ find,+ triggerEvent,+ visit,+} from "@ember/test-helpers";+import { test } from "qunit";+import sinon from "sinon";+import interceptClick from "discourse/lib/intercept-click";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import formKit from "discourse/tests/helpers/form-kit-helper";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Blog themes and identity", function (needs) {+ needs.user({ admin: true });+ needs.settings({ blog_enabled: true });+ needs.site({ blog_base_url: "https://blog.example.com" });++ let active;+ let draft;+ needs.hooks.beforeEach(() => {+ pretender.get("/admin/plugins/blog.json", () =>+ response({+ id: "blog",+ name: "blog",+ humanized_name: "Blog",+ authors: "Discourse",+ enabled: true,+ enabled_setting: "blog_enabled",+ has_settings: true,+ admin_route: { use_new_show_route: true, location: "blog" },+ })+ );+ pretender.get("/admin/plugins/blog/theme-authoring.json", () =>+ response({+ templates: Object.fromEntries(+ ["layout", "index", "article", "about", "not_found"].map((name) => [+ `template_${name}`,+ "<h1>{{ site.title }}</h1>",+ ])+ ),+ articles: [{ id: 1, title: "Published sample" }],+ variables: {+ site: { title: "Example blog" },+ article: {+ title: "Published sample",+ body_html: "<p>Sample body</p>",+ },+ },+ })+ );+ active = {+ id: "live",+ name: "Current appearance",+ revision: 2,+ preview_url: "https://blog.example.com/?blog_theme_preview=live",+ accent_color: "d64b2a",+ paper_color: "f5f0e6",+ ink_color: "19382d",+ css: "",+ javascript: "",+ };+ draft = {+ ...active,+ id: "candidate",+ name: "Candidate",+ revision: 1,+ preview_url: "https://blog.example.com/?blog_theme_preview=signed",+ };+ pretender.get("/admin/plugins/blog/themes.json", () =>+ response({ themes: [draft], active })+ );+ pretender.get("/admin/plugins/blog/themes/candidate.json", () =>+ response({ theme: draft, active })+ );+ const settings = {+ blog_title: "Fieldnotes",+ blog_description: "Ideas worth sharing",+ blog_about: "About our community",+ };+ pretender.get("/admin/site_settings.json", () =>+ response({+ site_settings: Object.entries(settings).map(([setting, value]) => ({+ setting,+ value,+ })),+ })+ );+ });++ test("separates the themes list from focused theme editing and identity", async function (assert) {+ await visit("/admin/plugins/blog/themes");+ assert+ .dom(".admin-plugin-config-page__top-nav-item")+ .exists(+ { count: 3 },+ "Settings, Themes, and Identity are distinct sections"+ );+ assert+ .dom(".blog-theme-editor__form")+ .doesNotExist("the list does not contain code editors");+ assert+ .dom(".blog-identity__form")+ .doesNotExist("identity is not mixed into the themes list");+ await click('[data-theme-id="candidate"] a');+ assert.strictEqual(+ currentURL(),+ "/admin/plugins/blog/themes/candidate/edit",+ "a theme opens its own URL"+ );+ assert+ .dom(".blog-themes")+ .doesNotExist("the list is absent from the focused editor");+ assert+ .dom(".blog-theme-editor__form")+ .exists("only the selected theme form is shown");+ assert+ .dom(".blog-theme-editor__javascript")+ .doesNotHaveAttribute("open", "JavaScript starts collapsed");+ for (const name of ["accent_color", "paper_color", "ink_color"]) {+ assert.true(+ Boolean(find(`[data-name="${name}"]`).closest(".form-kit__col")),+ `${name} retains its label containment`+ );+ }+ });++ test("saves a draft without activation and blocks activating unsaved edits", async function (assert) {+ pretender.put("/admin/plugins/blog/themes/candidate.json", (request) => {+ const values = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ values.get("theme[css]"),+ ".blog { font-size: 18px; }",+ "CSS reaches the draft endpoint"+ );+ assert.strictEqual(+ values.get("theme[javascript]"),+ "window.demo = true;",+ "JavaScript reaches the draft endpoint"+ );+ draft = { ...draft, revision: 2 };+ return response(draft);+ });+ await visit("/admin/plugins/blog/themes/candidate/edit");+ const form = formKit(".blog-theme-editor__form");+ await form.field("css").fillIn(".blog { font-size: 18px; }");+ await click(".blog-theme-editor__javascript summary");+ await form.field("javascript").fillIn("window.demo = true;");+ await form.submit();+ assert+ .dom(".blog-theme-editor__preview-draft")+ .isNotDisabled("a saved draft can be previewed");+ await formKit(".blog-theme-editor__form").field("name").fillIn("Unsaved");+ assert+ .dom(".blog-theme-editor__activate")+ .isDisabled("unsaved edits cannot be activated");+ assert+ .dom(".blog-theme-editor")+ .includesText(+ "Save your changes before activating this draft",+ "unsaved edits are called out before activating"+ );+ });++ test("edits Liquid templates as a saved draft without activating them", async function (assert) {+ pretender.put("/admin/plugins/blog/themes/candidate.json", (request) => {+ const values = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ values.get("theme[template_index]"),+ "<h1>{{ site.title }}</h1>",+ "Liquid is sent unchanged to the draft endpoint"+ );+ draft = {+ ...draft,+ revision: 2,+ template_index: values.get("theme[template_index]"),+ };+ return response(draft);+ });+ await visit("/admin/plugins/blog/themes/candidate/edit");+ assert+ .dom('[data-authoring-tab="design"]')+ .hasAttribute(+ "aria-current",+ "true",+ "the design fields are the default tab"+ );+ await click('[data-authoring-tab="template_index"]');+ assert+ .dom('[data-authoring-tab="template_index"]')+ .hasAttribute("aria-current", "true", "each template is its own tab");+ assert+ .dom('[data-authoring-tab="design"]')+ .doesNotHaveAttribute("aria-current");+ await click(".blog-theme-editor__customize");+ const form = formKit(".blog-theme-editor__form");+ assert+ .dom('[data-name="template_index"]')+ .hasClass(+ "blog-theme-editor__template-field",+ "the custom editor receives its full-width layout"+ );+ await fillControl(+ '[data-name="template_index"] textarea',+ "<h1>{{ site.title }}</h1>"+ );+ assert+ .dom(".blog-theme-editor__activate")+ .isDisabled("unsaved template edits cannot be activated");+ await form.submit();+ assert+ .dom(".blog-theme-editor__preview-draft")+ .isNotDisabled("the saved template can be previewed before activation");+ });++ test("customizes one effective template, inserts a variable, and restores its default", async function (assert) {+ await visit("/admin/plugins/blog/themes/candidate/edit");+ await click('[data-authoring-tab="template_layout"]');+ assert+ .dom(".blog-theme-editor__builtin code")+ .includesText(+ "site.title",+ "the effective default is visible before editing"+ );+ await click(".blog-theme-editor__customize");+ assert+ .dom('[data-name="template_layout"] .ace_content')+ .includesText(+ "site.title",+ "customizing starts with visible working source"+ );+ assert+ .dom('[data-name="template_index"]')+ .doesNotExist("other templates are not stacked below it");++ await fillControl(+ '[data-name="template_layout"] textarea',+ "<main>Unsaved author edits</main>"+ );+ const editor = find(".blog-theme-editor__template-control");++ await click(".blog-theme-editor__variables");+ assert+ .dom(".blog-theme-variables")+ .exists("the variable reference opens in a modal");+ await fillControl(+ 'input[aria-label="Find a variable"]',+ "article.body_html"+ );+ assert+ .dom(".blog-theme-variables__item")+ .exists({ count: 1 }, "the reference can be filtered");+ assert+ .dom(".blog-theme-variables__item")+ .includesText("Trusted HTML", "trusted fragments are identified");+ await click(".blog-theme-variables__insert");+ assert+ .dom(".blog-theme-variables")+ .doesNotExist("inserting a snippet closes the reference");+ assert+ .dom('[data-name="template_layout"] .ace_content')+ .includesText(+ "article.body_html",+ "the inserted snippet is visible in the editor"+ );+ assert+ .dom('[data-name="template_layout"] .ace_content')+ .includesText(+ "Unsaved author edits",+ "inserting preserves the author's changes"+ );+ assert.strictEqual(+ find(".blog-theme-editor__template-control"),+ editor,+ "programmatic changes update the existing editor without remounting"+ );++ await click('[data-authoring-tab="design"]');+ await click('[data-authoring-tab="template_layout"]');+ assert+ .dom('[data-name="template_layout"] .ace_content')+ .includesText(+ "article.body_html",+ "FormKit retains the snippet across tab changes"+ );++ await click(".blog-theme-editor__restore-default");+ await click(".dialog-footer .btn-primary");+ assert+ .dom(".blog-theme-editor__builtin code")+ .exists("restoring returns to the visible built-in template");+ assert+ .dom('[data-name="template_layout"]')+ .doesNotExist(+ "the override is removed rather than replaced with a hidden copy"+ );+ });++ test("previews unsaved changes in a modal without saving or activating", async function (assert) {+ const previewedPages = [];+ pretender.post(+ "/admin/plugins/blog/theme-authoring/preview.json",+ (request) => {+ const values = new URLSearchParams(request.requestBody);+ previewedPages.push(values.get("page"));+ assert.strictEqual(+ values.get("theme[css]"),+ ".blog { color: blue; }",+ "design edits survive unmounting their tab"+ );+ assert.strictEqual(+ values.get("theme[template_index]"),+ "<h1>Unsaved preview</h1>",+ "preview includes unsaved template changes"+ );+ assert.strictEqual(+ values.get("article_id"),+ "1",+ "the selected public article is used"+ );+ return response({+ url: `about:blank#preview-${previewedPages.length}`,+ });+ }+ );+ await visit("/admin/plugins/blog/themes/candidate/edit");+ await formKit(".blog-theme-editor__form")+ .field("css")+ .fillIn(".blog { color: blue; }");+ await click('[data-authoring-tab="template_index"]');+ await click(".blog-theme-editor__customize");+ await fillControl(+ '[data-name="template_index"] textarea',+ "<h1>Unsaved preview</h1>"+ );+ await click(".blog-theme-editor__preview-draft");+ assert+ .dom(".blog-theme-preview__frame")+ .hasAttribute(+ "src",+ "about:blank#preview-1",+ "the working snapshot is displayed"+ );+ assert+ .dom(".blog-theme-editor__activate")+ .isDisabled("previewing does not commit unsaved changes");++ await fillControl('select[aria-label="Page to preview"]', "article");+ assert+ .dom(".blog-theme-preview__frame")+ .hasAttribute(+ "src",+ "about:blank#preview-2",+ "picking another page re-previews it without a refresh button"+ );+ await fillControl('select[aria-label="Preview size"]', "mobile");+ assert+ .dom(".blog-theme-preview__frame")+ .hasAttribute(+ "data-size",+ "mobile",+ "mobile preview has its own viewport"+ );++ assert.deepEqual(+ previewedPages,+ ["index", "article"],+ "the preview follows the edited template, then the page picked in the modal"+ );++ await click(".d-modal__footer .btn");+ assert+ .dom(".blog-theme-preview")+ .doesNotExist("closing returns to the editor");+ assert+ .dom('[data-name="template_index"] .ace_content')+ .includesText("Unsaved preview", "template edits survive previewing");+ });++ test("explains that article previews need a published article", async function (assert) {+ let previews = 0;+ pretender.get("/admin/plugins/blog/theme-authoring.json", () =>+ response({+ templates: { template_article: "<h1>{{ site.title }}</h1>" },+ articles: [],+ variables: { site: { title: "Example blog" } },+ })+ );+ pretender.post("/admin/plugins/blog/theme-authoring/preview.json", () => {+ previews++;+ return response({ url: "about:blank#preview" });+ });++ await visit("/admin/plugins/blog/themes/candidate/edit");+ await click('[data-authoring-tab="template_article"]');+ await click(".blog-theme-editor__preview-draft");+ assert+ .dom(".blog-theme-preview__frame")+ .exists("without a published article the homepage stands in");++ await fillControl('select[aria-label="Page to preview"]', "article");+ assert+ .dom(".blog-theme-preview__empty")+ .includesText(+ "Article previews need a published article",+ "the article page explains what it needs"+ );+ assert.strictEqual(previews, 1, "no preview is requested for that page");+ });++ test("marks customized templates on their tab and names the state above the editor", async function (assert) {+ await visit("/admin/plugins/blog/themes/candidate/edit");+ assert+ .dom(".blog-theme-editor__tabs .nav-pills > li")+ .exists({ count: 6 }, "design and every template have a tab");+ assert+ .dom(".blog-theme-editor__state")+ .doesNotExist("the design tab needs no template state");++ await click('[data-authoring-tab="template_about"]');+ assert+ .dom(".blog-theme-editor__state")+ .includesText(+ "Built-in template",+ "an untouched template is named as built-in"+ );+ assert+ .dom('[data-authoring-tab="template_about"] .blog-theme-editor__marker')+ .doesNotExist("built-in tabs carry no marker");++ await click(".blog-theme-editor__customize");+ assert+ .dom(".blog-theme-editor__state")+ .includesText("Custom template", "the state follows the override");+ assert+ .dom('[data-authoring-tab="template_about"] .blog-theme-editor__marker')+ .exists("a customized template is marked on its tab");+ assert+ .dom('[data-authoring-tab="design"] .blog-theme-editor__marker')+ .doesNotExist("the design tab is never marked");++ await click('[data-authoring-tab="template_layout"]');+ assert+ .dom(".blog-theme-editor__state")+ .includesText("Built-in template", "switching tabs switches the state");+ assert+ .dom('[data-authoring-tab="template_about"] .blog-theme-editor__marker')+ .exists("the marker stays on the customized tab");+ });++ test("activates a saved draft only after confirmation", async function (assert) {+ pretender.post(+ "/admin/plugins/blog/themes/candidate/activate.json",+ (request) => {+ assert.strictEqual(+ new URLSearchParams(request.requestBody).get("revision"),+ "1",+ "the reviewed revision is activated"+ );+ assert.step("activated");+ return response(draft);+ }+ );+ await visit("/admin/plugins/blog/themes/candidate/edit");+ await click(".blog-theme-editor__activate");+ assert.verifySteps([], "opening confirmation makes no changes");+ await click(".dialog-footer .btn-primary");+ assert.verifySteps(["activated"], "confirmation activates the draft");+ });++ test("creates a theme on its own page then opens the persisted editor", async function (assert) {+ pretender.post("/admin/plugins/blog/themes.json", () => response(draft));+ await visit("/admin/plugins/blog/themes/new");+ assert+ .dom(".blog-themes")+ .doesNotExist("new theme creation has no list alongside it");+ await formKit(".blog-theme-editor__form").field("name").fillIn("Candidate");+ await formKit(".blog-theme-editor__form").submit();+ assert.strictEqual(+ currentURL(),+ "/admin/plugins/blog/themes/candidate/edit",+ "save opens the persisted theme without a dirty-form prompt"+ );+ });++ test("offers Import and exports only saved themes", async function (assert) {+ await visit("/admin/plugins/blog/themes");+ assert+ .dom(".d-page-subheader .btn-default")+ .hasText("Import", "the list offers a general import action");++ await visit("/admin/plugins/blog/themes/candidate/edit");+ assert+ .dom(".blog-theme-editor__export")+ .hasAttribute(+ "href",+ "/admin/plugins/blog/themes/candidate/export",+ "exports the saved draft"+ )+ .hasAttribute("download", "", "downloads rather than navigating");++ const event = {+ target: find(".blog-theme-editor__export"),+ preventDefault: sinon.spy(),+ };+ interceptClick(event);+ assert.false(+ event.preventDefault.called,+ "the client router leaves the download to the browser"+ );++ await visit("/admin/plugins/blog/themes/new");+ assert+ .dom(".blog-theme-editor__export")+ .doesNotExist("a theme must be saved before it can be exported");+ });++ test("imports a ZIP file and opens the imported draft", async function (assert) {+ const file = new File(["theme archive"], "theme.zip", {+ type: "application/zip",+ });+ pretender.post("/admin/plugins/blog/themes/import.json", (request) => {+ assert.strictEqual(+ request.requestBody.get("file"),+ file,+ "the archive is sent as multipart form data"+ );+ assert.false(+ request.requestBody.has("repository"),+ "no Git source is sent"+ );+ return response(draft);+ });++ await visit("/admin/plugins/blog/themes/import/new");+ await click('input[type="radio"][value="file"]');+ assert.dom('[name="repository"]').doesNotExist("Git fields are hidden");+ assert+ .dom(".blog-theme-import .pick-files-button button")+ .isVisible("a visible button opens the file picker")+ .hasText("Choose ZIP file", "the picker describes the supported format");++ const fileInput = find('.blog-theme-import input[type="file"]');+ const openPicker = sinon.stub(fileInput, "click");+ try {+ await click(".blog-theme-import .pick-files-button button");+ assert.true(+ openPicker.calledOnce,+ "the button opens the system file picker"+ );+ } finally {+ openPicker.restore();+ }++ await triggerEvent('.blog-theme-import input[type="file"]', "change", {+ files: [file],+ });+ assert+ .dom(".blog-theme-import__filename")+ .hasText(+ "theme.zip",+ "the selected filename is visible before importing"+ );+ await formKit(".blog-theme-import__form").submit();++ assert.strictEqual(+ currentURL(),+ "/admin/plugins/blog/themes/candidate/edit",+ "import opens the new draft"+ );+ });++ test("imports Git on a separate page and opens the imported draft", async function (assert) {+ pretender.post("/admin/plugins/blog/themes/import.json", (request) => {+ const values = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ values.get("repository"),+ "https://github.com/example/theme",+ "the source URL is submitted"+ );+ draft = {+ ...draft,+ source: {+ repository: values.get("repository"),+ branch: "design",+ commit: "abc123",+ },+ };+ return response(draft);+ });+ await visit("/admin/plugins/blog/themes/import/new");+ assert+ .dom(".blog-theme-editor__form")+ .doesNotExist("import is not mixed with theme editing");+ const form = formKit(".blog-theme-import__form");+ await form.field("repository").fillIn("https://github.com/example/theme");+ await form.field("branch").fillIn("design");+ await form.submit();+ assert.strictEqual(+ currentURL(),+ "/admin/plugins/blog/themes/candidate/edit",+ "import opens the focused editor"+ );+ assert+ .dom(".blog-theme-editor__source")+ .includesText("abc123", "the source is retained in its own disclosure");+ });++ test("saves identity separately through the audited settings endpoint", async function (assert) {+ pretender.put("/admin/site_settings/bulk_update.json", (request) => {+ const values = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ values.get("settings[blog_title][value]"),+ "New identity",+ "identity is saved"+ );+ assert.false(+ [...values.keys()].some((key) => key.includes("custom_css")),+ "identity never publishes theme code"+ );+ return response(204);+ });+ await visit("/admin/plugins/blog/identity");+ assert.dom(".blog-themes").doesNotExist("identity contains no themes list");+ assert+ .dom(".blog-theme-editor__form")+ .doesNotExist("identity contains no theme editor");+ const form = formKit(".blog-identity__form");+ await form.field("blog_title").fillIn("New identity");+ await form.submit();+ });++ test("warns before leaving a theme with unsaved changes", async function (assert) {+ await visit("/admin/plugins/blog/themes/candidate/edit");+ await formKit(".blog-theme-editor__form")+ .field("name")+ .fillIn("Unsaved name");+ await click('a[href="/admin/plugins/blog/themes"]');+ assert+ .dom(".dialog-body")+ .exists("FormKit asks before discarding theme edits");+ assert+ .dom(".blog-theme-editor__form")+ .exists("the editor remains until navigation is confirmed");+ await click(".dialog-footer .btn-primary");+ assert.strictEqual(+ currentURL(),+ "/admin/plugins/blog/themes",+ "confirmation returns to the list"+ );+ });++ test("theme covers show a shared specimen and the saved palette", async function (assert) {+ await visit("/admin/plugins/blog/themes");++ assert+ .dom(".blog-theme-thumbnail__headline")+ .hasText("Stay curious.", "the cover shows readable sample typography");+ assert+ .dom(".blog-theme-thumbnail__excerpt")+ .hasText(+ "Notes on making things, staying curious, and finding meaning in the everyday.",+ "the cover includes a sample excerpt"+ );+ assert+ .dom(".blog-theme-thumbnail__caption")+ .hasText("Theme palette", "the cover identifies its palette specimen");+ const style = find(".blog-theme-thumbnail").style;+ assert.strictEqual(+ style.getPropertyValue("--blog-theme-paper").trim(),+ "#f5f0e6",+ "the cover uses the saved paper color"+ );+ assert.strictEqual(+ style.getPropertyValue("--blog-theme-ink").trim(),+ "#19382d",+ "the cover uses the saved ink color"+ );+ assert.strictEqual(+ style.getPropertyValue("--blog-theme-accent").trim(),+ "#d64b2a",+ "the cover uses the saved accent color"+ );+ assert+ .dom(".blog-theme-thumbnail__swatch")+ .exists({ count: 3 }, "all three palette colors have swatches");+ });++ test("theme covers fall back safely for missing or invalid colors", async function (assert) {+ draft.paper_color = null;+ draft.ink_color = "invalid";+ draft.accent_color = "abcdef; background: url(https://example.com/image)";++ await visit("/admin/plugins/blog/themes");++ const style = find(".blog-theme-thumbnail").style;+ for (const [name, fallback] of [+ ["paper", "secondary"],+ ["ink", "primary"],+ ["accent", "tertiary"],+ ]) {+ assert.strictEqual(+ style.getPropertyValue(`--blog-theme-${name}`).trim(),+ `var(--${fallback})`,+ `invalid ${name} falls back to the admin palette`+ );+ }+ assert.strictEqual(+ style.length,+ 3,+ "invalid colors cannot inject declarations"+ );+ });++ test("lists each design as a card with its palette, state, and actions", async function (assert) {+ const imported = {+ ...draft,+ source: {+ repository: "https://example.com/blog-theme.git",+ branch: "main",+ commit: "abc1234",+ },+ locally_modified: true,+ };+ pretender.get("/admin/plugins/blog/themes.json", () =>+ response({ themes: [active, imported], active })+ );++ await visit("/admin/plugins/blog/themes");+ assert.dom(".theme-card").exists({ count: 2 }, "each design is a card");+ assert+ .dom(`.theme-card[data-theme-id="live"] .blog-theme-thumbnail`)+ .exists("cards show a preview built from the theme palette");+ assert+ .dom(`.theme-card[data-theme-id="live"] .theme-card__badge`)+ .includesText("Active", "the live design is badged");+ assert+ .dom(`.theme-card[data-theme-id="candidate"] .theme-card__badge`)+ .includesText("Local edits", "local Git edits are badged");+ assert+ .dom(`.theme-card[data-theme-id="live"] .theme-card__description`)+ .includesText("Draft revision 2", "the card names the saved revision");+ await click(+ `.theme-card[data-theme-id="candidate"] .theme-card__footer-menu`+ );+ assert+ .dom(+ '[data-identifier="blog-theme-actions-candidate"] .theme-card__button'+ )+ .exists(+ { count: 4 },+ "a Git design offers activate, pull, preview, and delete"+ );+ assert+ .dom(+ '[data-identifier="blog-theme-actions-candidate"] .d-icon-cloud-arrow-down'+ )+ .exists("its Git source can be pulled");+ assert+ .dom('[data-identifier="blog-theme-actions-candidate"] .preview')+ .hasAttribute(+ "href",+ draft.preview_url,+ "the saved revision can be previewed without activating it"+ );++ await click(`.theme-card[data-theme-id="live"] .theme-card__footer-menu`);+ assert+ .dom('[data-identifier="blog-theme-actions-live"] .theme-card__button')+ .exists({ count: 3 }, "a design without a Git source cannot be pulled");+ assert+ .dom('[data-identifier="blog-theme-actions-live"] .preview')+ .exists("the live design keeps a useful action");+ assert+ .dom(+ '[data-identifier="blog-theme-actions-live"] .d-icon-cloud-arrow-down'+ )+ .doesNotExist("its menu has no pull item");+ assert+ .dom('[data-identifier="blog-theme-actions-live"] .d-icon-play')+ .exists("activation stays available");+ assert+ .dom(`.theme-card[data-theme-id="live"] .theme-card__footer-menu`)+ .exists("the menu belongs to the card it was opened from");+ });++ test("activating from a card confirms first and reloads the list", async function (assert) {+ let listLoads = 0;+ pretender.get("/admin/plugins/blog/themes.json", () => {+ listLoads++;+ return response({ themes: [active, draft], active });+ });+ pretender.post("/admin/plugins/blog/themes/candidate/activate.json", () => {+ assert.step("activated");+ return response(draft);+ });++ await visit("/admin/plugins/blog/themes");+ await click(+ `.theme-card[data-theme-id="candidate"] .theme-card__footer-menu`+ );+ const loadsBeforeActivating = listLoads;+ await click(+ '[data-identifier="blog-theme-actions-candidate"] .theme-card__button:not([disabled])'+ );+ assert.verifySteps([], "opening the confirmation changes nothing");+ await click(".dialog-footer .btn-primary");+ assert.verifySteps(["activated"], "confirming activates the design");+ assert.true(+ listLoads > loadsBeforeActivating,+ "the list reloads after activating"+ );+ });++ test("pulling from a card refreshes the design and its badges", async function (assert) {+ let theme = {+ ...draft,+ source: {+ repository: "https://example.com/blog-theme.git",+ branch: "main",+ commit: "abc1234",+ },+ locally_modified: true,+ };+ pretender.get("/admin/plugins/blog/themes.json", () =>+ response({ themes: [active, theme], active })+ );+ pretender.post(+ "/admin/plugins/blog/themes/candidate/pull.json",+ (request) => {+ assert.strictEqual(+ new URLSearchParams(request.requestBody).get("revision"),+ "1",+ "the saved revision is pulled"+ );+ assert.step("pulled");+ theme = { ...theme, locally_modified: false, revision: 2 };+ return response(theme);+ }+ );++ await visit("/admin/plugins/blog/themes");+ assert+ .dom(`.theme-card[data-theme-id="candidate"] .theme-card__badge`)+ .includesText("Local edits", "local edits are flagged before pulling");++ await click(+ `.theme-card[data-theme-id="candidate"] .theme-card__footer-menu`+ );+ await click(+ '[data-identifier="blog-theme-actions-candidate"] .d-icon-cloud-arrow-down'+ );+ await click(".dialog-footer .btn-primary");+ assert.verifySteps(["pulled"], "confirming pulls the latest commit");+ assert+ .dom(`.theme-card[data-theme-id="candidate"] .theme-card__badge`)+ .doesNotExist("the badge clears once the list reloads");+ });++ test("preserves the old appearance URL as a redirect to themes", async function (assert) {+ await visit("/admin/plugins/blog/appearance");+ assert.strictEqual(+ currentURL(),+ "/admin/plugins/blog/themes",+ "old bookmarks open the themes index"+ );+ });+});diff --git a/plugins/blog/test/javascripts/unit/blog-discussion-resize-test.js b/plugins/blog/test/javascripts/unit/blog-discussion-resize-test.jsnew file mode 100644index 00000000000..78e82a3f024--- /dev/null+++ b/plugins/blog/test/javascripts/unit/blog-discussion-resize-test.js@@ -0,0 +1,104 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import EmbedMode from "discourse/lib/embed-mode";+import initializer from "discourse/plugins/blog/discourse/initializers/blog-discussion-resize";++module("Unit | Initializer | blog-discussion-resize", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.sandbox = sinon.createSandbox();+ this.embedEnabled = EmbedMode.enabled;+ this.hadClass = document.documentElement.classList.contains(+ "discourse-blog-discussion"+ );+ EmbedMode.enabled = true;+ document.documentElement.classList.add("discourse-blog-discussion");+ const settings = this.owner.lookup("service:site-settings");+ settings.blog_enabled = true;+ this.owner.lookup("service:site").blog_base_url =+ "https://blog.example.com";+ });++ hooks.afterEach(function () {+ initializer.teardown();+ this.sandbox.restore();+ EmbedMode.enabled = this.embedEnabled;+ document.documentElement.classList.toggle(+ "discourse-blog-discussion",+ this.hadClass+ );+ });++ test("leaves the embed unmanaged when the blog URL is unusable", function (assert) {+ this.owner.lookup("service:site").blog_base_url = "not a url";+ const observe = this.sandbox.stub();+ this.sandbox.stub(window, "ResizeObserver").callsFake(() => ({+ observe,+ disconnect() {},+ }));++ initializer.initialize(this.owner);++ assert.true(+ observe.notCalled,+ "no observer without a usable parent origin"+ );+ });++ test("continues sizing beyond the initial notifications and cleans up", function (assert) {+ let resize;+ const disconnect = this.sandbox.spy();+ const element = {+ scrollHeight: 1800,+ getBoundingClientRect: () => ({ height: 1800.3 }),+ };+ this.sandbox+ .stub(document, "getElementById")+ .withArgs("main")+ .returns(element);+ this.sandbox.stub(window, "ResizeObserver").callsFake(function (callback) {+ resize = callback;+ return {+ observe: (target, options) => {+ assert.deepEqual(+ options,+ { box: "border-box" },+ "composer padding and border changes trigger resizing"+ );+ },+ disconnect,+ };+ });+ this.sandbox.stub(window, "requestAnimationFrame").callsFake((callback) => {+ callback();+ return 1;+ });+ this.sandbox.stub(window, "cancelAnimationFrame");+ const postMessage = this.sandbox.stub(window.parent, "postMessage");++ initializer.initialize(this.owner);+ for (let index = 0; index < 12; index++) {+ element.scrollHeight += 20;+ resize();+ }+ resize();++ assert.strictEqual(+ postMessage.callCount,+ 12,+ "sizing remains active and unchanged heights are skipped"+ );+ assert.deepEqual(+ postMessage.lastCall.args,+ [+ { type: "discourse-blog-resize", height: 2040 },+ "https://blog.example.com",+ ],+ "height is sent only to the configured parent origin"+ );+ initializer.teardown();+ assert.true(disconnect.calledOnce, "the observer disconnects on teardown");+ });+});diff --git a/plugins/blog/test/javascripts/unit/blog-discussion-test.js b/plugins/blog/test/javascripts/unit/blog-discussion-test.jsnew file mode 100644index 00000000000..44f4ff1558b--- /dev/null+++ b/plugins/blog/test/javascripts/unit/blog-discussion-test.js@@ -0,0 +1,170 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import EmbedMode from "discourse/lib/embed-mode";+import initializer from "discourse/plugins/blog/discourse/initializers/blog-discussion";++const BLOG_ORIGIN = "https://blog.example.com";+const PALETTE = { accent: "#d64b2a", paper: "#f5f0e6", ink: "#19382d" };++module("Unit | Initializer | blog-discussion", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.originalEmbedMode = EmbedMode.enabled;+ this.root = document.documentElement;+ this.originalStyle = this.root.getAttribute("style");+ this.hadClass = this.root.classList.contains("discourse-blog-discussion");+ this.settings = this.owner.lookup("service:site-settings");+ this.settings.blog_enabled = true;+ this.site = this.owner.lookup("service:site");+ this.site.blog_base_url = BLOG_ORIGIN;+ for (const color of ["accent", "paper", "ink"]) {+ this.root.style.removeProperty(`--blog-${color}-color`);+ }+ });++ hooks.afterEach(function () {+ EmbedMode.enabled = this.originalEmbedMode;+ this.root.classList.toggle("discourse-blog-discussion", this.hadClass);+ if (this.originalStyle === null) {+ this.root.removeAttribute("style");+ } else {+ this.root.setAttribute("style", this.originalStyle);+ }+ });++ function sendPalette({ origin = BLOG_ORIGIN, ...palette } = {}) {+ window.dispatchEvent(+ new MessageEvent("message", {+ origin,+ data: { type: "discourse-blog-palette", ...PALETTE, ...palette },+ })+ );+ }++ test("applies the palette the blog sends with the embedded conversation", function (assert) {+ EmbedMode.enabled = true;+ this.root.classList.add("discourse-blog-discussion");+ initializer.initialize(this.owner);++ sendPalette();++ for (const color of ["accent", "paper", "ink"]) {+ assert.strictEqual(+ this.root.style.getPropertyValue(`--blog-${color}-color`),+ PALETTE[color],+ `the blog ${color} color styles the conversation`+ );+ }+ });++ test("ignores a palette from another origin", function (assert) {+ EmbedMode.enabled = true;+ this.root.classList.add("discourse-blog-discussion");+ initializer.initialize(this.owner);++ sendPalette({ origin: "https://example.com", paper: "#000000" });++ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-paper-color"),+ "",+ "only the configured blog may restyle the conversation"+ );+ });++ test("ignores palette values that are not colors", function (assert) {+ EmbedMode.enabled = true;+ this.root.classList.add("discourse-blog-discussion");+ initializer.initialize(this.owner);++ sendPalette({ paper: "url(https://example.com/pixel)" });++ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-paper-color"),+ "",+ "unexpected values never reach the stylesheet"+ );+ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-accent-color"),+ "",+ "a partly invalid palette is refused whole"+ );+ });++ test("restores styling after an iframe-only reload loses the server class", function (assert) {+ EmbedMode.enabled = true;+ this.root.classList.remove("discourse-blog-discussion");+ const previousURL = window.location.href;+ try {+ window.history.replaceState(+ null,+ "",+ "?class_name=discourse-blog-discussion"+ );+ initializer.initialize(this.owner);+ assert.true(+ this.root.classList.contains("discourse-blog-discussion"),+ "the layout scope is restored from the embed URL"+ );++ sendPalette();+ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-paper-color"),+ PALETTE.paper,+ "the blog palette still arrives"+ );+ } finally {+ window.history.replaceState(null, "", previousURL);+ }+ });++ test("leaves ordinary forum pages unchanged", function (assert) {+ EmbedMode.enabled = false;+ this.root.classList.add("discourse-blog-discussion");+ initializer.initialize(this.owner);+ sendPalette();+ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-paper-color"),+ "",+ "a class alone cannot activate the palette"+ );+ });++ test("leaves other embeds unchanged", function (assert) {+ EmbedMode.enabled = true;+ this.root.classList.remove("discourse-blog-discussion");+ initializer.initialize(this.owner);+ sendPalette();+ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-paper-color"),+ "",+ "other embedding sites retain the forum palette"+ );+ });++ test("does not apply the palette when the blog is disabled", function (assert) {+ EmbedMode.enabled = true;+ this.root.classList.add("discourse-blog-discussion");+ this.settings.blog_enabled = false;+ initializer.initialize(this.owner);+ sendPalette();+ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-paper-color"),+ "",+ "disabled blogs do not initialize the palette"+ );+ });++ test("ignores palette messages without a usable blog URL", function (assert) {+ EmbedMode.enabled = true;+ this.root.classList.add("discourse-blog-discussion");+ this.site.blog_base_url = "";+ initializer.initialize(this.owner);+ sendPalette();+ assert.strictEqual(+ this.root.style.getPropertyValue("--blog-paper-color"),+ "",+ "without a configured blog there is no origin to trust"+ );+ });+});diff --git a/plugins/blog/test/javascripts/unit/blog-origin-test.js b/plugins/blog/test/javascripts/unit/blog-origin-test.jsnew file mode 100644index 00000000000..330cb761569--- /dev/null+++ b/plugins/blog/test/javascripts/unit/blog-origin-test.js@@ -0,0 +1,21 @@+import { module, test } from "qunit";+import blogOrigin from "discourse/plugins/blog/discourse/lib/blog-origin";++module("Unit | Lib | blog-origin", function () {+ test("returns the origin of the configured blog URL", function (assert) {+ assert.strictEqual(+ blogOrigin("https://blog.example.com/some/path"),+ "https://blog.example.com"+ );+ });++ test("returns null for values that cannot be parsed", function (assert) {+ assert.strictEqual(blogOrigin(""), null, "a blank setting has no origin");+ assert.strictEqual(+ blogOrigin("blog.example.com"),+ null,+ "a scheme-less host"+ );+ assert.strictEqual(blogOrigin(undefined), null, "an unset setting");+ });+});diff --git a/plugins/blog/tsconfig.json b/plugins/blog/tsconfig.jsonnew file mode 100644index 00000000000..52976040160--- /dev/null+++ b/plugins/blog/tsconfig.json@@ -0,0 +1,25 @@+{+ "extends": "discourse/tsconfig-plugin",+ "include": [+ "admin/assets/javascripts/**/*",+ "assets/javascripts/**/*",+ "test/javascripts/**/*"+ ],+ "compilerOptions": {+ "paths": {+ "discourse/plugins/blog/*": [+ "./assets/javascripts/*",+ "./assets/javascripts/*.gjs",+ "./assets/javascripts/*.gts",+ "./test/javascripts/*",+ "./test/javascripts/*.gjs",+ "./test/javascripts/*.gts"+ ]+ }+ },+ "references": [+ {+ "path": "../../frontend/discourse"+ }+ ]+}diff --git a/plugins/blog/vendor/highlightjs/LICENSE b/plugins/blog/vendor/highlightjs/LICENSEnew file mode 100644index 00000000000..2250cc7eca9--- /dev/null+++ b/plugins/blog/vendor/highlightjs/LICENSE@@ -0,0 +1,29 @@+BSD 3-Clause License++Copyright (c) 2006, Ivan Sagalaev.+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++* Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/plugins/blog/vendor/highlightjs/README.md b/plugins/blog/vendor/highlightjs/README.mdnew file mode 100644index 00000000000..1c14379f10d--- /dev/null+++ b/plugins/blog/vendor/highlightjs/README.md@@ -0,0 +1,22 @@+# Reader syntax-highlighting module++`core.min.js` is the unmodified ES module from `@highlightjs/cdn-assets` version+11.12.0, distributed under the accompanying BSD-3-Clause `LICENSE`.++This file is shipped with the plugin so the reader can serve it without production+`node_modules` or changes to core's runtime asset packaging. Language registrations+continue to come from core's `/highlight-js/` endpoint and respect the site's+configured languages.++When core upgrades its highlighting dependency, refresh this module and license+from the matching installed dependency, from the Discourse project root:++```sh+cp frontend/discourse/node_modules/@highlightjs/cdn-assets/es/core.min.js plugins/blog/vendor/highlightjs/core.min.js+cp frontend/discourse/node_modules/@highlightjs/cdn-assets/LICENSE plugins/blog/vendor/highlightjs/LICENSE+node --test plugins/blog/test/browser/*.test.mjs+bin/rspec plugins/blog/spec/requests/syntax_highlighter_spec.rb+```++Update the version above. Preserve the upstream file rather than formatting or+editing it; the served asset URL is derived from its content digest.diff --git a/plugins/blog/vendor/highlightjs/core.min.js b/plugins/blog/vendor/highlightjs/core.min.jsnew file mode 100644index 00000000000..896cdc72a0d--- /dev/null+++ b/plugins/blog/vendor/highlightjs/core.min.js@@ -0,0 +1,305 @@+/*!+ Highlight.js v11.12.0 (git: f7f7d3803b)+ (c) 2006-2026 Josh Goebel <[email protected]> and other contributors+ License: BSD-3-Clause+ */+function e(t){return t instanceof Map?t.clear=t.delete=t.set=()=>{+throw Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=()=>{+throw Error("set is read-only")+}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{+const i=t[n],s=typeof i;"object"!==s&&"function"!==s||Object.isFrozen(i)||e(i)+}),t}class t{constructor(e){+void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}+ignoreMatch(){this.isMatchIgnored=!0}}function n(e){+return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")+}function i(e,...t){const n=Object.create(null);for(const t in e)n[t]=e[t]+;return t.forEach(e=>{for(const t in e)n[t]=e[t]}),n}const s=e=>!!e.scope+;class r{constructor(e,t){+this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){+this.buffer+=n(e)}openNode(e){if(!s(e))return;const t=((e,{prefix:t})=>{+if(e.startsWith("language:"))return e.replace("language:","language-")+;if(e.includes(".")){const n=e.split(".")+;return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}+return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){+s(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){+this.buffer+=`<span class="${e}">`}}const o=(e={})=>{const t={children:[]}+;return Object.assign(t,e),t};class a{constructor(){+this.rootNode=o(),this.stack=[this.rootNode]}get top(){+return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){+this.top.children.push(e)}openNode(e){const t=o({scope:e})+;this.add(t),this.stack.push(t)}closeNode(){+if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){+for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}+walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){+return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),+t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){+"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{+a._collapse(e)}))}}class c extends a{constructor(e){super(),this.options=e}+addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){+this.closeNode()}__addSublanguage(e,t){const n=e.root+;t&&(n.scope="language:"+t),this.add(n)}toHTML(){+return new r(this,this.options).value()}finalize(){+return this.closeAllNodes(),!0}}function l(e){+return e?"string"==typeof e?e:e.source:null}function g(e){return h("(?=",e,")")}+function u(e){return h("(?:",e,")*")}function d(e){return h("(?:",e,")?")}+function h(...e){return e.map(e=>l(e)).join("")}function f(...e){const t=(e=>{+const t=e[e.length-1]+;return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}+})(e);return"("+(t.capture?"":"?:")+e.map(e=>l(e)).join("|")+")"}function p(e){+return RegExp(e.toString()+"|").exec("").length-1}+const b=RegExp(f(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./))+;function m(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n+;let i=l(e),s="";for(;i.length>0;){const e=b.exec(i);if(!e){s+=i;break}+s+=i.substring(0,e.index),+i=i.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?s+="\\"+(Number(e[1])+t):(s+=e[0],+("("===e[0]||/^\(\?[<']/.test(e[0]))&&n++)}return s}).map(e=>`(${e})`).join(t)}+const E="[a-zA-Z]\\w*",x="[a-zA-Z_]\\w*",_="\\b\\d+(\\.\\d+)?",y="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",w="\\b(0b[01]+)",O={+begin:"\\\\[\\s\\S]",relevance:0},k={scope:"string",begin:"'",end:"'",+illegal:"\\n",contains:[O]},N={scope:"string",begin:'"',end:'"',illegal:"\\n",+contains:[O]},S=(e,t,n={})=>{const s=i({scope:"comment",begin:e,end:t,+contains:[]},n);s.contains.push({scope:"doctag",+begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",+end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0})+;const r=f("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/)+;return s.contains.push({begin:h(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),s+},v=S("//","$"),M=S("/\\*","\\*/"),R=S("#","$");var A=Object.freeze({+__proto__:null,APOS_STRING_MODE:k,BACKSLASH_ESCAPE:O,BINARY_NUMBER_MODE:{+scope:"number",begin:w,relevance:0},BINARY_NUMBER_RE:w,COMMENT:S,+C_BLOCK_COMMENT_MODE:M,C_LINE_COMMENT_MODE:v,C_NUMBER_MODE:{scope:"number",+begin:y,relevance:0},C_NUMBER_RE:y,END_SAME_AS_BEGIN:e=>Object.assign(e,{+"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{+t.data._beginMatch!==e[1]&&t.ignoreMatch()}}),HASH_COMMENT_MODE:R,IDENT_RE:E,+MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:{begin:"\\.\\s*"+x,relevance:0},+NUMBER_MODE:{scope:"number",begin:_,relevance:0},NUMBER_RE:_,+PHRASAL_WORDS_MODE:{+begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/+},QUOTE_STRING_MODE:N,REGEXP_MODE:{scope:"regexp",begin:/\/(?=[^/\n]*\/)/,+end:/\/[gimuy]*/,contains:[O,{begin:/\[/,end:/\]/,relevance:0,contains:[O]}]},+RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",+SHEBANG:(e={})=>{const t=/^#![ ]*\//+;return e.binary&&(e.begin=h(t,/.*\b/,e.binary,/\b.*/)),i({scope:"meta",begin:t,+end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},+TITLE_MODE:{scope:"title",begin:E,relevance:0},UNDERSCORE_IDENT_RE:x,+UNDERSCORE_TITLE_MODE:{scope:"title",begin:x,relevance:0}});function j(e,t){+"."===e.input[e.index-1]&&t.ignoreMatch()}function I(e,t){+void 0!==e.className&&(e.scope=e.className,delete e.className)}function T(e,t){+t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",+e.__beforeBegin=j,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,+void 0===e.relevance&&(e.relevance=0))}function L(e,t){+Array.isArray(e.illegal)&&(e.illegal=f(...e.illegal))}function B(e,t){+if(e.match){+if(e.begin||e.end)throw Error("begin & end are not supported with match")+;e.begin=e.match,delete e.match}}function P(e,t){+void 0===e.relevance&&(e.relevance=1)}const D=(e,t)=>{if(!e.beforeMatch)return+;if(e.starts)throw Error("beforeMatch cannot be used with starts")+;const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]+}),e.keywords=n.keywords,e.begin=h(n.beforeMatch,g(n.begin)),e.starts={+relevance:0,contains:[Object.assign(n,{endsParent:!0})]+},e.relevance=0,delete n.beforeMatch+},H=["of","and","for","in","not","or","if","then","parent","list","value"]+;function C(e,t,n="keyword"){const i=Object.create(null)+;return"string"==typeof e?s(n,e.split(" ")):Array.isArray(e)?s(n,e):Object.keys(e).forEach(n=>{+Object.assign(i,C(e[n],t,n))}),i;function s(e,n){+t&&(n=n.map(e=>e.toLowerCase())),n.forEach(t=>{const n=t.split("|")+;i[n[0]]=[e,$(n[0],n[1])]})}}function $(e,t){+return t?Number(t):(e=>H.includes(e.toLowerCase()))(e)?0:1}const U={},z=e=>{+console.error(e)},W=(e,...t)=>{console.log("WARN: "+e,...t)},X=(e,t)=>{+U[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),U[`${e}/${t}`]=!0)+},G=Error();function K(e,t,{key:n}){let i=0;const s=e[n],r={},o={}+;for(let e=1;e<=t.length;e++)o[e+i]=s[e],r[e+i]=!0,i+=p(t[e-1])+;e[n]=o,e[n]._emit=r,e[n]._multi=!0}function F(e){(e=>{+e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,+delete e.scope)})(e),"string"==typeof e.beginScope&&(e.beginScope={+_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope+}),(e=>{if(Array.isArray(e.begin)){+if(e.skip||e.excludeBegin||e.returnBegin)throw z("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),+G+;if("object"!=typeof e.beginScope||null===e.beginScope)throw z("beginScope must be object"),+G;K(e,e.begin,{key:"beginScope"}),e.begin=m(e.begin,{joinWith:""})}})(e),(e=>{+if(Array.isArray(e.end)){+if(e.skip||e.excludeEnd||e.returnEnd)throw z("skip, excludeEnd, returnEnd not compatible with endScope: {}"),+G+;if("object"!=typeof e.endScope||null===e.endScope)throw z("endScope must be object"),+G;K(e,e.end,{key:"endScope"}),e.end=m(e.end,{joinWith:""})}})(e)}function Z(e){+function t(t,n){+return RegExp(l(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))+}class n{constructor(){+this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}+addRule(e,t){+t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),+this.matchAt+=p(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null)+;const e=this.regexes.map(e=>e[1]);this.matcherRe=t(m(e,{joinWith:"|"+}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex+;const t=this.matcherRe.exec(e);if(!t)return null+;const n=t.findIndex((e,t)=>t>0&&void 0!==e),i=this.matchIndexes[n]+;return t.splice(0,n),Object.assign(t,i)}}class s{constructor(){+this.rules=[],this.multiRegexes=[],+this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){+if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n+;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),+t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){+return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){+this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){+const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex+;let n=t.exec(e)+;if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else{+const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}+return n&&(this.regexIndex+=n.position+1,+this.regexIndex===this.count&&this.considerAll()),n}}+if(e.compilerExtensions||(e.compilerExtensions=[]),+e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.")+;return e.classNameAliases=i(e.classNameAliases||{}),function n(r,o){const a=r+;if(r.isCompiled)return a+;[I,B,F,D].forEach(e=>e(r,o)),e.compilerExtensions.forEach(e=>e(r,o)),+r.__beforeBegin=null,[T,L,P].forEach(e=>e(r,o)),r.isCompiled=!0;let c=null+;return"object"==typeof r.keywords&&r.keywords.$pattern&&(r.keywords=Object.assign({},r.keywords),+c=r.keywords.$pattern,+delete r.keywords.$pattern),c=c||/\w+/,r.keywords&&(r.keywords=C(r.keywords,e.case_insensitive)),+a.keywordPatternRe=t(c,!0),+o&&(r.begin||(r.begin=/\B|\b/),a.beginRe=t(a.begin),r.end||r.endsWithParent||(r.end=/\B|\b/),+r.end&&(a.endRe=t(a.end)),+a.terminatorEnd=l(a.end)||"",r.endsWithParent&&o.terminatorEnd&&(a.terminatorEnd+=(r.end?"|":"")+o.terminatorEnd)),+r.illegal&&(a.illegalRe=t(r.illegal)),+r.contains||(r.contains=[]),r.contains=[].concat(...r.contains.map(e=>(e=>(e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(t=>i(e,{+variants:null},t))),e.cachedVariants?e.cachedVariants:V(e)?i(e,{+starts:e.starts?i(e.starts):null+}):Object.isFrozen(e)?i(e):e))("self"===e?r:e))),r.contains.forEach(e=>{n(e,a)+}),r.starts&&n(r.starts,o),a.matcher=(e=>{const t=new s+;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"+})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"+}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t})(a),a}(e)}function V(e){+return!!e&&(e.endsWithParent||V(e.starts))}class q extends Error{+constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}+const J=n,Y=i,Q=Symbol("nomatch"),ee=n=>{+const i=Object.create(null),s=Object.create(null),r=[];let o=!0+;const a="Could not find the language '{}', did you forget to load/include a language module?",l={+disableAutodetect:!0,name:"Plain text",contains:[]};let p={+ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,+languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",+cssSelector:"pre code",languages:null,__emitter:c};function b(e){+return p.noHighlightRe.test(e)}function m(e,t,n){let i="",s=""+;"object"==typeof t?(i=e,+n=t.ignoreIllegals,s=t.language):(X("10.7.0","highlight(lang, code, ...args) has been deprecated."),+X("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),+s=e,i=t),void 0===n&&(n=!0);const r={code:i,language:s};S("before:highlight",r)+;const o=r.result?r.result:E(r.language,r.code,n)+;return o.code=r.code,S("after:highlight",o),o}function E(e,n,s,r){+const c=Object.create(null);function l(e,t){return e.keywords[t]}function g(){+if(!v.keywords)return void R.addText(A);let e=0;v.keywordPatternRe.lastIndex=0+;let t=v.keywordPatternRe.exec(A),n="";for(;t;){n+=A.substring(e,t.index)+;const i=k.case_insensitive?t[0].toLowerCase():t[0],s=l(v,i);if(s){const[e,r]=s+;if(R.addText(n),+n="",c[i]=(c[i]||0)+1,c[i]<=7&&(j+=r),e.startsWith("_"))n+=t[0];else{+const n=k.classNameAliases[e]||e;d(t[0],n)}}else n+=t[0]+;e=v.keywordPatternRe.lastIndex,t=v.keywordPatternRe.exec(A)}+n+=A.substring(e),R.addText(n)}function u(){null!=v.subLanguage?(()=>{+if(""===A)return;let e=null;if("string"==typeof v.subLanguage){+if(!i[v.subLanguage])return void R.addText(A)+;e=E(v.subLanguage,A,!0,M[v.subLanguage]),M[v.subLanguage]=e._top+}else e=x(A,v.subLanguage.length?v.subLanguage:null)+;v.relevance>0&&(j+=e.relevance),R.__addSublanguage(e._emitter,e.language)+})():g(),A=""}function d(e,t){+""!==e&&(R.startScope(t),R.addText(e),R.endScope())}function h(e,t){let n=1+;const i=t.length-1;for(;n<=i;){if(!e._emit[n]){n++;continue}+const i=k.classNameAliases[e[n]]||e[n],s=t[n];i?d(s,i):(A=s,g(),A=""),n++}}+function f(e,t){+return e.scope&&"string"==typeof e.scope&&R.openNode(k.classNameAliases[e.scope]||e.scope),+e.beginScope&&(e.beginScope._wrap?(d(A,k.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),+A=""):e.beginScope._multi&&(h(e.beginScope,t),A="")),v=Object.create(e,{parent:{+value:v}}),v}function b(e,n,i){let s=((e,t)=>{const n=e&&e.exec(t)+;return n&&0===n.index})(e.endRe,i);if(s){if(e["on:end"]){const i=new t(e)+;e["on:end"](n,i),i.isMatchIgnored&&(s=!1)}if(s){+for(;e.endsParent&&e.parent;)e=e.parent;return e}}+if(e.endsWithParent)return b(e.parent,n,i)}function m(e){+return 0===v.matcher.regexIndex?(A+=e[0],1):(L=!0,0)}function _(e){+const t=e[0],i=n.substring(e.index),s=b(v,e,i);if(!s)return Q;const r=v+;v.endScope&&v.endScope._wrap?(u(),+d(t,v.endScope._wrap)):v.endScope&&v.endScope._multi?(u(),+h(v.endScope,e)):r.skip?A+=t:(r.returnEnd||r.excludeEnd||(A+=t),+u(),r.excludeEnd&&(A=t));do{+v.scope&&R.closeNode(),v.skip||v.subLanguage||(j+=v.relevance),v=v.parent+}while(v!==s.parent);return s.starts&&f(s.starts,e),r.returnEnd?0:t.length}+let y={};function w(i,r){const a=r&&r[0];if(A+=i,null==a)return u(),0+;if("begin"===y.type&&"end"===r.type&&y.index===r.index&&""===a){+if(A+=n.slice(r.index,r.index+1),!o){const t=Error(`0 width match regex (${e})`)+;throw t.languageName=e,t.badRule=y.rule,t}return 1}+if(y=r,"begin"===r.type)return(e=>{+const n=e[0],i=e.rule,s=new t(i),r=[i.__beforeBegin,i["on:begin"]]+;for(const t of r)if(t&&(t(e,s),s.isMatchIgnored))return m(n)+;return i.skip?A+=n:(i.excludeBegin&&(A+=n),+u(),i.returnBegin||i.excludeBegin||(A=n)),f(i,e),i.returnBegin?0:n.length})(r)+;if("illegal"===r.type&&!s){+const e=Error('Illegal lexeme "'+a+'" for mode "'+(v.scope||"<unnamed>")+'"')+;throw e.mode=v,e}if("end"===r.type){const e=_(r);if(e!==Q)return e}+if("illegal"===r.type&&""===a)return r.index===n.length||(A+="\n"),1+;if(T>1e5&&T>3*r.index)throw Error("potential infinite loop, way more iterations than matches")+;return A+=a,a.length}const k=O(e)+;if(!k)throw z(a.replace("{}",e)),Error('Unknown language: "'+e+'"')+;const N=Z(k);let S="",v=r||N;const M={},R=new p.__emitter(p);(()=>{const e=[]+;for(let t=v;t!==k;t=t.parent)t.scope&&e.unshift(t.scope)+;e.forEach(e=>R.openNode(e))})();let A="",j=0,I=0,T=0,L=!1;try{+if(k.__emitTokens)k.__emitTokens(n,R);else{for(v.matcher.considerAll();;){+T++,L?L=!1:v.matcher.considerAll(),v.matcher.lastIndex=I+;const e=v.matcher.exec(n);if(!e)break;const t=w(n.substring(I,e.index),e)+;I=e.index+t}w(n.substring(I))}return R.finalize(),S=R.toHTML(),{language:e,+value:S,relevance:j,illegal:!1,_emitter:R,_top:v}}catch(t){+if(t.message&&t.message.includes("Illegal"))return{language:e,value:J(n),+illegal:!0,relevance:0,_illegalBy:{message:t.message,index:I,+context:n.slice(I-100,I+100),mode:t.mode,resultSoFar:S},_emitter:R};if(o)return{+language:e,value:J(n),illegal:!1,relevance:0,errorRaised:t,_emitter:R,_top:v}+;throw t}}function x(e,t){t=t||p.languages||Object.keys(i);const n=(e=>{+const t={value:J(e),illegal:!1,relevance:0,_top:l,_emitter:new p.__emitter(p)}+;return t._emitter.addText(e),t})(e),s=t.filter(O).filter(N).map(t=>E(t,e,!1))+;s.unshift(n);const r=s.sort((e,t)=>{+if(e.relevance!==t.relevance)return t.relevance-e.relevance+;if(e.language&&t.language){if(O(e.language).supersetOf===t.language)return 1+;if(O(t.language).supersetOf===e.language)return-1}return 0}),[o,a]=r,c=o+;return c.secondBest=a,c}function _(e){let t=null;const n=(e=>{+let t=e.className+" ";t+=e.parentNode?e.parentNode.className:""+;const n=p.languageDetectRe.exec(t);if(n){const t=O(n[1])+;return t||(W(a.replace("{}",n[1])),+W("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}+return t.split(/\s+/).find(e=>b(e)||O(e))})(e);if(b(n))return+;if(S("before:highlightElement",{el:e,language:n+}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e)+;if(e.children.length>0&&(p.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),+console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),+console.warn("The element with unescaped HTML:"),+console.warn(e)),p.throwUnescapedHTML))throw new q("One of your code blocks includes unescaped HTML.",e.innerHTML)+;t=e;const i=t.textContent,r=n?m(i,{language:n,ignoreIllegals:!0}):x(i)+;e.innerHTML=r.value,e.dataset.highlighted="yes",((e,t,n)=>{const i=t&&s[t]||n+;e.classList.add("hljs"),e.classList.add("language-"+i)+})(e,n,r.language),e.result={language:r.language,re:r.relevance,+relevance:r.relevance},r.secondBest&&(e.secondBest={+language:r.secondBest.language,relevance:r.secondBest.relevance+}),S("after:highlightElement",{el:e,result:r,text:i})}let y=!1;function w(){+if("loading"===document.readyState)return y||window.addEventListener("DOMContentLoaded",()=>{+w()},!1),void(y=!0);document.querySelectorAll(p.cssSelector).forEach(_)}+function O(e){return e=(e||"").toLowerCase(),i[e]||i[s[e]]}+function k(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{+s[e.toLowerCase()]=t})}function N(e){const t=O(e);return t&&!t.disableAutodetect+}function S(e,t){const n=e;r.forEach(e=>{e[n]&&e[n](t)})}Object.assign(n,{+highlight:m,highlightAuto:x,highlightAll:w,highlightElement:_,+highlightBlock:e=>(X("10.7.0","highlightBlock will be removed entirely in v12.0"),+X("10.7.0","Please use highlightElement now."),_(e)),configure:e=>{p=Y(p,e)},+initHighlighting:()=>{+w(),X("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},+initHighlightingOnLoad:()=>{+w(),X("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")+},registerLanguage:(e,t)=>{let s=null;try{s=t(n)}catch(t){+if(z("Language definition for '{}' could not be registered.".replace("{}",e)),+!o)throw t;z(t),s=l}+s.name||(s.name=e),i[e]=s,s.rawDefinition=t.bind(null,n),s.aliases&&k(s.aliases,{+languageName:e})},unregisterLanguage:e=>{delete i[e]+;for(const t of Object.keys(s))s[t]===e&&delete s[t]},+listLanguages:()=>Object.keys(i),getLanguage:O,registerAliases:k,+autoDetection:N,inherit:Y,addPlugin:e=>{(e=>{+e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{+e["before:highlightBlock"](Object.assign({block:t.el},t))+}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{+e["after:highlightBlock"](Object.assign({block:t.el},t))})})(e),r.push(e)},+removePlugin:e=>{const t=r.indexOf(e);-1!==t&&r.splice(t,1)}}),n.debugMode=()=>{+o=!1},n.safeMode=()=>{o=!0},n.versionString="11.12.0",n.regex={concat:h,+lookahead:g,either:f,optional:d,anyNumberOfTimes:u}+;for(const t in A)"object"==typeof A[t]&&e(A[t]);return Object.assign(n,A),n+},te=ee({});te.newInstance=()=>ee({});export{te as default};\ No newline at end of filediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 55c12bb8251..64fc7968542 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -899,6 +899,12 @@ importers:specifier: workspace:@discourse/types@*version: link:../../frontend/discourse-types+ plugins/blog:+ dependencies:+ discourse:+ specifier: workspace:@discourse/types@*+ version: link:../../frontend/discourse-types+plugins/boards:dependencies:discourse:diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex bf66c5fa85b..97a0df5d61e 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -31,6 +31,7 @@ packages:- "frontend/discourse-types"- "frontend/playwright-runner"- "plugins/automation"+- "plugins/blog"- "plugins/boards"- "plugins/chat"- "plugins/checklist"diff --git a/spec/lib/plugin/metadata_spec.rb b/spec/lib/plugin/metadata_spec.rbindex bbabc005eeb..d457db3df3d 100644--- a/spec/lib/plugin/metadata_spec.rb+++ b/spec/lib/plugin/metadata_spec.rb@@ -50,6 +50,7 @@ TEXTofficial("discourse-akismet")official("discourse-cakeday")official("discourse-data-explorer")+ official("blog")official("boards")unofficial("babble")enddiff --git a/translator.yml b/translator.ymlindex a6626b2ecf5..ac1467230cb 100644--- a/translator.yml+++ b/translator.yml@@ -24,6 +24,13 @@ files:destination_path: error_pages/503.htmllabel: core+ - source_path: plugins/blog/config/locales/client.en.yml+ destination_path: plugins/blog/client.yml+ label: blog+ - source_path: plugins/blog/config/locales/server.en.yml+ destination_path: plugins/blog/server.yml+ label: blog+- source_path: plugins/boards/config/locales/client.en.ymldestination_path: plugins/boards/client.ymllabel: boardsdiff --git a/tsconfig.json b/tsconfig.jsonindex b6a14a1d99e..1552339c0e0 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -3,6 +3,7 @@{ "path": "frontend/discourse" },{ "path": "frontend/discourse-i18n" },{ "path": "plugins/automation" },+ { "path": "plugins/blog" },{ "path": "plugins/boards" },{ "path": "plugins/chat" },{ "path": "plugins/checklist" },