Test widget.
continuous-integration/drone/push Build is failing Details

This commit is contained in:
Oliver 2026-11-26 17:03:27 +00:00
parent 0b47b9ca40
commit a518c9671b
15 changed files with 674 additions and 111 deletions

2
.gitignore vendored
View File

@ -32,6 +32,8 @@ projects/**/pom.xml
/bases/do-blog/resources/public/archive/ /bases/do-blog/resources/public/archive/
/bases/do-blog/resources/public/chess/ /bases/do-blog/resources/public/chess/
/bases/do-blog/resources/public/posts/ /bases/do-blog/resources/public/posts/
/bases/do-blog/resources/public/todo/
/bases/do-blog/resources/public/widget/
# nrepl # nrepl
.nrepl-port .nrepl-port

View File

@ -3,6 +3,7 @@
[cljs.reader :as reader] [cljs.reader :as reader]
[clojure.walk :as walk] [clojure.walk :as walk]
[replicant.dom :as r] [replicant.dom :as r]
[reitit.core :as rc]
[reitit.frontend.easy :as rfe] [reitit.frontend.easy :as rfe]
[com.oly.static-sites.do-blog.routes :refer [router normalize-match]] [com.oly.static-sites.do-blog.routes :refer [router normalize-match]]
[com.oly.static-sites.do-blog.views :as views] [com.oly.static-sites.do-blog.views :as views]
@ -11,7 +12,8 @@
[com.oly.static-sites.do-blog.pages.chess-board :as chess] [com.oly.static-sites.do-blog.pages.chess-board :as chess]
[com.oly.static-sites.do-blog.pages.chess.state :as chess-state] [com.oly.static-sites.do-blog.pages.chess.state :as chess-state]
[com.oly.static-sites.do-blog.pages.chess.vstate :as viking-state] [com.oly.static-sites.do-blog.pages.chess.vstate :as viking-state]
[com.oly.static-sites.do-blog.pages.matrix-widget :as widget]) [com.oly.static-sites.do-blog.pages.matrix-widget :as widget]
[com.oly.static-sites.do-blog.pages.todo-widget :as todo])
(:require-macros [cl-eorg.macros :refer [org-doc->move-process]])) (:require-macros [cl-eorg.macros :refer [org-doc->move-process]]))
;; Copy org documents into public/ and write org-meta-index.edn at compile time. ;; Copy org documents into public/ and write org-meta-index.edn at compile time.
@ -38,15 +40,35 @@
x)) x))
actions)) actions))
(defn handle-action [[action & args]] (defn handle-action [dom-event [action & args]]
(case action (case action
:dom/prevent-default (some-> dom-event .preventDefault)
:search/set-terms (swap! state assoc-in [:search :terms] (first args)) :search/set-terms (swap! state assoc-in [:search :terms] (first args))
:widget/set-draft (swap! widget/widget-state assoc :draft (first args)) (case (namespace action)
:widget/send (widget/send-message! (:draft @widget/widget-state)) "widget" (widget/handle-action action args)
(js/console.warn "Unknown action" (pr-str action)))) "todo" (todo/handle-action action args)
(js/console.warn "Unknown action" (pr-str action)))))
(defn dispatch [{:replicant/keys [dom-event]} actions] (defn dispatch [{:replicant/keys [dom-event]} actions]
(run! handle-action (interpolate dom-event actions))) (run! #(handle-action dom-event %) (interpolate dom-event actions)))
(defn start-widget!
"Connect a widget page to the Matrix client the first time it is shown,
and re-render when its connection status changes."
[start! client]
(start!)
(when-let [c @client]
(add-watch c ::render (fn [_ _ old new]
(when (not= (:state old) (:state new))
(render!))))))
(defn start-widget-for!
"Start the widget for a route name, if it is a widget page."
[route-name]
(case route-name
:widget (start-widget! widget/start! widget/client)
:todo (start-widget! todo/start! todo/client)
nil))
;; Navigation ;; Navigation
@ -91,6 +113,8 @@
:posts (show-document! match (-> match :path-params :path)) :posts (show-document! match (-> match :path-params :path))
:chess (do (chess/start! match) :chess (do (chess/start! match)
(show-route! match)) (show-route! match))
(:widget :todo) (do (start-widget-for! (-> match :data :name))
(show-route! match))
(show-route! match)) (show-route! match))
(show-not-found! nil))) (show-not-found! nil)))
@ -103,6 +127,10 @@
(add-watch chess-state/game-state ::render (fn [_ _ _ _] (render!))) (add-watch chess-state/game-state ::render (fn [_ _ _ _] (render!)))
(add-watch viking-state/game-state ::render (fn [_ _ _ _] (render!))) (add-watch viking-state/game-state ::render (fn [_ _ _ _] (render!)))
(add-watch widget/widget-state ::render (fn [_ _ _ _] (render!))) (add-watch widget/widget-state ::render (fn [_ _ _ _] (render!)))
(add-watch todo/todo-state ::render (fn [_ _ _ _] (render!)))
;; Element sends its first widget request once, when the iframe has loaded,
;; so a widget page must listen now, not after the article index arrives.
(start-widget-for! (some-> (rc/match-by-path router js/location.pathname) :data :name))
(fetch-text "/documents/org-meta-index.edn" (fetch-text "/documents/org-meta-index.edn"
(fn [response] (fn [response]
(load-index! (reader/read-string response)) (load-index! (reader/read-string response))

View File

@ -1,30 +1,21 @@
(ns com.oly.static-sites.do-blog.pages.matrix-widget (ns com.oly.static-sites.do-blog.pages.matrix-widget
"Minimal Matrix widget, written against the postMessage protocol directly. "Minimal Matrix chat widget: shows room messages and sends text messages.
The protocol lives in the matrix-widget component.
Add it to a room in Element with: Add it to a room in Element with:
/addwidget https://<site>/widget/ /addwidget https://<site>/widget/"
The conversation with the client (Element) is:
1. client -> widget toWidget capabilities we reply with what we want
2. client -> widget toWidget notify_capabilities we reply {} and are ready
3. widget -> client fromWidget send_event post a message to the room
4. client -> widget toWidget send_event a new event in the room
Replies echo the request object back with an added :response key.
Requests we send need a unique :requestId and the :widgetId the client gave us."
(:require [clojure.string :as str] (:require [clojure.string :as str]
[com.oly.static-sites.matrix-widget.interface :as mw]
[com.oly.static-sites.do-blog.views :as views])) [com.oly.static-sites.do-blog.views :as views]))
(def capabilities (def capabilities
["org.matrix.msc2762.send.event:m.room.message#m.text" [(mw/send-event-capability "m.room.message" "m.text")
"org.matrix.msc2762.receive.event:m.room.message"]) (mw/receive-event-capability "m.room.message")])
(defonce widget-state (defonce widget-state
(atom {:status :waiting ;; :waiting -> :negotiating -> :ready (atom {:draft "" :log []}))
:widget-id nil
:approved [] (defonce client (atom nil))
:draft ""
:log []}))
(defn log! [direction text] (defn log! [direction text]
(swap! widget-state update :log (swap! widget-state update :log
@ -32,84 +23,31 @@
(take-last 50) (take-last 50)
vec))) vec)))
;; Sending (defn on-event [{:keys [type sender content]}]
(when (= "m.room.message" type)
(defn post! [message] (log! :in (str sender ": " (:body content)))))
(.postMessage js/window.parent (clj->js message) "*"))
(defn reply!
"Answer a toWidget request: the same object back, plus :response."
[request response]
(post! (assoc request :response response)))
(defn request!
"Send a fromWidget request to the client."
[action data]
(post! {:api "fromWidget"
:widgetId (:widget-id @widget-state)
:requestId (str (random-uuid))
:action action
:data data}))
(defn send-message! [body]
(when-not (str/blank? body)
(request! "send_event" {:type "m.room.message"
:content {:msgtype "m.text" :body body}})
(log! :out body)
(swap! widget-state assoc :draft "")))
;; Receiving
(defn handle-request
"Requests the client sends to us (api toWidget)."
[{:keys [action data widgetId] :as request}]
(case action
"capabilities"
(do (swap! widget-state assoc :status :negotiating :widget-id widgetId)
(reply! request {:capabilities capabilities}))
"notify_capabilities"
(do (swap! widget-state assoc :status :ready :approved (vec (:approved data)))
(reply! request {}))
"supported_api_versions"
(reply! request {:supported_versions ["0.0.1" "0.0.2" "org.matrix.msc2762"]})
"send_event"
(do (when (= "m.room.message" (:type data))
(log! :in (str (:sender data) ": " (-> data :content :body))))
(reply! request {}))
;; Anything else: say so, rather than leaving the client waiting.
(reply! request {:error {:message (str "Unsupported action: " action)}})))
(defn handle-response
"Replies from the client to requests we sent (api fromWidget)."
[{:keys [action response]}]
(when-let [error (:error response)]
(log! :error (str action " failed: " (:message error)))))
(defn on-message [event]
;; Only listen to the window that embeds us.
(when (and (not= js/window js/window.parent)
(= (.-source event) js/window.parent))
(let [{:keys [api response] :as message}
(js->clj (.-data event) :keywordize-keys true)]
(cond
(and (= "toWidget" api) (not response)) (handle-request message)
(and (= "fromWidget" api) response) (handle-response message)))))
(defn start! (defn start!
"Listen for the client straight away. Clients that do not wait for the "Connect to the Matrix client once; later visits reuse the connection."
iframe load event expect content_loaded before they start the handshake."
[] []
(.addEventListener js/window "message" on-message) (when-not @client
(when (not= js/window js/window.parent) (reset! client (mw/connect! {:capabilities capabilities
(js/setTimeout #(when (= :waiting (:status @widget-state)) :on-event on-event}))))
(request! "content_loaded" {}))
2000)))
(defonce started (start!)) (defn send-message! [body]
(when-let [c @client]
(when-not (str/blank? body)
(-> (mw/send-event! c "m.room.message" {:msgtype "m.text" :body body})
(.catch #(log! :error (str "send failed: " (.-message %)))))
(log! :out body)
(swap! widget-state assoc :draft ""))))
(defn handle-action
"Actions dispatched from the view; see core/handle-action."
[action args]
(case action
:widget/set-draft (swap! widget-state assoc :draft (first args))
:widget/send (send-message! (:draft @widget-state))))
;; View ;; View
@ -119,15 +57,16 @@
:ready "Connected"}) :ready "Connected"})
(defn widget-page [_state] (defn widget-page [_state]
(let [{:keys [status widget-id draft log approved]} @widget-state (let [{:keys [draft log]} @widget-state
embedded? (not= js/window js/window.parent)] c @client
{:keys [status widget-id approved]} (some-> c deref :state)]
[:div.pa3.font.lh-copy [:div.pa3.font.lh-copy
[:h1.f3.mt0 "Matrix widget"] [:h1.f3.mt0 "Matrix widget"]
(if-not embedded? (if-not (mw/embedded?)
[:p "Open this page as a widget inside a Matrix room, e.g. " [:p "Open this page as a widget inside a Matrix room, e.g. "
[:code "/addwidget " (.-origin js/location) "/widget/"]] [:code "/addwidget " (.-origin js/location) "/widget/"]]
[:div [:div
[:p.b {:role "status"} (status-text status)] [:p.b {:role "status"} (status-text status (status-text :waiting))]
(when widget-id [:p.f6.gray "Widget id: " widget-id]) (when widget-id [:p.f6.gray "Widget id: " widget-id])
(when (= :ready status) (when (= :ready status)
[:div [:div

View File

@ -0,0 +1,83 @@
(ns com.oly.static-sites.do-blog.pages.todo.model
"Todo list kept in a Matrix room, as pure functions.
Every change is a room event of event-type whose content is the whole item:
{:id \"uuid\" :text \"Buy milk\" :done false}
Toggling an item sends its content again with :done flipped. The list is the
newest event per :id, ordered by the server timestamp (origin_server_ts), so
it comes out the same whatever order events arrive in.
A chat message \"!todo Buy milk\" adds an item too; its id is the event id."
(:require [clojure.string :as str]))
(def event-type "com.digitaloctave.todo")
(def chat-command #"(?i)^\s*!todo\s+(\S.*)$")
(defn chat-todo-text
"The item text in a \"!todo ...\" chat message, or nil."
[body]
(when (string? body)
(some-> (re-find chat-command body) second str/trim)))
(defn event->todo
"The todo item an event describes, or nil when it is not one."
[{:keys [type content event_id sender origin_server_ts]}]
(let [ts (or origin_server_ts 0)]
(cond
(= event-type type)
(let [{:keys [id text done]} content]
(when (and (string? id) (string? text) (not (str/blank? text)))
{:id id :text text :done (true? done)
:sender sender :created ts :updated ts}))
(= "m.room.message" type)
(when-let [text (chat-todo-text (:body content))]
(when event_id
{:id event_id :text text :done false
:sender sender :created ts :updated ts})))))
(defn merge-todo
"Add a todo to todos (a map of id -> todo). The newer version wins; a
:pending (sent but not yet echoed by the server) item always gives way.
:created is kept from the first version seen."
[todos {:keys [id updated] :as todo}]
(let [current (get todos id)]
(cond
(nil? todo) todos
(nil? current) (assoc todos id todo)
:else
(let [newer (if (or (:pending current) (>= updated (:updated current)))
todo
current)
created (if (:pending current)
(:created todo)
(min (:created current) (:created todo)))]
(assoc todos id (assoc newer :created created))))))
(defn apply-events
"Fold room events into todos; events that are not todos are ignored."
[todos events]
(reduce merge-todo todos (keep event->todo events)))
(defn new-content
"Content for an event adding a todo, or nil for blank text."
[id text]
(let [text (str/trim (str text))]
(when-not (str/blank? text)
{:id id :text text :done false})))
(defn toggled-content
"Content for an event flipping a todo's :done."
[{:keys [id text done]}]
{:id id :text text :done (not done)})
(defn pending
"Show content locally straight away, until the server echoes the event."
[content now]
(assoc content :pending true :created now :updated now))
(defn sorted-todos
"Open items first, then done ones; oldest first within each group."
[todos]
(sort-by (juxt :done :created :id) (vals todos)))

View File

@ -0,0 +1,128 @@
(ns com.oly.static-sites.do-blog.pages.todo-widget
"A shared todo list for a Matrix room, embedded as a widget.
Add it to a room in Element with:
/addwidget https://<site>/todo/
Then add items in the widget, or from the chat with: !todo Buy milk"
(:require [com.oly.static-sites.matrix-widget.interface :as mw]
[com.oly.static-sites.do-blog.pages.todo.model :as model]
[com.oly.static-sites.do-blog.views :as views]))
(def send-todos (mw/send-event-capability model/event-type))
(def receive-todos (mw/receive-event-capability model/event-type))
(def receive-chat (mw/receive-event-capability "m.room.message" "m.text"))
(def capabilities [send-todos receive-todos receive-chat])
(defonce todo-state
(atom {:todos {} :draft "" :error nil}))
(defonce client (atom nil))
(defn- show-error! [error]
(swap! todo-state assoc :error (.-message error)))
(defn receive! [events]
(swap! todo-state update :todos model/apply-events events))
(defn load-history!
"Items sent before the widget opened (whatever the client has loaded)."
[c]
(-> (js/Promise.all
#js [(if (mw/approved? c receive-todos)
(mw/read-events! c model/event-type)
(js/Promise.resolve []))
(if (mw/approved? c receive-chat)
(mw/read-events! c "m.room.message" {:msgtype "m.text"})
(js/Promise.resolve []))])
(.then (fn [results] (receive! (mapcat identity results))))
(.catch show-error!)))
(defn start!
"Connect to the Matrix client once; later visits reuse the connection."
[]
(when-not @client
(reset! client (mw/connect! {:capabilities capabilities
:on-ready load-history!
:on-event #(receive! [%])}))))
(defn- publish! [content]
(when-let [c @client]
(swap! todo-state update :todos model/merge-todo (model/pending content (js/Date.now)))
(-> (mw/send-event! c model/event-type content)
(.catch show-error!))))
(defn add! []
(when-let [content (model/new-content (str (random-uuid)) (:draft @todo-state))]
(swap! todo-state assoc :draft "" :error nil)
(publish! content)))
(defn toggle! [id]
(when-let [todo (get-in @todo-state [:todos id])]
(publish! (model/toggled-content todo))))
(defn handle-action
"Actions dispatched from the view; see core/handle-action."
[action args]
(case action
:todo/set-draft (swap! todo-state assoc :draft (first args))
:todo/add (add!)
:todo/toggle (toggle! (first args))))
;; View
(def status-text
{:waiting "Waiting for the Matrix client…"
:negotiating "Asking for permission to use the todo list…"})
(defn todo-item [{:keys [id text done pending sender]}]
[:li.flex.items-center.pv2.bb.b--black-10 {:replicant/key id}
[:input.mr2 {:type "checkbox"
:id (str "todo-" id)
:checked done
:disabled pending
:on {:change [[:todo/toggle id]]}}]
[:label.flex-auto {:for (str "todo-" id)
:class (when done ["strike" "gray"])}
text]
(when sender [:span.f7.gray.ml2 sender])])
(defn todo-form [draft]
[:form.flex.mb3 {:on {:submit [[:dom/prevent-default] [:todo/add]]}}
[:input.input-reset.ba.b--black-20.pa2.flex-auto
{:type "text"
:placeholder "Add a todo"
:aria-label "New todo"
:value draft
:on {:input [[:todo/set-draft :event.target/value]]}}]
[:button.ml2.pa2.ba.b--black-20.bg-blue.white.pointer {:type "submit"} "Add"]])
(defn todo-page [_state]
(let [{:keys [todos draft error]} @todo-state
c @client
status (some-> c mw/status)
items (model/sorted-todos todos)]
[:div.pa3.font.lh-copy.mw6
[:h1.f3.mt0 "Todo"]
(cond
(not (mw/embedded?))
[:p "Add this page to a Matrix room as a widget: "
[:code "/addwidget " (.-origin js/location) "/todo/"]]
(not= :ready status)
[:p {:role "status"} (status-text status (status-text :waiting))]
(not (mw/approved? c send-todos))
[:p "The todo list needs permission to send and read todo events in this room."]
:else
[:div
(todo-form draft)
(when error [:p.dark-red {:role "alert"} error])
(if (seq items)
[:ul.list.pl0.mt0 (map todo-item items)]
[:p.gray "Nothing to do. Add an item above, or send "
[:code "!todo something"] " in the chat."])])]))
(defmethod views/page :todo [state]
(todo-page state))

View File

@ -11,7 +11,9 @@
["/archive/{*tag}" {:name :archive}] ["/archive/{*tag}" {:name :archive}]
["/chess/" {:name :chess}] ["/chess/" {:name :chess}]
["/about/" {:name :about}] ["/about/" {:name :about}]
["/widget/" {:name :widget}] ;; :embed? pages are shown inside a Matrix client, without the site chrome.
["/widget/" {:name :widget :embed? true}]
["/todo/" {:name :todo :embed? true}]
["/posts/{*path}" {:name :posts}]]) ["/posts/{*path}" {:name :posts}]])
(def router (rc/router routes)) (def router (rc/router routes))

View File

@ -53,6 +53,7 @@
[(href :about) (page-state (href :about) nil)] [(href :about) (page-state (href :about) nil)]
[(href :chess) (page-state (href :chess) nil)] [(href :chess) (page-state (href :chess) nil)]
[(href :widget) (page-state (href :widget) nil)] [(href :widget) (page-state (href :widget) nil)]
[(href :todo) (page-state (href :todo) nil)]
[(archive-href "") (page-state (archive-href "") nil)]] [(archive-href "") (page-state (archive-href "") nil)]]
(for [tag tags (for [tag tags
:let [url (archive-href tag)]] :let [url (archive-href tag)]]
@ -73,8 +74,14 @@
(defn generate! (defn generate!
([] (generate! default-public-dir default-template)) ([] (generate! default-public-dir default-template))
([public-dir template-file] ([public-dir template-file]
(let [template (slurp template-file) (let [index-file (io/file public-dir "documents" "org-meta-index.edn")
index (load-index! (edn/read-string (slurp (io/file public-dir "documents" "org-meta-index.edn")))) _ (when-not (.exists index-file)
(throw (ex-info (str index-file " is missing. It is written when the blog's"
" core.cljs is compiled; run the shadow-cljs blog build first"
" and check it compiled com.oly.static-sites.do-blog.core.")
{:file (str index-file)})))
template (slurp template-file)
index (load-index! (edn/read-string (slurp index-file)))
results (doall results (doall
(for [[url state] (pages public-dir index)] (for [[url state] (pages public-dir index)]
(try (try

View File

@ -26,6 +26,7 @@
:chess "Chess" :chess "Chess"
:about "About" :about "About"
:widget "Matrix widget" :widget "Matrix widget"
:todo "Todo"
"Page not found"))] "Page not found"))]
(if (str/blank? title) (if (str/blank? title)
site-name site-name
@ -59,10 +60,13 @@
#?(:clj (defmethod page :chess [_state] #?(:clj (defmethod page :chess [_state]
[:p.lh-copy "Loading the chess board…"])) [:p.lh-copy "Loading the chess board…"]))
;; Likewise the Matrix widget (pages/matrix_widget.cljs). ;; Likewise the Matrix widgets (pages/matrix_widget.cljs, pages/todo_widget.cljs).
#?(:clj (defmethod page :widget [_state] #?(:clj (defmethod page :widget [_state]
[:p.pa3.lh-copy "Loading the Matrix widget…"])) [:p.pa3.lh-copy "Loading the Matrix widget…"]))
#?(:clj (defmethod page :todo [_state]
[:p.pa3.lh-copy "Loading the todo list…"]))
(defn loading-bar [loading] (defn loading-bar [loading]
(when loading (when loading
[:div.fixed.top-0.left-0.w-100.bg-green.white.f6.tc.pa1.z-999 [:div.fixed.top-0.left-0.w-100.bg-green.white.f6.tc.pa1.z-999
@ -133,6 +137,6 @@
(defn app [state] (defn app [state]
(cond (cond
(:not-found? state) (layout state (not-found-page)) (:not-found? state) (layout state (not-found-page))
;; The widget is embedded in a Matrix client, so it skips the site chrome. ;; Widgets are embedded in a Matrix client, so they skip the site chrome.
(= :widget (-> state :route :data :name)) (page state) (-> state :route :data :embed?) (page state)
:else (layout state (page state)))) :else (layout state (page state))))

View File

@ -0,0 +1,4 @@
{:paths ["src"]
:deps {}
:aliases {:test {:extra-paths ["test"]
:extra-deps {}}}}

View File

@ -0,0 +1,122 @@
(ns com.oly.static-sites.matrix-widget.browser
"postMessage transport for the Matrix widget API: talks to the client
(e.g. Element) in the parent window. The protocol rules are in
matrix-widget.core; this namespace only moves messages.
A client is an atom holding
{:state session state (see core/initial-state)
:origin origin of the parent window, learned from its first message
:pending {request-id {:resolve f :reject f}}}
so callers can add-watch it to re-render on status changes."
(:require [com.oly.static-sites.matrix-widget.core :as core]))
(defn embedded?
"Is this page running inside another window (an iframe)?"
[]
(not (identical? js/window js/window.parent)))
(defn- post!
"Send a message to the parent. Until the client has spoken we do not know
its origin, so only content_loaded (which carries no data) goes to \"*\"."
[client message]
(.postMessage js/window.parent message (or (:origin @client) "*")))
(defn- answer! [client raw-request response]
;; Echo the client's own object back rather than a clj->js round trip,
;; so keys we do not know about survive unchanged.
(post! client (js/Object.assign #js {} raw-request
#js {:response (clj->js response)})))
(defn- on-request [client {:keys [on-event on-ready]} raw message]
(let [before (:state @client)
{:keys [state response event]} (core/handle-request before message)]
(swap! client assoc :state state)
(answer! client raw response)
(when (and on-ready (not= :ready (:status before)) (= :ready (:status state)))
(on-ready client))
(when (and on-event event)
(on-event event))))
(defn- on-response [client {:keys [requestId response]}]
(when-let [{:keys [resolve reject]} (get-in @client [:pending requestId])]
(swap! client update :pending dissoc requestId)
(if-let [error (core/response-error response)]
(reject (js/Error. error))
(resolve response))))
(defn- on-message [client opts event]
(let [origin (:origin @client)]
;; Only the window that embeds us, and once known only from its origin.
(when (and (identical? (.-source event) js/window.parent)
(or (nil? origin) (= origin (.-origin event))))
(let [raw (.-data event)
message (js->clj raw :keywordize-keys true)]
(case (core/classify message)
:request (do (swap! client update :origin #(or % (.-origin event)))
(on-request client opts raw message))
:response (on-response client message)
nil)))))
(defn request!
"Send a fromWidget request. Returns a js/Promise of the client's response
map, rejected with a js/Error when the client answers with an error."
[client action data]
(js/Promise.
(fn [resolve reject]
(let [request-id (str (random-uuid))]
(swap! client assoc-in [:pending request-id] {:resolve resolve :reject reject})
(post! client (clj->js (core/request-message
(-> @client :state :widget-id) request-id action data)))))))
(defn connect!
"Start listening for the Matrix client that embeds this page.
Options:
:capabilities capability strings to ask for (see core/*-capability)
:on-ready (fn [client]) once the user has approved capabilities
:on-event (fn [event]) for every room event the client sends us
Returns the client atom. Does nothing useful outside an iframe; check
embedded? to show instructions instead."
[{:keys [capabilities] :as opts}]
(let [client (atom {:state (core/initial-state capabilities)
:origin nil
:pending {}})
listener #(on-message client opts %)]
(swap! client assoc :listener listener)
(.addEventListener js/window "message" listener)
;; Clients that do not wait for the iframe load event wait for this.
(when (embedded?)
(js/setTimeout #(when (= :waiting (-> @client :state :status))
(post! client (clj->js (core/request-message
nil (str (random-uuid)) "content_loaded" {}))))
2000))
client))
(defn disconnect!
"Stop listening; pending requests are left unanswered."
[client]
(.removeEventListener js/window "message" (:listener @client)))
;; Convenience wrappers
(defn status [client] (-> @client :state :status))
(defn approved? [client capability] (core/approved? (:state @client) capability))
(defn send-event!
"Send a room event. Resolves to the client's response, which includes the
:event_id once the homeserver has accepted it."
[client event-type content]
(request! client "send_event" {:type event-type :content content}))
(defn read-events!
"Read recent room events of event-type (MSC2876). Needs the receive
capability for that type. Resolves to a vector of events. The client only
returns what it has loaded, so this is recent history, not the whole room."
([client event-type] (read-events! client event-type {}))
([client event-type {:keys [msgtype limit] :or {limit 100}}]
(-> (request! client "org.matrix.msc2876.read_events"
(cond-> {:type event-type :limit limit}
msgtype (assoc :msgtype msgtype)))
(.then #(vec (:events %))))))

View File

@ -0,0 +1,113 @@
(ns com.oly.static-sites.matrix-widget.core
"The Matrix widget API (MSC2762) as pure data in, data out: no browser here,
so it can be tested on the JVM. The browser transport is in
matrix-widget.browser.
Messages are maps sent with window.postMessage:
toWidget requests from the client (e.g. Element), which we answer
fromWidget requests we send to the client, which it answers
An answer is the request echoed back with a :response key added.
The handshake is:
1. client -> widget capabilities reply with the capabilities we want
2. client -> widget notify_capabilities which of them the user approved
after which the client forwards room events to us as send_event requests.")
(def supported-versions
["0.0.1" "0.0.2" "org.matrix.msc2762" "org.matrix.msc2871" "org.matrix.msc2876"])
;; Capabilities
(defn- event-capability [verb event-type msgtype]
(str "org.matrix.msc2762." verb ".event:" event-type
(when msgtype (str "#" msgtype))))
(defn send-event-capability
"Permission to send room events of event-type, e.g.
(send-event-capability \"m.room.message\" \"m.text\")."
([event-type] (send-event-capability event-type nil))
([event-type msgtype] (event-capability "send" event-type msgtype)))
(defn receive-event-capability
"Permission to be sent (and to read, via read_events) room events of event-type."
([event-type] (receive-event-capability event-type nil))
([event-type msgtype] (event-capability "receive" event-type msgtype)))
;; Session state
(defn initial-state
"State before the client has contacted us. :status goes
:waiting -> :negotiating -> :ready."
[capabilities]
{:status :waiting
:widget-id nil
:requested (vec capabilities)
:approved []})
(defn approved?
"Did the user grant capability?"
[state capability]
(boolean (some #{capability} (:approved state))))
;; Messages
(defn classify
"Is message a :request from the client, a :response to one of ours, or
neither (nil)?"
[message]
(when (map? message)
(let [{:keys [api response]} message]
(cond
(and (= "toWidget" api) (not (contains? message :response))) :request
(and (= "fromWidget" api) (some? response)) :response))))
(defn request-message
"A fromWidget request to send to the client."
[widget-id request-id action data]
{:api "fromWidget"
:widgetId widget-id
:requestId request-id
:action action
:data data})
(defn response-error
"The error message in a response, or nil when it succeeded."
[response]
(some-> response :error :message))
;; Answering client requests
(def ^:private acknowledged
"Client notifications we have nothing to say about but must still answer."
#{"theme_change" "language_change" "visibility" "update_visibility"
"widget_config" "update_state"})
(defn handle-request
"Work out how to answer a toWidget request. Returns
{:state the new session state
:response the data for the :response key of the reply
:event a room event the client delivered, when there is one}"
[state {:keys [action data widgetId]}]
(case action
"capabilities"
{:state (assoc state
:status :negotiating
:widget-id (or widgetId (:widget-id state)))
:response {:capabilities (:requested state)}}
"notify_capabilities"
{:state (assoc state :status :ready :approved (vec (:approved data)))
:response {}}
"supported_api_versions"
{:state state
:response {:supported_versions supported-versions}}
"send_event"
{:state state :response {} :event data}
(if (acknowledged action)
{:state state :response {}}
;; Say so, rather than leave the client waiting for an answer.
{:state state
:response {:error {:message (str "Unsupported action: " action)}}})))

View File

@ -0,0 +1,69 @@
(ns com.oly.static-sites.matrix-widget.interface
"Build Matrix widgets (pages embedded in a Matrix room, e.g. in Element)
without the matrix-widget-api JS library.
(def client
(connect! {:capabilities [(send-event-capability \"com.example.thing\")
(receive-event-capability \"com.example.thing\")]
:on-ready (fn [client] (read-events! client \"com.example.thing\"))
:on-event (fn [event] (prn event))}))
(send-event! client \"com.example.thing\" {:text \"hello\"})
The client is an atom; add-watch it to re-render when (status client)
changes. Add the page to a room with: /addwidget https://<site>/<page>/"
(:require [com.oly.static-sites.matrix-widget.core :as core]
#?(:cljs [com.oly.static-sites.matrix-widget.browser :as browser])))
;; Protocol helpers (cljc)
(defn send-event-capability
([event-type] (core/send-event-capability event-type))
([event-type msgtype] (core/send-event-capability event-type msgtype)))
(defn receive-event-capability
([event-type] (core/receive-event-capability event-type))
([event-type msgtype] (core/receive-event-capability event-type msgtype)))
;; Browser API
#?(:cljs
(do
(defn embedded?
"Is this page inside an iframe? Outside one there is no client to talk to."
[]
(browser/embedded?))
(defn connect!
"Start listening for the embedding Matrix client. Options:
:capabilities, :on-ready (fn [client]), :on-event (fn [event]).
Returns the client atom."
[opts]
(browser/connect! opts))
(defn disconnect! [client] (browser/disconnect! client))
(defn status
"One of :waiting, :negotiating or :ready."
[client]
(browser/status client))
(defn approved?
"Did the user grant capability?"
[client capability]
(browser/approved? client capability))
(defn request!
"Send any fromWidget action; returns a js/Promise of the response."
[client action data]
(browser/request! client action data))
(defn send-event!
"Send a room event; returns a js/Promise."
[client event-type content]
(browser/send-event! client event-type content))
(defn read-events!
"Recent room events of event-type; returns a js/Promise of a vector.
Options: :msgtype, :limit (default 100)."
([client event-type] (browser/read-events! client event-type))
([client event-type opts] (browser/read-events! client event-type opts)))))

View File

@ -0,0 +1,59 @@
(ns com.oly.static-sites.matrix-widget.core-test
(:require [clojure.test :refer [deftest is testing]]
[com.oly.static-sites.matrix-widget.core :as core]))
(def caps [(core/send-event-capability "m.room.message" "m.text")
(core/receive-event-capability "com.example.todo")])
(deftest capability-strings
(is (= ["org.matrix.msc2762.send.event:m.room.message#m.text"
"org.matrix.msc2762.receive.event:com.example.todo"]
caps)))
(deftest classify-messages
(is (= :request (core/classify {:api "toWidget" :action "capabilities"})))
(is (= :response (core/classify {:api "fromWidget" :action "send_event" :response {}})))
(testing "our own requests echoed back without an answer are ignored"
(is (nil? (core/classify {:api "fromWidget" :action "send_event"}))))
(testing "a toWidget message that already has a response is not a new request"
(is (nil? (core/classify {:api "toWidget" :action "capabilities" :response {}}))))
(is (nil? (core/classify "some other postMessage")))
(is (nil? (core/classify nil))))
(deftest handshake
(let [s0 (core/initial-state caps)
{s1 :state r1 :response} (core/handle-request
s0 {:api "toWidget" :action "capabilities"
:widgetId "w1" :requestId "1" :data {}})
{s2 :state r2 :response} (core/handle-request
s1 {:api "toWidget" :action "notify_capabilities"
:widgetId "w1" :requestId "2"
:data {:requested caps :approved [(first caps)]}})]
(is (= :waiting (:status s0)))
(is (= {:capabilities caps} r1))
(is (= {:status :negotiating :widget-id "w1"} (select-keys s1 [:status :widget-id])))
(is (= {} r2))
(is (= :ready (:status s2)))
(is (core/approved? s2 (first caps)))
(is (not (core/approved? s2 (second caps))))))
(deftest room-events-are-passed-on
(let [event {:type "com.example.todo" :content {:text "x"} :sender "@a:b"}
{:keys [response] :as result}
(core/handle-request (core/initial-state caps)
{:api "toWidget" :action "send_event" :data event})]
(is (= {} response))
(is (= event (:event result)))))
(deftest other-requests
(let [s (core/initial-state caps)]
(is (= {:supported_versions core/supported-versions}
(:response (core/handle-request s {:action "supported_api_versions"}))))
(is (= {} (:response (core/handle-request s {:action "theme_change" :data {}}))))
(is (= "Unsupported action: screenshot"
(core/response-error (:response (core/handle-request s {:action "screenshot"})))))))
(deftest request-messages
(is (= {:api "fromWidget" :widgetId "w1" :requestId "r1"
:action "send_event" :data {:type "t"}}
(core/request-message "w1" "r1" "send_event" {:type "t"}))))

View File

@ -1,5 +1,5 @@
{:mvn/repos {"clojars" {:url "https://repo.clojars.org/"}} {:mvn/repos {"clojars" {:url "https://repo.clojars.org/"}}
:paths ["development/src" "bases/portfolio/src" "bases/do-blog/src" "components/ui-tachyon/src"] :paths ["development/src" "bases/portfolio/src" "bases/do-blog/src" "components/ui-tachyon/src" "components/matrix-widget/src"]
:deps {cjohansen/dumdom {:mvn/version "2023.11.06"} :deps {cjohansen/dumdom {:mvn/version "2023.11.06"}
org.clojure/clojurescript {:mvn/version "1.12.134"} org.clojure/clojurescript {:mvn/version "1.12.134"}
no.cjohansen/portfolio {:mvn/version "2026.03.1"}} no.cjohansen/portfolio {:mvn/version "2026.03.1"}}
@ -21,6 +21,8 @@
:blog {:extra-paths ["components/ui-hiccup/src" :blog {:extra-paths ["components/ui-hiccup/src"
"components/ui-tachyon/src" "components/ui-tachyon/src"
"components/matrix-widget/src"
"components/matrix-widget/test"
"development/src" "bases/do-blog/src" "development/src" "bases/do-blog/src"
"bases/do-blog/test"] "bases/do-blog/test"]
:extra-deps { :extra-deps {
@ -74,7 +76,7 @@
cider/cider-nrepl {:mvn/version "0.58.0"} cider/cider-nrepl {:mvn/version "0.58.0"}
refactor-nrepl/refactor-nrepl {:mvn/version "3.11.0"} refactor-nrepl/refactor-nrepl {:mvn/version "3.11.0"}
cider/piggieback {:mvn/version "0.5.3"}} cider/piggieback {:mvn/version "0.5.3"}}
:extra-paths ["bases/do-blog/src" "bases/clojure-demos/src" "components/ui-hiccup/src" "components/ui-tachyon/src"] :extra-paths ["bases/do-blog/src" "bases/clojure-demos/src" "components/ui-hiccup/src" "components/ui-tachyon/src" "components/matrix-widget/src"]
:main-opts ["-m" "shadow.cljs.devtools.cli"]} :main-opts ["-m" "shadow.cljs.devtools.cli"]}
:test {:extra-paths []} :test {:extra-paths []}

View File

@ -8,4 +8,5 @@
:release "v[0-9]*"} :release "v[0-9]*"}
:projects {"development" {:alias "dev"}} :projects {"development" {:alias "dev"}}
:components {"ui-tachyon" {:alias "ui-tachyon"} :components {"ui-tachyon" {:alias "ui-tachyon"}
"ui-hiccup" {:alias "ui-hiccup"}}} "ui-hiccup" {:alias "ui-hiccup"}
"matrix-widget" {:alias "matrix-widget"}}}