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 629edb9f29
11 changed files with 342 additions and 212 deletions

View File

@ -0,0 +1,39 @@
<!DOCTYPE html>
<html class="tachyon ma0 pa0 h-100">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Todo · Digital Octave</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />
<link rel="stylesheet" href="https://unpkg.com/tachyons@4.12.0/css/tachyons.min.css" />
<script src="https://cdn.tailwindcss.com"></script>
<style type="text/css">
.font { font-family: "Roboto Slab", serif !important; }
</style>
<style type="text/css" media="screen">
#loading {
-webkit-animation: rotation 2s infinite linear;
}
@-webkit-keyframes rotation {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
}
}
</style>
</head>
<body class="ma0 pa0 h-100">
<!-- Everything between the app markers is replaced by the static generator
(com.oly.static-sites.do-blog.ssr). -->
<div id="app" class="ma0 pa0 h-100"><!--app--><p class="pa3 lh-copy">Loading the todo list…</p><!--/app--></div>
<script src="/js/base.js" type="text/javascript"></script>
<script src="/js/app.js" type="text/javascript"></script>
</body>
</html>

View File

@ -0,0 +1,39 @@
<!DOCTYPE html>
<html class="tachyon ma0 pa0 h-100">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Matrix widget · Digital Octave</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />
<link rel="stylesheet" href="https://unpkg.com/tachyons@4.12.0/css/tachyons.min.css" />
<script src="https://cdn.tailwindcss.com"></script>
<style type="text/css">
.font { font-family: "Roboto Slab", serif !important; }
</style>
<style type="text/css" media="screen">
#loading {
-webkit-animation: rotation 2s infinite linear;
}
@-webkit-keyframes rotation {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
}
}
</style>
</head>
<body class="ma0 pa0 h-100">
<!-- Everything between the app markers is replaced by the static generator
(com.oly.static-sites.do-blog.ssr). -->
<div id="app" class="ma0 pa0 h-100"><!--app--><p class="pa3 lh-copy">Loading the Matrix widget…</p><!--/app--></div>
<script src="/js/base.js" type="text/javascript"></script>
<script src="/js/app.js" type="text/javascript"></script>
</body>
</html>

View File

@ -1,109 +1 @@
(ns com.oly.static-sites.do-blog.core
(:require [ajax.core :refer [GET text-response-format]]
[cljs.reader :as reader]
[clojure.walk :as walk]
[replicant.dom :as r]
[reitit.frontend.easy :as rfe]
[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.pages.helpers.database
:refer [state load-index! latest-article org->document]]
[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.vstate :as viking-state]
[com.oly.static-sites.do-blog.pages.matrix-widget :as widget])
(:require-macros [cl-eorg.macros :refer [org-doc->move-process]]))
;; Copy org documents into public/ and write org-meta-index.edn at compile time.
(org-doc->move-process
"bases/do-blog/resources/documents/"
"bases/do-blog/resources/public/documents/")
;; Rendering
(defn render! []
;; Nothing to render until the first route has resolved; until then the
;; static (server generated) HTML stays in place.
(when-let [current (when (:route @state) @state)]
(set! js/document.title (views/page-title current))
(r/render (js/document.getElementById "app") (views/app current))))
;; Event handling for data driven handlers, e.g. [[:search/set-terms :event.target/value]]
(defn interpolate [event actions]
(walk/postwalk
(fn [x]
(case x
:event.target/value (.. event -target -value)
x))
actions))
(defn handle-action [[action & args]]
(case action
:search/set-terms (swap! state assoc-in [:search :terms] (first args))
:widget/set-draft (swap! widget/widget-state assoc :draft (first args))
:widget/send (widget/send-message! (:draft @widget/widget-state))
(js/console.warn "Unknown action" (pr-str action))))
(defn dispatch [{:replicant/keys [dom-event]} actions]
(run! handle-action (interpolate dom-event actions)))
;; Navigation
(defn fetch-text
([path on-success] (fetch-text path on-success nil))
([path on-success on-error]
(GET path {:response-format (text-response-format)
:handler on-success
:error-handler (fn [error]
(js/console.error "Failed to fetch" path (clj->js error))
(when on-error (on-error error)))})))
(defn show-route! [match & {:as extra}]
(swap! state merge
{:route match :search {:terms ""} :loading nil :not-found? false}
extra))
(defn show-not-found! [match]
(show-route! (or match {:data {:name :not-found}
:path js/location.pathname})
:document nil
:not-found? true))
(defn show-document!
"Fetch and show an org document. The current page stays visible with a
loading indicator until it arrives; responses for a page we have since
navigated away from are dropped."
[match relative-path]
(if relative-path
(let [path (:path match)
current? #(= path (:loading @state))]
(swap! state assoc :loading path)
(fetch-text (str "/documents/" relative-path)
#(when (current?) (show-route! match :document (org->document %)))
#(when (current?) (show-not-found! match))))
(show-not-found! match)))
(defn on-navigate [raw-match]
(if-let [match (normalize-match raw-match)]
(case (-> match :data :name)
:homepage (show-document! match (latest-article))
:posts (show-document! match (-> match :path-params :path))
:chess (do (chess/start! match)
(show-route! match))
(show-route! match))
(show-not-found! nil)))
(defn ^:dev/after-load reload! []
(render!))
(defn init []
(r/set-dispatch! dispatch)
(add-watch state ::render (fn [_ _ _ _] (render!)))
(add-watch chess-state/game-state ::render (fn [_ _ _ _] (render!)))
(add-watch viking-state/game-state ::render (fn [_ _ _ _] (render!)))
(add-watch widget/widget-state ::render (fn [_ _ _ _] (render!)))
(fetch-text "/documents/org-meta-index.edn"
(fn [response]
(load-index! (reader/read-string response))
(rfe/start! router on-navigate {:use-fragment false}))))
(ns com.oly.static-sites.do-blog.core)

View File

@ -1,30 +1,21 @@
(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:
/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."
/addwidget https://<site>/widget/"
(:require [clojure.string :as str]
[com.oly.static-sites.matrix-widget.interface :as mw]
[com.oly.static-sites.do-blog.views :as views]))
(def capabilities
["org.matrix.msc2762.send.event:m.room.message#m.text"
"org.matrix.msc2762.receive.event:m.room.message"])
[(mw/send-event-capability "m.room.message" "m.text")
(mw/receive-event-capability "m.room.message")])
(defonce widget-state
(atom {:status :waiting ;; :waiting -> :negotiating -> :ready
:widget-id nil
:approved []
:draft ""
:log []}))
(atom {:draft "" :log []}))
(defonce client (atom nil))
(defn log! [direction text]
(swap! widget-state update :log
@ -32,84 +23,31 @@
(take-last 50)
vec)))
;; Sending
(defn post! [message]
(.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 on-event [{:keys [type sender content]}]
(when (= "m.room.message" type)
(log! :in (str sender ": " (:body content)))))
(defn start!
"Listen for the client straight away. Clients that do not wait for the
iframe load event expect content_loaded before they start the handshake."
"Connect to the Matrix client once; later visits reuse the connection."
[]
(.addEventListener js/window "message" on-message)
(when (not= js/window js/window.parent)
(js/setTimeout #(when (= :waiting (:status @widget-state))
(request! "content_loaded" {}))
2000)))
(when-not @client
(reset! client (mw/connect! {:capabilities capabilities
:on-event on-event}))))
(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
@ -119,15 +57,16 @@
:ready "Connected"})
(defn widget-page [_state]
(let [{:keys [status widget-id draft log approved]} @widget-state
embedded? (not= js/window js/window.parent)]
(let [{:keys [draft log]} @widget-state
c @client
{:keys [status widget-id approved]} (some-> c deref :state)]
[:div.pa3.font.lh-copy
[: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. "
[:code "/addwidget " (.-origin js/location) "/widget/"]]
[: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 (= :ready status)
[: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}]
["/chess/" {:name :chess}]
["/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}]])
(def router (rc/router routes))

View File

@ -53,6 +53,7 @@
[(href :about) (page-state (href :about) nil)]
[(href :chess) (page-state (href :chess) nil)]
[(href :widget) (page-state (href :widget) nil)]
[(href :todo) (page-state (href :todo) nil)]
[(archive-href "") (page-state (archive-href "") nil)]]
(for [tag tags
:let [url (archive-href tag)]]

View File

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

View File

@ -1,5 +1,5 @@
{: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"}
org.clojure/clojurescript {:mvn/version "1.12.134"}
no.cjohansen/portfolio {:mvn/version "2026.03.1"}}
@ -21,6 +21,8 @@
:blog {:extra-paths ["components/ui-hiccup/src"
"components/ui-tachyon/src"
"components/matrix-widget/src"
"components/matrix-widget/test"
"development/src" "bases/do-blog/src"
"bases/do-blog/test"]
:extra-deps {
@ -74,7 +76,7 @@
cider/cider-nrepl {:mvn/version "0.58.0"}
refactor-nrepl/refactor-nrepl {:mvn/version "3.11.0"}
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"]}
:test {:extra-paths []}

View File

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