@bigmistqke/whiteboard 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -209
- package/bin/whiteboard.ts +82 -239
- package/dist/bin/whiteboard.js +70 -200
- package/dist/client/runtime.js +66 -7
- package/dist/plugins/chat/public/style.css +10 -6
- package/dist/plugins/code/README.md +10 -0
- package/dist/plugins/code/index.js +31 -22
- package/dist/plugins/code/public/client.js +1 -0
- package/dist/plugins/code/public/style.css +33 -2
- package/dist/plugins/comments/public/client.js +1 -1
- package/dist/plugins/form/public/style.css +2 -0
- package/dist/plugins/iframe/index.js +2 -2
- package/dist/plugins/lightbox/public/client.js +1 -1
- package/dist/plugins/terminal/index.js +7 -9
- package/dist/plugins/terminal/public/client.js +1 -1
- package/dist/plugins/terminal/public/style.css +3 -3
- package/dist/plugins/toc/index.js +1 -1
- package/dist/plugins/toc/public/client.js +1 -1
- package/dist/plugins/window/index.js +4 -4
- package/dist/src/build.js +159 -0
- package/dist/src/client/page/main.js +1 -1
- package/dist/src/document.js +93 -0
- package/dist/src/events.js +3 -13
- package/dist/src/hub.js +47 -35
- package/dist/src/listen.js +100 -0
- package/dist/src/listeners.js +67 -0
- package/dist/src/pages/index.js +1 -1
- package/dist/src/pages/markdown.js +23 -11
- package/dist/src/pages/render.js +13 -8
- package/dist/src/server.js +166 -514
- package/dist/src/site.js +173 -0
- package/dist/src/status.js +63 -1
- package/package.json +1 -1
- package/plugins/README.md +258 -0
- package/plugins/chat/public/style.css +10 -6
- package/plugins/code/README.md +10 -0
- package/plugins/code/client.ts +73 -0
- package/plugins/code/index.ts +38 -26
- package/plugins/code/public/style.css +33 -2
- package/plugins/comments/client.ts +8 -1
- package/plugins/form/public/style.css +2 -0
- package/plugins/iframe/index.ts +2 -2
- package/plugins/lightbox/client.ts +13 -3
- package/plugins/terminal/client.ts +10 -2
- package/plugins/terminal/index.ts +8 -6
- package/plugins/terminal/public/style.css +3 -3
- package/plugins/toc/client.ts +9 -2
- package/plugins/toc/index.ts +1 -1
- package/plugins/window/index.ts +4 -4
- package/skills/whiteboard/SKILL.md +3 -1
- package/src/build.ts +213 -0
- package/src/client/page/elsewhere.ts +2 -1
- package/src/client/runtime.ts +88 -10
- package/src/client/toast.ts +1 -1
- package/src/define.ts +34 -18
- package/src/document.ts +191 -0
- package/src/events.ts +11 -16
- package/src/hub.ts +48 -34
- package/src/listen.ts +125 -0
- package/src/listeners.ts +95 -0
- package/src/pages/index.ts +1 -1
- package/src/pages/markdown.ts +29 -18
- package/src/pages/render.ts +13 -8
- package/src/server.ts +165 -609
- package/src/site.ts +165 -0
- package/src/status.ts +100 -0
|
@@ -16,13 +16,13 @@ async function render(ctx) {
|
|
|
16
16
|
if (!safeSrc(src)) return html`<pre class="wb-error">iframe: src must be an http(s) URL or a path, not ${src.split(":")[0]}:</pre>`;
|
|
17
17
|
const title = ctx.labelText ?? ctx.attrs.title ?? src;
|
|
18
18
|
return html`<div class="wb-iframe-frame" style="height: ${height(ctx.attrs.height)}">
|
|
19
|
-
<iframe src="${src}" title="${title}" loading="lazy" referrerpolicy="no-referrer"></iframe>
|
|
19
|
+
<iframe src="${ctx.fileUrl(src)}" title="${title}" loading="lazy" referrerpolicy="no-referrer"></iframe>
|
|
20
20
|
</div>`;
|
|
21
21
|
}
|
|
22
22
|
/** What it shows on its own, for the ↗ of a window around it: its address. */
|
|
23
23
|
function open(ctx) {
|
|
24
24
|
const src = (ctx.attrs.src ?? "").trim();
|
|
25
|
-
return src && safeSrc(src) ? src : null;
|
|
25
|
+
return src && safeSrc(src) ? ctx.fileUrl(src) : null;
|
|
26
26
|
}
|
|
27
27
|
function iframe() {
|
|
28
28
|
return definePlugin({
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
const e=e=>`<svg viewBox="0 0 16 16" width="18" height="18" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="${e}"/></svg>`,t=e(`M10 3.5 5.5 8l4.5 4.5`),n=e(`M6 3.5 10.5 8 6 12.5`),r=e(`M4 4l8 8M12 4l-8 8`),i=e=>[...e.querySelectorAll(`img, video`)].filter(e=>!e.closest(`a, .wb-window-bar, .wb-lightbox`));let a=null,o=[],s=0;function c(){if(!a)return;let e=o[s],t=a.querySelector(`.wb-lightbox-stage`),n;if(e instanceof HTMLVideoElement){let t=e.cloneNode(!0);t.controls=!0,t.removeAttribute(`autoplay`),n=t}else{let t=document.createElement(`img`);t.src=e.currentSrc||e.src,t.alt=e.alt,n=t}t.replaceChildren(n),a.querySelector(`.wb-lightbox-caption`).textContent=(e instanceof HTMLImageElement?e.alt:e.getAttribute(`aria-label`))??``;for(let e of a.querySelectorAll(`.wb-lightbox-prev, .wb-lightbox-next`))e.hidden=o.length<2}function l(e,l){o=i(e),s=Math.max(0,o.indexOf(l)),a?.remove(),a=document.createElement(`div`),a.className=`wb-lightbox`,a.setAttribute(`role`,`dialog`),a.setAttribute(`aria-modal`,`true`),a.innerHTML=`<div class="wb-lightbox-stage"></div><div class="wb-lightbox-caption"></div>
|
|
2
2
|
<button type="button" class="wb-lightbox-prev" aria-label="Previous">${t}</button>
|
|
3
3
|
<button type="button" class="wb-lightbox-next" aria-label="Next">${n}</button>
|
|
4
|
-
<button type="button" class="wb-lightbox-close" aria-label="Close">${r}</button>`,a.addEventListener(`click`,e=>{let t=e.target;t.closest(`.wb-lightbox-prev`)?u(-1):t.closest(`.wb-lightbox-next`)?u(1):(t.closest(`.wb-lightbox-close`)||t===a||t.matches(`.wb-lightbox-stage`))&&d()}),
|
|
4
|
+
<button type="button" class="wb-lightbox-close" aria-label="Close">${r}</button>`,a.addEventListener(`click`,e=>{let t=e.target;t.closest(`.wb-lightbox-prev`)?u(-1):t.closest(`.wb-lightbox-next`)?u(1):(t.closest(`.wb-lightbox-close`)||t===a||t.matches(`.wb-lightbox-stage`))&&d()}),f?.append(a),c()}function u(e){o.length<2||(s=(s+e+o.length)%o.length,c())}function d(){a?.remove(),a=null}let f=null,p=!1;const m=(e,t,n)=>{n.slot(`overlay`,e=>(f=e,()=>{d(),f=null})),p||(p=!0,document.addEventListener(`click`,e=>{let t=e.target.closest?.(`img`),n=t?.closest(`[data-lightbox]`);t&&n&&f&&!t.closest(`a, .wb-lightbox`)&&(e.preventDefault(),l(n,t))}),document.addEventListener(`keydown`,e=>{if(a){if(e.key===`Escape`)d();else if(e.key===`ArrowLeft`)u(-1);else if(e.key===`ArrowRight`)u(1);else return;e.preventDefault()}}))};export{m as default};
|
|
@@ -13,19 +13,17 @@ const STYLE = "style.css";
|
|
|
13
13
|
* render, and each session's screen is in it as HTML, so a page shows it from its first render on;
|
|
14
14
|
* client.js puts the live terminal in its place.
|
|
15
15
|
*/
|
|
16
|
-
const drawer = (state, screens
|
|
16
|
+
const drawer = (state, screens) => html(_templateObject || (_templateObject = _taggedTemplateLiteral([
|
|
17
17
|
"<aside id=\"wb-terminal\" aria-label=\"Terminal\" data-sessions=\"",
|
|
18
18
|
"\">\n <div class=\"wb-term-grip\" title=\"drag to resize\"></div>\n <div class=\"wb-term-bar\">\n <button type=\"button\" class=\"wb-term-toggle\" title=\"Toggle the terminal (Ctrl+`)\">\n <span class=\"wb-term-chevron\"></span>terminal</button\n ><span class=\"wb-term-status\"></span><span class=\"wb-term-actions\"></span\n ><span class=\"wb-term-tabs\"\n >",
|
|
19
19
|
"</span\n >\n </div>\n <div class=\"wb-term-screen\">\n ",
|
|
20
|
-
"\n </div>\n </aside>\n <script>\n try {\n const t = document.getElementById('wb-terminal'),\n s = sessionStorage,\n o = new URLSearchParams(location.search).get('terminal') === 'open' || s.getItem('wb-terminal-open') === '1'\n t.dataset.state = o ? 'open' : 'collapsed'\n const h = +s.getItem('wb-terminal-height')\n if (h) document.documentElement.style.setProperty('--wb-term-h', h + 'px')\n const tabs = [...t.querySelectorAll('.wb-term-tab')],\n k = s.getItem('wb-terminal-tab'),\n a = tabs.find(b => b.dataset.id === k) ?? tabs[0]\n if (a) {\n t.dataset.tab = a.dataset.id\n a.classList.add('wb-current')\n t.querySelector('.wb-term-placeholder[data-id=\"' + a.dataset.id + '\"]')?.classList.add('wb-current')\n }\n } catch {}\n <\/script
|
|
21
|
-
"\"><\/script>"
|
|
20
|
+
"\n </div>\n </aside>\n <script>\n try {\n const t = document.getElementById('wb-terminal'),\n s = sessionStorage,\n o = new URLSearchParams(location.search).get('terminal') === 'open' || s.getItem('wb-terminal-open') === '1'\n t.dataset.state = o ? 'open' : 'collapsed'\n const h = +s.getItem('wb-terminal-height')\n if (h) document.documentElement.style.setProperty('--wb-term-h', h + 'px')\n const tabs = [...t.querySelectorAll('.wb-term-tab')],\n k = s.getItem('wb-terminal-tab'),\n a = tabs.find(b => b.dataset.id === k) ?? tabs[0]\n if (a) {\n t.dataset.tab = a.dataset.id\n a.classList.add('wb-current')\n t.querySelector('.wb-term-placeholder[data-id=\"' + a.dataset.id + '\"]')?.classList.add('wb-current')\n }\n } catch {}\n <\/script>"
|
|
22
21
|
], [
|
|
23
22
|
"<aside id=\"wb-terminal\" aria-label=\"Terminal\" data-sessions=\"",
|
|
24
23
|
"\">\n <div class=\"wb-term-grip\" title=\"drag to resize\"></div>\n <div class=\"wb-term-bar\">\n <button type=\"button\" class=\"wb-term-toggle\" title=\"Toggle the terminal (Ctrl+\\`)\">\n <span class=\"wb-term-chevron\"></span>terminal</button\n ><span class=\"wb-term-status\"></span><span class=\"wb-term-actions\"></span\n ><span class=\"wb-term-tabs\"\n >",
|
|
25
24
|
"</span\n >\n </div>\n <div class=\"wb-term-screen\">\n ",
|
|
26
|
-
"\n </div>\n </aside>\n <script>\n try {\n const t = document.getElementById('wb-terminal'),\n s = sessionStorage,\n o = new URLSearchParams(location.search).get('terminal') === 'open' || s.getItem('wb-terminal-open') === '1'\n t.dataset.state = o ? 'open' : 'collapsed'\n const h = +s.getItem('wb-terminal-height')\n if (h) document.documentElement.style.setProperty('--wb-term-h', h + 'px')\n const tabs = [...t.querySelectorAll('.wb-term-tab')],\n k = s.getItem('wb-terminal-tab'),\n a = tabs.find(b => b.dataset.id === k) ?? tabs[0]\n if (a) {\n t.dataset.tab = a.dataset.id\n a.classList.add('wb-current')\n t.querySelector('.wb-term-placeholder[data-id=\"' + a.dataset.id + '\"]')?.classList.add('wb-current')\n }\n } catch {}\n <\/script
|
|
27
|
-
|
|
28
|
-
])), JSON.stringify(state), state.sessions.map((s) => html`<button type="button" class="wb-term-tab" data-id="${s.id}">${s.label}</button>`), state.sessions.map((s) => screens[s.id] && html`<div class="wb-term-placeholder" data-id="${s.id}" aria-hidden="true">${raw(screens[s.id])}</div>`), client);
|
|
25
|
+
"\n </div>\n </aside>\n <script>\n try {\n const t = document.getElementById('wb-terminal'),\n s = sessionStorage,\n o = new URLSearchParams(location.search).get('terminal') === 'open' || s.getItem('wb-terminal-open') === '1'\n t.dataset.state = o ? 'open' : 'collapsed'\n const h = +s.getItem('wb-terminal-height')\n if (h) document.documentElement.style.setProperty('--wb-term-h', h + 'px')\n const tabs = [...t.querySelectorAll('.wb-term-tab')],\n k = s.getItem('wb-terminal-tab'),\n a = tabs.find(b => b.dataset.id === k) ?? tabs[0]\n if (a) {\n t.dataset.tab = a.dataset.id\n a.classList.add('wb-current')\n t.querySelector('.wb-term-placeholder[data-id=\"' + a.dataset.id + '\"]')?.classList.add('wb-current')\n }\n } catch {}\n <\/script>"
|
|
26
|
+
])), JSON.stringify(state), state.sessions.map((s) => html`<button type="button" class="wb-term-tab" data-id="${s.id}">${s.label}</button>`), state.sessions.map((s) => screens[s.id] && html`<div class="wb-term-placeholder" data-id="${s.id}" aria-hidden="true">${raw(screens[s.id])}</div>`));
|
|
29
27
|
function terminal() {
|
|
30
28
|
return {
|
|
31
29
|
name: "terminal",
|
|
@@ -36,8 +34,8 @@ function terminal() {
|
|
|
36
34
|
dir: ctx.project.dir,
|
|
37
35
|
home: ctx.dataDir
|
|
38
36
|
});
|
|
39
|
-
const client = ctx.asset(CLIENT);
|
|
40
37
|
return {
|
|
38
|
+
client: CLIENT,
|
|
41
39
|
routes: {
|
|
42
40
|
"GET /sessions": {
|
|
43
41
|
description: "the sessions (the drawer's tabs): id, label, whether each runs",
|
|
@@ -106,10 +104,10 @@ function terminal() {
|
|
|
106
104
|
run: ({ body }) => term.open(body.id, body.path)
|
|
107
105
|
}
|
|
108
106
|
},
|
|
109
|
-
async
|
|
107
|
+
async slots(req) {
|
|
110
108
|
if (!ctx.authorized(req)) return null;
|
|
111
109
|
const state = await term.sessions();
|
|
112
|
-
return {
|
|
110
|
+
return { bottom: drawer(state, await term.screens(state.sessions)) };
|
|
113
111
|
}
|
|
114
112
|
};
|
|
115
113
|
},
|
|
@@ -38,4 +38,4 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
|
|
|
38
38
|
* http://bellard.org/jslinux/
|
|
39
39
|
* Copyright (c) 2011 Fabrice Bellard
|
|
40
40
|
*/
|
|
41
|
-
this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(ns,Math.floor(u/e.css.cell.width)),rows:Math.max(rs,Math.floor(l/e.css.cell.height))}}};const as={get:e=>{try{return sessionStorage.getItem(e)}catch{return null}},set:(e,t)=>{try{sessionStorage.setItem(e,t)}catch{}}},os=(()=>{try{return JSON.parse(document.getElementById(`wb-page`)?.textContent??`{}`).base??``}catch{return``}})();function ss(e){let t=e.querySelector(`.wb-term-screen`),n=e.querySelector(`.wb-term-tabs`),r=e.querySelector(`.wb-term-status`),i=e.querySelector(`.wb-term-actions`),a=e.querySelector(`.wb-term-toggle`),o=e.querySelector(`.wb-term-grip`),s=[];try{({sessions:s}=JSON.parse(e.dataset.sessions??`{}`)),s??=[]}catch{}let c=e.dataset.tab??s[0]?.id??null,l=new ts({fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,fontSize:13,cursorBlink:!0,scrollback:5e3,scrollSensitivity:3,allowProposedApi:!0,theme:{background:`#0f1115`,foreground:`#d7dae0`,cursor:`#d7dae0`,selectionBackground:`#3a4150`}}),u=new is;l.loadAddon(u),l.open(t);let d=()=>e.dataset.state===`open`;if(new URLSearchParams(location.search).get(`terminal`)===`open`){as.set(`wb-terminal-open`,`1`);let e=new URL(location.href);e.searchParams.delete(`terminal`),history.replaceState(history.state,``,e)}let f=crypto.randomUUID(),p=null,m=null,h=as.get(`wb-terminal-active`)===`1`,g=``,_=()=>p===f;function ee(){if(!d()||!c)return;let e=u.proposeDimensions();if(!e?.cols||!e?.rows)return;let t=`${c} ${e.cols}x${e.rows} ${h}`;t!==g&&(g=t,cs(os+`/api/terminal/resize`,{id:c,viewer:f,cols:e.cols,rows:e.rows,active:h}),h&&=(p=f,!1)),te()}function te(){let e=u.proposeDimensions(),t=_()||!m?e:m;t?.cols&&t?.rows&&(t.cols!==l.cols||t.rows!==l.rows)&&l.resize(t.cols,t.rows)}function ne(){!_()&&c&&(h=!0,ee())}new ResizeObserver(()=>ee()).observe(t),l.textarea?.addEventListener(`focus`,ne);function re(t){let n=()=>{e.dataset.state=t?`open`:`collapsed`,as.set(`wb-terminal-open`,t?`1`:`0`)},r=document.startViewTransition;r&&!matchMedia(`(prefers-reduced-motion: reduce)`).matches?r.call(document,n):n(),requestAnimationFrame(()=>{t&&ne(),ee(),t&&l.focus()})}a.addEventListener(`click`,()=>re(!d())),addEventListener(`keydown`,e=>{e.ctrlKey&&e.key==="`"&&(e.preventDefault(),re(!d()))}),o.addEventListener(`pointerdown`,t=>{t.preventDefault(),o.setPointerCapture(t.pointerId),d()||re(!0);let n=e.querySelector(`.wb-term-bar`).offsetHeight,r=e=>{let t=Math.max(120,Math.min(innerHeight-80,innerHeight-e.clientY-n));document.documentElement.style.setProperty(`--wb-term-h`,`${Math.round(t)}px`)},i=()=>{o.removeEventListener(`pointermove`,r),o.removeEventListener(`pointerup`,i);let e=getComputedStyle(document.documentElement).getPropertyValue(`--wb-term-h`);as.set(`wb-terminal-height`,String(parseInt(e)||``)),ee()};o.addEventListener(`pointermove`,r),o.addEventListener(`pointerup`,i)});let ie=``,ae=Promise.resolve();l.onData(e=>{if(!c)return;ne();let t=c;ie||queueMicrotask(()=>{let e=ie;ie=``,ae=ae.then(()=>cs(os+`/api/terminal/input`,{id:t,data:e})).then(()=>{},()=>{})}),ie+=e});function v(e,t=[]){r.textContent=e,i.replaceChildren(...t.map(([e,t])=>{let n=document.createElement(`button`);return n.type=`button`,n.textContent=e,n.addEventListener(`click`,t),n}))}function oe(){n.replaceChildren(...s.map(e=>{let t=document.createElement(`span`);t.className=`wb-term-tab`,t.dataset.id=e.id,t.classList.toggle(`wb-current`,e.id===c),t.toggleAttribute(`data-exited`,!e.running);let n=document.createElement(`button`);n.type=`button`,n.className=`wb-term-tab-name`,n.textContent=e.label,n.title=e.running?e.label:`${e.label}: exited (${e.exited})`,n.addEventListener(`click`,()=>ce(e.id)),t.append(n);let r=document.createElement(`button`);return r.type=`button`,r.className=`wb-term-tab-close`,r.title=`Close this tab (ends its program)`,r.textContent=`×`,r.addEventListener(`click`,()=>b(e.id)),t.append(r),t})),se()}let y=document.createElement(`button`);y.type=`button`,y.className=`wb-term-add`,y.title=`A new tab with a shell`,y.textContent=`+`,y.addEventListener(`click`,()=>le({})),n.after(y);function se(){let e=s.find(e=>e.id===c);if(!e||e.running)return v(``,[]);v(e.exited==null?`stopped`:`exited (${e.exited})`,[[`Start again`,()=>le({id:e.id,restart:!0})]])}function ce(e){e===c&&S||(c=e,e&&as.set(`wb-terminal-tab`,e),oe(),C()),d()&&l.focus()}async function b(e){await cs(os+`/api/terminal/close`,{id:e}),s=s.filter(t=>t.id!==e),c===e?ce(s.at(-1)?.id??null):oe()}async function le(e){v(`starting…`);let t=await cs(os+`/api/terminal/start`,e),n=await t.json().catch(()=>({}));if(!t.ok)return v(n.error??`could not start`,[[`Try again`,()=>le(e)]]);await x(),d()||re(!0),ce(n.session),l.focus()}async function x(){try{let e=await fetch(os+`/api/terminal/sessions`);e.ok&&({sessions:s}=await e.json())}catch{}oe()}let S=null;function C(){S?.close(),l.reset(),g=``,c||se(),S=new EventSource(`${os}/api/terminal/stream?${c?`id=${encodeURIComponent(c)}&`:``}viewer=${f}`),S.addEventListener(`sessions`,e=>{if(s=JSON.parse(e.data).sessions,c?!s.some(e=>e.id===c):s.length)return ce(s.at(-1)?.id??null);oe()}),S.addEventListener(`none`,()=>{l.reset(),t.querySelectorAll(`.wb-term-placeholder`).forEach(e=>e.remove()),se()}),S.addEventListener(`screen`,e=>{let{d:n,cols:r,rows:i,active:a}=JSON.parse(e.data);l.reset(),m=r&&i?{cols:r,rows:i}:null,p=a??null,m&&l.resize(m.cols,m.rows),l.write(n,()=>{ee(),t.querySelectorAll(`.wb-term-placeholder`).forEach(e=>e.remove())}),se(),d()&&as.get(`wb-terminal-focus`)===`1`&&l.focus()}),S.addEventListener(`data`,e=>l.write(JSON.parse(e.data).d)),S.addEventListener(`navigate`,e=>{let{path:t}=JSON.parse(e.data);typeof t==`string`&&t.startsWith(`/`)&&!t.startsWith(`//`)&&location.assign(os+t)}),S.addEventListener(`size`,e=>{let{cols:t,rows:n,active:r}=JSON.parse(e.data);m={cols:t,rows:n},p=r??null,as.set(`wb-terminal-active`,_()?`1`:`0`),te()}),S.addEventListener(`exit`,e=>{let t=JSON.parse(e.data).code,n=s.find(e=>e.id===c);n&&(n.running=!1,n.exited=t),oe()})}addEventListener(`pagehide`,()=>as.set(`wb-terminal-focus`,e.contains(document.activeElement)?`1`:`0`)),oe(),C()}function cs(e,t){return fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}const ls=
|
|
41
|
+
this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(ns,Math.floor(u/e.css.cell.width)),rows:Math.max(rs,Math.floor(l/e.css.cell.height))}}};const as={get:e=>{try{return sessionStorage.getItem(e)}catch{return null}},set:(e,t)=>{try{sessionStorage.setItem(e,t)}catch{}}},os=(()=>{try{return JSON.parse(document.getElementById(`wb-page`)?.textContent??`{}`).base??``}catch{return``}})();function ss(e){let t=e.querySelector(`.wb-term-screen`),n=e.querySelector(`.wb-term-tabs`),r=e.querySelector(`.wb-term-status`),i=e.querySelector(`.wb-term-actions`),a=e.querySelector(`.wb-term-toggle`),o=e.querySelector(`.wb-term-grip`),s=[];try{({sessions:s}=JSON.parse(e.dataset.sessions??`{}`)),s??=[]}catch{}let c=e.dataset.tab??s[0]?.id??null,l=new ts({fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,fontSize:13,cursorBlink:!0,scrollback:5e3,scrollSensitivity:3,allowProposedApi:!0,theme:{background:`#0f1115`,foreground:`#d7dae0`,cursor:`#d7dae0`,selectionBackground:`#3a4150`}}),u=new is;l.loadAddon(u),l.open(t);let d=()=>e.dataset.state===`open`;if(new URLSearchParams(location.search).get(`terminal`)===`open`){as.set(`wb-terminal-open`,`1`);let e=new URL(location.href);e.searchParams.delete(`terminal`),history.replaceState(history.state,``,e)}let f=crypto.randomUUID(),p=null,m=null,h=as.get(`wb-terminal-active`)===`1`,g=``,_=()=>p===f;function ee(){if(!d()||!c)return;let e=u.proposeDimensions();if(!e?.cols||!e?.rows)return;let t=`${c} ${e.cols}x${e.rows} ${h}`;t!==g&&(g=t,cs(os+`/api/terminal/resize`,{id:c,viewer:f,cols:e.cols,rows:e.rows,active:h}),h&&=(p=f,!1)),te()}function te(){let e=u.proposeDimensions(),t=_()||!m?e:m;t?.cols&&t?.rows&&(t.cols!==l.cols||t.rows!==l.rows)&&l.resize(t.cols,t.rows)}function ne(){!_()&&c&&(h=!0,ee())}new ResizeObserver(()=>ee()).observe(t),l.textarea?.addEventListener(`focus`,ne);function re(t){let n=()=>{e.dataset.state=t?`open`:`collapsed`,as.set(`wb-terminal-open`,t?`1`:`0`)},r=document.startViewTransition;r&&!matchMedia(`(prefers-reduced-motion: reduce)`).matches?r.call(document,n):n(),requestAnimationFrame(()=>{t&&ne(),ee(),t&&l.focus()})}a.addEventListener(`click`,()=>re(!d())),addEventListener(`keydown`,e=>{e.ctrlKey&&e.key==="`"&&(e.preventDefault(),re(!d()))}),o.addEventListener(`pointerdown`,t=>{t.preventDefault(),o.setPointerCapture(t.pointerId),d()||re(!0);let n=e.querySelector(`.wb-term-bar`).offsetHeight,r=e=>{let t=Math.max(120,Math.min(innerHeight-80,innerHeight-e.clientY-n));document.documentElement.style.setProperty(`--wb-term-h`,`${Math.round(t)}px`)},i=()=>{o.removeEventListener(`pointermove`,r),o.removeEventListener(`pointerup`,i);let e=getComputedStyle(document.documentElement).getPropertyValue(`--wb-term-h`);as.set(`wb-terminal-height`,String(parseInt(e)||``)),ee()};o.addEventListener(`pointermove`,r),o.addEventListener(`pointerup`,i)});let ie=``,ae=Promise.resolve();l.onData(e=>{if(!c)return;ne();let t=c;ie||queueMicrotask(()=>{let e=ie;ie=``,ae=ae.then(()=>cs(os+`/api/terminal/input`,{id:t,data:e})).then(()=>{},()=>{})}),ie+=e});function v(e,t=[]){r.textContent=e,i.replaceChildren(...t.map(([e,t])=>{let n=document.createElement(`button`);return n.type=`button`,n.textContent=e,n.addEventListener(`click`,t),n}))}function oe(){n.replaceChildren(...s.map(e=>{let t=document.createElement(`span`);t.className=`wb-term-tab`,t.dataset.id=e.id,t.classList.toggle(`wb-current`,e.id===c),t.toggleAttribute(`data-exited`,!e.running);let n=document.createElement(`button`);n.type=`button`,n.className=`wb-term-tab-name`,n.textContent=e.label,n.title=e.running?e.label:`${e.label}: exited (${e.exited})`,n.addEventListener(`click`,()=>ce(e.id)),t.append(n);let r=document.createElement(`button`);return r.type=`button`,r.className=`wb-term-tab-close`,r.title=`Close this tab (ends its program)`,r.textContent=`×`,r.addEventListener(`click`,()=>b(e.id)),t.append(r),t})),se()}let y=document.createElement(`button`);y.type=`button`,y.className=`wb-term-add`,y.title=`A new tab with a shell`,y.textContent=`+`,y.addEventListener(`click`,()=>le({})),n.after(y);function se(){let e=s.find(e=>e.id===c);if(!e||e.running)return v(``,[]);v(e.exited==null?`stopped`:`exited (${e.exited})`,[[`Start again`,()=>le({id:e.id,restart:!0})]])}function ce(e){e===c&&S||(c=e,e&&as.set(`wb-terminal-tab`,e),oe(),C()),d()&&l.focus()}async function b(e){await cs(os+`/api/terminal/close`,{id:e}),s=s.filter(t=>t.id!==e),c===e?ce(s.at(-1)?.id??null):oe()}async function le(e){v(`starting…`);let t=await cs(os+`/api/terminal/start`,e),n=await t.json().catch(()=>({}));if(!t.ok)return v(n.error??`could not start`,[[`Try again`,()=>le(e)]]);await x(),d()||re(!0),ce(n.session),l.focus()}async function x(){try{let e=await fetch(os+`/api/terminal/sessions`);e.ok&&({sessions:s}=await e.json())}catch{}oe()}let S=null;function C(){S?.close(),l.reset(),g=``,c||se(),S=new EventSource(`${os}/api/terminal/stream?${c?`id=${encodeURIComponent(c)}&`:``}viewer=${f}`),S.addEventListener(`sessions`,e=>{if(s=JSON.parse(e.data).sessions,c?!s.some(e=>e.id===c):s.length)return ce(s.at(-1)?.id??null);oe()}),S.addEventListener(`none`,()=>{l.reset(),t.querySelectorAll(`.wb-term-placeholder`).forEach(e=>e.remove()),se()}),S.addEventListener(`screen`,e=>{let{d:n,cols:r,rows:i,active:a}=JSON.parse(e.data);l.reset(),m=r&&i?{cols:r,rows:i}:null,p=a??null,m&&l.resize(m.cols,m.rows),l.write(n,()=>{ee(),t.querySelectorAll(`.wb-term-placeholder`).forEach(e=>e.remove())}),se(),d()&&as.get(`wb-terminal-focus`)===`1`&&l.focus()}),S.addEventListener(`data`,e=>l.write(JSON.parse(e.data).d)),S.addEventListener(`navigate`,e=>{let{path:t}=JSON.parse(e.data);typeof t==`string`&&t.startsWith(`/`)&&!t.startsWith(`//`)&&location.assign(os+t)}),S.addEventListener(`size`,e=>{let{cols:t,rows:n,active:r}=JSON.parse(e.data);m={cols:t,rows:n},p=r??null,as.set(`wb-terminal-active`,_()?`1`:`0`),te()}),S.addEventListener(`exit`,e=>{let t=JSON.parse(e.data).code,n=s.find(e=>e.id===c);n&&(n.running=!1,n.exited=t),oe()})}addEventListener(`pagehide`,()=>as.set(`wb-terminal-focus`,e.contains(document.activeElement)?`1`:`0`)),oe(),C()}function cs(e,t){return fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}const ls=(e,t,n)=>{n.slot(`bottom`,e=>{let t=e.querySelector(`#wb-terminal`);t&&ss(t)})};export{ls as default};
|
|
@@ -303,10 +303,10 @@
|
|
|
303
303
|
--wb-term-h: 320px;
|
|
304
304
|
--wb-term-bar: 34px;
|
|
305
305
|
}
|
|
306
|
-
:root:has(
|
|
306
|
+
:root:has(#wb-terminal) {
|
|
307
307
|
--wb-inset-bottom: var(--wb-term-bar);
|
|
308
308
|
}
|
|
309
|
-
:root:has(
|
|
309
|
+
:root:has(#wb-terminal[data-state='open']) {
|
|
310
310
|
--wb-inset-bottom: calc(var(--wb-term-bar) + var(--wb-term-h));
|
|
311
311
|
}
|
|
312
312
|
|
|
@@ -328,7 +328,7 @@
|
|
|
328
328
|
system-ui,
|
|
329
329
|
sans-serif;
|
|
330
330
|
}
|
|
331
|
-
body:has(
|
|
331
|
+
body:has(#wb-terminal) {
|
|
332
332
|
padding-bottom: var(--wb-inset-bottom);
|
|
333
333
|
}
|
|
334
334
|
|
|
@@ -17,7 +17,7 @@ function toc(options = {}) {
|
|
|
17
17
|
style: "style.css",
|
|
18
18
|
setup: () => ({
|
|
19
19
|
client: "client.js",
|
|
20
|
-
|
|
20
|
+
slots: () => ({ head: html`<meta
|
|
21
21
|
name="wb-toc"
|
|
22
22
|
content="${options.always ? "always" : "opt-in"}"
|
|
23
23
|
${options.minWidth != null ? html` data-min-width="${String(options.minWidth)}"` : ""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=document.createElement(`nav`);e.className=`wb-toc`,e.setAttribute(`aria-label`,`Contents`);const t=document.createElement(`ol`);e.append(t);const n=document.createElement(`button`);n.type=`button`,n.className=`wb-toc-toggle`,n.title=n.ariaLabel=`Contents`,n.setAttribute(`aria-expanded`,`false`),n.innerHTML=`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M2.5 4h11M2.5 8h11M2.5 12h7"/></svg>`;let r,i,a=[];const o=()=>document.querySelector(`.wb-nav`)?.getBoundingClientRect().height??0;function s(){let t=parseFloat(getComputedStyle(e).minWidth)||0;return r.getBoundingClientRect().left>=t+40+16}const c=e=>{let t=/^(\d+(?:\.\d+)?)(px|em|rem|ch|vw)?$/.exec(String(e??``).trim());return t&&Number(t[1])>0?t[1]+(t[2]??`px`):null};function l(){let t=document.querySelector(`meta[name=wb-toc]`),n=d.settings(),r=n&&typeof n==`object`?n:{};for(let[n,i]of[[`minWidth`,`--wb-toc-min-width`],[`maxWidth`,`--wb-toc-max-width`]]){let a=c(r[n])??c(t?.dataset[n]);a?e.style.setProperty(i,a):e.style.removeProperty(i)}}function u(){let t=r.getBoundingClientRect().left;e.style.setProperty(`--wb-toc-right`,`${document.documentElement.clientWidth-t+40}px`),e.style.setProperty(`--wb-toc-room`,`${t-40-16}px`)}let d;function f(t){e.classList.toggle(`wb-toc-open`,t),e.hidden=!t,n.setAttribute(`aria-expanded`,String(t))}function p(){let e=d.settings(),t=document.querySelector(`meta[name=wb-toc]`)?.getAttribute(`content`)===`always`;return e===!1?!1:e===!0||e&&typeof e==`object`?!0:t}function m(e){let t=e.cloneNode(!0);return t.querySelectorAll(`.wb-badge`).forEach(e=>e.remove()),t.textContent?.trim()??``}function h(){a=p()?[...r.querySelectorAll(`:scope > :is(h2, h3, h4, h5, h6)`)]:[];let i=[0,0,0,0,0],o=[{level:1,list:t}];t.replaceChildren(),a.forEach((e,t)=>{let n=Number(e.tagName[1]);for(i[n-2]++,i.fill(0,n-1);o.length>1&&o.at(-1).level>=n;)o.pop();let r=o.at(-1);r.item&&!r.item.querySelector(`:scope > ol`)&&r.item.append(document.createElement(`ol`));let a=r.item?r.item.querySelector(`:scope > ol`):r.list,s=document.createElement(`li`);s.dataset.level=String(n);let c=document.createElement(`a`);c.href=`#`,c.dataset.index=String(t),c.innerHTML=`<span class="wb-toc-number"></span><span class="wb-toc-text"></span>`,c.querySelector(`.wb-toc-number`).textContent=i.slice(0,n-1).join(`.`),c.querySelector(`.wb-toc-text`).textContent=m(e),s.append(c),a.append(s),o.push({level:n,list:a,item:s})});let c=a.length>1;l(),u(),n.hidden=!c||s(),e.hidden=!c||!s()&&!e.classList.contains(`wb-toc-open`),e.classList.toggle(`wb-toc-docked`,s()),_(),v()}function g(e){let t=-1;for(let n=0;n<a.length&&a[n].compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING;n++)t=n;return t}function _(){let e=/* @__PURE__ */ new Set,n=new Set(i.unread().map(e=>e.id)),o=[...r.querySelectorAll(`form[data-wb-open]`),...[...r.querySelectorAll(`[data-wb-message]`)].filter(e=>n.has(e.dataset.wbMessage))];for(let t of o)e.add(g(t));for(let t of document.querySelectorAll(`[data-wb-holds]`)){if(!t.dataset.wbHolds.split(` `).some(e=>n.has(e)))continue;let r=t.getBoundingClientRect().top,i=-1;a.forEach((e,t)=>{e.getBoundingClientRect().top<=r&&(i=t)}),e.add(i)}t.querySelectorAll(`a`).forEach((t,n)=>t.toggleAttribute(`data-waiting`,e.has(n)))}function v(){let e=o()+40,n=0;a.forEach((t,r)=>{t.getBoundingClientRect().top<=e&&(n=r)}),t.querySelectorAll(`a`).forEach((e,t)=>e.toggleAttribute(`aria-current`,t===n&&a.length>0))}function y(e){let t=a[e];t&&(scrollTo({top:Math.max(0,scrollY+t.getBoundingClientRect().top-o()-12),behavior:`smooth`}),s()||f(!1))}const b=(a,o,s)=>{if(o.kind!==`page`&&o.kind!==`file`)return;d=o,r=a.querySelector(`#wb-main`)??a,i=s,
|
|
1
|
+
const e=document.createElement(`nav`);e.className=`wb-toc`,e.setAttribute(`aria-label`,`Contents`);const t=document.createElement(`ol`);e.append(t);const n=document.createElement(`button`);n.type=`button`,n.className=`wb-toc-toggle`,n.title=n.ariaLabel=`Contents`,n.setAttribute(`aria-expanded`,`false`),n.innerHTML=`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M2.5 4h11M2.5 8h11M2.5 12h7"/></svg>`;let r,i,a=[];const o=()=>document.querySelector(`.wb-nav`)?.getBoundingClientRect().height??0;function s(){let t=parseFloat(getComputedStyle(e).minWidth)||0;return r.getBoundingClientRect().left>=t+40+16}const c=e=>{let t=/^(\d+(?:\.\d+)?)(px|em|rem|ch|vw)?$/.exec(String(e??``).trim());return t&&Number(t[1])>0?t[1]+(t[2]??`px`):null};function l(){let t=document.querySelector(`meta[name=wb-toc]`),n=d.settings(),r=n&&typeof n==`object`?n:{};for(let[n,i]of[[`minWidth`,`--wb-toc-min-width`],[`maxWidth`,`--wb-toc-max-width`]]){let a=c(r[n])??c(t?.dataset[n]);a?e.style.setProperty(i,a):e.style.removeProperty(i)}}function u(){let t=r.getBoundingClientRect().left;e.style.setProperty(`--wb-toc-right`,`${document.documentElement.clientWidth-t+40}px`),e.style.setProperty(`--wb-toc-room`,`${t-40-16}px`)}let d;function f(t){e.classList.toggle(`wb-toc-open`,t),e.hidden=!t,n.setAttribute(`aria-expanded`,String(t))}function p(){let e=d.settings(),t=document.querySelector(`meta[name=wb-toc]`)?.getAttribute(`content`)===`always`;return e===!1?!1:e===!0||e&&typeof e==`object`?!0:t}function m(e){let t=e.cloneNode(!0);return t.querySelectorAll(`.wb-badge`).forEach(e=>e.remove()),t.textContent?.trim()??``}function h(){a=p()?[...r.querySelectorAll(`:scope > :is(h2, h3, h4, h5, h6)`)]:[];let i=[0,0,0,0,0],o=[{level:1,list:t}];t.replaceChildren(),a.forEach((e,t)=>{let n=Number(e.tagName[1]);for(i[n-2]++,i.fill(0,n-1);o.length>1&&o.at(-1).level>=n;)o.pop();let r=o.at(-1);r.item&&!r.item.querySelector(`:scope > ol`)&&r.item.append(document.createElement(`ol`));let a=r.item?r.item.querySelector(`:scope > ol`):r.list,s=document.createElement(`li`);s.dataset.level=String(n);let c=document.createElement(`a`);c.href=`#`,c.dataset.index=String(t),c.innerHTML=`<span class="wb-toc-number"></span><span class="wb-toc-text"></span>`,c.querySelector(`.wb-toc-number`).textContent=i.slice(0,n-1).join(`.`),c.querySelector(`.wb-toc-text`).textContent=m(e),s.append(c),a.append(s),o.push({level:n,list:a,item:s})});let c=a.length>1;l(),u(),n.hidden=!c||s(),e.hidden=!c||!s()&&!e.classList.contains(`wb-toc-open`),e.classList.toggle(`wb-toc-docked`,s()),_(),v()}function g(e){let t=-1;for(let n=0;n<a.length&&a[n].compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING;n++)t=n;return t}function _(){let e=/* @__PURE__ */ new Set,n=new Set(i.unread().map(e=>e.id)),o=[...r.querySelectorAll(`form[data-wb-open]`),...[...r.querySelectorAll(`[data-wb-message]`)].filter(e=>n.has(e.dataset.wbMessage))];for(let t of o)e.add(g(t));for(let t of document.querySelectorAll(`[data-wb-holds]`)){if(!t.dataset.wbHolds.split(` `).some(e=>n.has(e)))continue;let r=t.getBoundingClientRect().top,i=-1;a.forEach((e,t)=>{e.getBoundingClientRect().top<=r&&(i=t)}),e.add(i)}t.querySelectorAll(`a`).forEach((t,n)=>t.toggleAttribute(`data-waiting`,e.has(n)))}function v(){let e=o()+40,n=0;a.forEach((t,r)=>{t.getBoundingClientRect().top<=e&&(n=r)}),t.querySelectorAll(`a`).forEach((e,t)=>e.toggleAttribute(`aria-current`,t===n&&a.length>0))}function y(e){let t=a[e];t&&(scrollTo({top:Math.max(0,scrollY+t.getBoundingClientRect().top-o()-12),behavior:`smooth`}),s()||f(!1))}const b=(a,o,s)=>{if(o.kind!==`page`&&o.kind!==`file`)return;d=o,r=a.querySelector(`#wb-main`)??a,i=s,s.slot(`aside`,t=>(t.append(e),()=>e.remove())),s.slot(`header`,e=>(e.append(n),()=>n.remove())),t.addEventListener(`click`,e=>{let t=e.target.closest(`a[data-index]`);t&&(e.preventDefault(),y(Number(t.dataset.index)))}),n.addEventListener(`click`,()=>f(!e.classList.contains(`wb-toc-open`))),document.addEventListener(`keydown`,t=>{t.key===`Escape`&&e.classList.contains(`wb-toc-open`)&&n.click()});let c=0,l=e=>()=>{cancelAnimationFrame(c),c=requestAnimationFrame(e)};addEventListener(`scroll`,l(v),{passive:!0}),addEventListener(`resize`,l(h)),i.onRendered(h),o.settings.on(h),i.forms.on(()=>_()),i.events.on(()=>requestAnimationFrame(_)),h()};export{b as default};
|
|
@@ -23,9 +23,9 @@ ${kind}: needs a src, like ::${kind}[a label]{src="${kind === "image" ? "shot.pn
|
|
|
23
23
|
if (!safeSrc(src)) return html`<pre class="wb-error">${kind}: src must be an http(s) URL or a path, not ${src.split(":")[0]}:</pre>`;
|
|
24
24
|
const alt = ctx.labelText ?? ctx.attrs.alt ?? "";
|
|
25
25
|
const flag = (name) => name in ctx.attrs && raw(` ${name}`);
|
|
26
|
-
const poster = ctx.attrs.poster && safeSrc(ctx.attrs.poster) ? html` poster="${ctx.attrs.poster}"` : "";
|
|
27
|
-
return kind === "image" ? html`<img src="${src}" alt="${alt}" loading="lazy" />` : html`<video
|
|
28
|
-
src="${src}"
|
|
26
|
+
const poster = ctx.attrs.poster && safeSrc(ctx.attrs.poster) ? html` poster="${ctx.fileUrl(ctx.attrs.poster)}"` : "";
|
|
27
|
+
return kind === "image" ? html`<img src="${ctx.fileUrl(src)}" alt="${alt}" loading="lazy" />` : html`<video
|
|
28
|
+
src="${ctx.fileUrl(src)}"
|
|
29
29
|
controls${flag("loop")}${flag("autoplay")}${"autoplay" in ctx.attrs || "muted" in ctx.attrs ? raw(" muted") : ""}
|
|
30
30
|
playsinline
|
|
31
31
|
preload="metadata"
|
|
@@ -35,7 +35,7 @@ ${kind}: needs a src, like ::${kind}[a label]{src="${kind === "image" ? "shot.pn
|
|
|
35
35
|
/** What an image or video shows on its own, for the ↗ of a window around it: its file. */
|
|
36
36
|
const mediaOpen = (ctx) => {
|
|
37
37
|
const src = (ctx.attrs.src ?? "").trim();
|
|
38
|
-
return src && safeSrc(src) ? src : null;
|
|
38
|
+
return src && safeSrc(src) ? ctx.fileUrl(src) : null;
|
|
39
39
|
};
|
|
40
40
|
async function render(ctx) {
|
|
41
41
|
return windowFrame({
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { RUNTIME, pageDocument, pluginParts } from "./document.js";
|
|
2
|
+
import { toPath } from "./loader.js";
|
|
3
|
+
import { PACKAGE_DIR } from "./package.js";
|
|
4
|
+
import { pageSource, within } from "./site.js";
|
|
5
|
+
import { stripTypeScriptTypes } from "node:module";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
// src/build.ts
|
|
9
|
+
const ENGINE_DIR = PACKAGE_DIR;
|
|
10
|
+
const TYPESCRIPT = /\.m?ts$/i;
|
|
11
|
+
const typeScriptModule = (file) => stripTypeScriptTypes(fs.readFileSync(file, "utf8"));
|
|
12
|
+
/** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
|
|
13
|
+
const BUILD_SKIP = [
|
|
14
|
+
"form",
|
|
15
|
+
"chat",
|
|
16
|
+
"comments",
|
|
17
|
+
"draft"
|
|
18
|
+
];
|
|
19
|
+
/** In the folder a build writes, so that a next build knows it may replace it. */
|
|
20
|
+
const BUILD_MARK = ".whiteboard-build";
|
|
21
|
+
async function build({ project, config, hooks: setUp, files: served }, options = {}) {
|
|
22
|
+
const cfg = await config();
|
|
23
|
+
if (cfg.errors.length) throw new Error(`the config failed to load: ${cfg.errors[0].message}`);
|
|
24
|
+
if (!cfg.pages) throw new Error("the config has no pages renderer");
|
|
25
|
+
const pages = cfg.pages;
|
|
26
|
+
const defined = (...xs) => xs.find((x) => x !== void 0);
|
|
27
|
+
const patterns = defined(options.pages, cfg.build.pages) ?? [];
|
|
28
|
+
const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP);
|
|
29
|
+
const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? "site");
|
|
30
|
+
if (!patterns.length) throw new Error("nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config");
|
|
31
|
+
const warnings = [];
|
|
32
|
+
const include = patterns.filter((p) => !p.startsWith("!"));
|
|
33
|
+
const exclude = patterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
|
|
34
|
+
const files = [...new Set(include.flatMap((p) => fs.globSync(p, { cwd: project.dir }).map((f) => path.resolve(project.dir, f))))].filter((f) => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile()).filter((f) => !exclude.some((g) => path.matchesGlob(path.relative(project.dir, f), g))).sort();
|
|
35
|
+
if (!files.length) throw new Error(`no markdown files match ${patterns.join(" ")}`);
|
|
36
|
+
const base = files.map(path.dirname).reduce((a, b) => {
|
|
37
|
+
while (!within(b, a)) a = path.dirname(a);
|
|
38
|
+
return a;
|
|
39
|
+
});
|
|
40
|
+
const outOf = (file) => {
|
|
41
|
+
const rel = path.relative(base, file);
|
|
42
|
+
return path.join(outDir, /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel)) ? path.join(path.dirname(rel), "index.html") : rel.replace(/\.(md|markdown)$/i, ".html"));
|
|
43
|
+
};
|
|
44
|
+
const built = new Map(files.map((f) => [f, outOf(f)]));
|
|
45
|
+
if (fs.existsSync(outDir)) {
|
|
46
|
+
if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK))) throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`);
|
|
47
|
+
fs.rmSync(outDir, { recursive: true });
|
|
48
|
+
}
|
|
49
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
50
|
+
fs.writeFileSync(path.join(outDir, BUILD_MARK), "written by whiteboard build; the next build replaces this folder\n");
|
|
51
|
+
const copied = /* @__PURE__ */ new Map();
|
|
52
|
+
function copyAsset(file) {
|
|
53
|
+
const known = copied.get(file);
|
|
54
|
+
if (known) return known;
|
|
55
|
+
const rel = within(file, ENGINE_DIR) ? path.join("_", "whiteboard", path.relative(ENGINE_DIR, file)) : within(file, project.dir) ? path.join("_", "project", path.relative(project.dir, file)) : path.join("_", "files", path.basename(path.dirname(file)), path.basename(file));
|
|
56
|
+
const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, ".js") : rel);
|
|
57
|
+
copied.set(file, dest);
|
|
58
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
59
|
+
if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file));
|
|
60
|
+
else fs.copyFileSync(file, dest);
|
|
61
|
+
if (/\.css$/i.test(file)) for (const m of fs.readFileSync(file, "utf8").matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
|
|
62
|
+
const ref = m[1];
|
|
63
|
+
if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue;
|
|
64
|
+
const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ""));
|
|
65
|
+
if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target);
|
|
66
|
+
}
|
|
67
|
+
return dest;
|
|
68
|
+
}
|
|
69
|
+
/** a file beside the pages (an image), copied to its place below the site */
|
|
70
|
+
function copyBeside(file) {
|
|
71
|
+
if (!within(file, base)) return null;
|
|
72
|
+
const dest = path.join(outDir, path.relative(base, file));
|
|
73
|
+
if (!fs.existsSync(dest)) {
|
|
74
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
75
|
+
fs.copyFileSync(file, dest);
|
|
76
|
+
}
|
|
77
|
+
return dest;
|
|
78
|
+
}
|
|
79
|
+
const hooks = await setUp();
|
|
80
|
+
const result = {
|
|
81
|
+
out: outDir,
|
|
82
|
+
pages: [],
|
|
83
|
+
warnings
|
|
84
|
+
};
|
|
85
|
+
for (const [file, dest] of built) {
|
|
86
|
+
const here = path.dirname(dest);
|
|
87
|
+
const relTo = (target) => path.relative(here, target).split(path.sep).map(encodeURIComponent).join("/") || ".";
|
|
88
|
+
const assetHere = (ref) => relTo(copyAsset(toPath(ref)));
|
|
89
|
+
const urlFor = (abs) => {
|
|
90
|
+
for (const candidate of [abs, abs + ".md"]) {
|
|
91
|
+
if (!fs.existsSync(candidate)) continue;
|
|
92
|
+
if (fs.statSync(candidate).isDirectory()) {
|
|
93
|
+
const index = [...built.keys()].find((f) => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)));
|
|
94
|
+
if (index) return relTo(built.get(index));
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (built.has(candidate)) return relTo(built.get(candidate));
|
|
98
|
+
if (/\.(md|markdown)$/i.test(candidate)) {
|
|
99
|
+
warnings.push(`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`);
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const copy = copyBeside(candidate);
|
|
103
|
+
if (copy) return relTo(copy);
|
|
104
|
+
warnings.push(`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`);
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
};
|
|
109
|
+
const id = within(file, project.pagesDir) ? path.relative(project.pagesDir, file).split(path.sep).join("/").replace(/\.(md|markdown)$/i, "") : "-/" + path.relative(project.dir, file).split(path.sep).join("/");
|
|
110
|
+
const stored = pageSource(id, file);
|
|
111
|
+
if (stored.frontmatterError) warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`);
|
|
112
|
+
const context = {
|
|
113
|
+
project: {
|
|
114
|
+
name: project.name,
|
|
115
|
+
dir: project.dir,
|
|
116
|
+
files: served()
|
|
117
|
+
},
|
|
118
|
+
asset: assetHere,
|
|
119
|
+
urlFor,
|
|
120
|
+
live: false,
|
|
121
|
+
skip
|
|
122
|
+
};
|
|
123
|
+
const rendered = await pages.render(stored, context);
|
|
124
|
+
const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file)) ? path.basename(path.dirname(file)) : path.basename(file).replace(/\.(md|markdown)$/i, "");
|
|
125
|
+
const title = !rendered.title || rendered.title === id ? named : rendered.title;
|
|
126
|
+
const out = {
|
|
127
|
+
...rendered,
|
|
128
|
+
title,
|
|
129
|
+
html: String(rendered.html ?? ""),
|
|
130
|
+
head: String(rendered.head ?? "")
|
|
131
|
+
};
|
|
132
|
+
const parts = await pluginParts(hooks, null, {
|
|
133
|
+
asset: assetHere,
|
|
134
|
+
messages: [],
|
|
135
|
+
leaveOut: skip,
|
|
136
|
+
failed: (message) => warnings.push(`${path.relative(project.dir, file)}: ${message}`)
|
|
137
|
+
});
|
|
138
|
+
const doc = pageDocument(stored, {
|
|
139
|
+
page: true,
|
|
140
|
+
out,
|
|
141
|
+
notices: []
|
|
142
|
+
}, parts, {
|
|
143
|
+
live: false,
|
|
144
|
+
base: "",
|
|
145
|
+
asset: assetHere,
|
|
146
|
+
runtime: assetHere(RUNTIME),
|
|
147
|
+
title: project.name
|
|
148
|
+
});
|
|
149
|
+
fs.mkdirSync(here, { recursive: true });
|
|
150
|
+
fs.writeFileSync(dest, doc);
|
|
151
|
+
result.pages.push({
|
|
152
|
+
file,
|
|
153
|
+
to: dest
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
if (![...built.values()].includes(path.join(outDir, "index.html"))) warnings.push("no README.md or index.md in the top folder: the site has no index.html");
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
export { build };
|
|
@@ -866,7 +866,7 @@ function trackElsewhere(root, handle, core) {
|
|
|
866
866
|
current$1 = handle.id;
|
|
867
867
|
const nav = root.querySelector(".wb-nav");
|
|
868
868
|
if (!nav) return;
|
|
869
|
-
nav.querySelector(".wb-theme")?.before(box);
|
|
869
|
+
(nav.querySelector("[data-wb-slot=header]") ?? nav.querySelector(".wb-theme"))?.before(box);
|
|
870
870
|
toggle.addEventListener("click", () => open(!!list.hidden));
|
|
871
871
|
document.addEventListener("click", (e) => {
|
|
872
872
|
if (!box.contains(e.target)) open(false);
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { html, raw } from "./html.js";
|
|
2
|
+
import { PACKAGE_DIR } from "./package.js";
|
|
3
|
+
import _taggedTemplateLiteral from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
// src/document.ts
|
|
6
|
+
var _templateObject;
|
|
7
|
+
/** The browser runtime, built by build.ts. */
|
|
8
|
+
const RUNTIME = path.join(PACKAGE_DIR, "dist", "client", "runtime.js");
|
|
9
|
+
/** The page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts. */
|
|
10
|
+
const PAGE_CLIENT = path.join(PACKAGE_DIR, "dist", "src", "client", "page", "main.js");
|
|
11
|
+
/** The slots at the end of <body>, in the order they are there; `corner` is the page's dock. */
|
|
12
|
+
const BODY_SLOTS = [
|
|
13
|
+
"aside",
|
|
14
|
+
"bottom",
|
|
15
|
+
"overlay"
|
|
16
|
+
];
|
|
17
|
+
/**
|
|
18
|
+
* What the plugins add to a page: each one's markup for the slots (`slots`, asked with the browser's request, or
|
|
19
|
+
* null for a page no browser asked for), and its browser module. One that failed to start or fails
|
|
20
|
+
* here is left out and told to `failed`; so are those in `leaveOut` (a build's skip), silently.
|
|
21
|
+
*/
|
|
22
|
+
async function pluginParts(hooks, req, { asset, messages, leaveOut = /* @__PURE__ */ new Set(), failed }) {
|
|
23
|
+
const included = hooks.filter((h) => !leaveOut.has(h.name));
|
|
24
|
+
for (const h of included) if (h.error) failed(`plugin "${h.name}" failed to start: ${h.error.message}`);
|
|
25
|
+
const working = included.filter((h) => !h.error);
|
|
26
|
+
const parts = await Promise.all(working.map(async (h) => {
|
|
27
|
+
try {
|
|
28
|
+
return await h.slots?.(req) ?? null;
|
|
29
|
+
} catch (err) {
|
|
30
|
+
failed(`plugin "${h.name}" failed on this page: ${err.message}`);
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}));
|
|
34
|
+
const slotted = (slot) => working.flatMap((h, i) => {
|
|
35
|
+
const markup = parts[i]?.[slot];
|
|
36
|
+
return markup == null ? [] : [{
|
|
37
|
+
name: h.name,
|
|
38
|
+
html: raw(String(markup))
|
|
39
|
+
}];
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
head: parts.map((x) => raw(String(x?.head ?? ""))),
|
|
43
|
+
slots: {
|
|
44
|
+
aside: slotted("aside"),
|
|
45
|
+
bottom: slotted("bottom"),
|
|
46
|
+
overlay: slotted("overlay"),
|
|
47
|
+
corner: slotted("corner")
|
|
48
|
+
},
|
|
49
|
+
clients: working.filter((h) => h.client).map((h) => ({
|
|
50
|
+
name: h.name,
|
|
51
|
+
client: asset(h.client)
|
|
52
|
+
})),
|
|
53
|
+
messages
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
|
|
57
|
+
const frontmatterOf = (page) => page.kind === "page" ? page.frontmatter : {};
|
|
58
|
+
/** JSON made safe inside a <script>. */
|
|
59
|
+
const json = (s) => JSON.stringify(s).replace(/</g, "\\u003c");
|
|
60
|
+
const DOCK_STYLE = "#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:not(:has(> :not(:empty))){display:none}[data-wb-slot]:not(#wb-dock),[data-wb-slot]>[data-plugin]{display:contents}.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}.wb-toast{max-width:min(24rem,calc(100vw - 32px));text-align:left}.wb-toast-more{margin:0 -4px 0 -2px;padding:0 4px;opacity:.75}.wb-toast-more:hover{opacity:1}.wb-toast[data-open]{flex-wrap:wrap;border-radius:12px}.wb-toast-details{flex-basis:100%;padding:2px 0 3px;font-weight:400;cursor:text}.wb-toast-details[hidden]{display:none}";
|
|
61
|
+
/** Each plugin's own element in a slot, with what it rendered there. */
|
|
62
|
+
const slotted = (list) => list.map((x) => html`<div data-plugin="${x.name}">${x.html}</div>`);
|
|
63
|
+
/** A page as a document: the render, the plugins' parts, and the handoff for the browser runtime. */
|
|
64
|
+
function pageDocument(page, { page: rendered, out, notices }, parts, o) {
|
|
65
|
+
const handoff = {
|
|
66
|
+
id: page.id,
|
|
67
|
+
kind: page.kind,
|
|
68
|
+
live: o.live,
|
|
69
|
+
base: o.base,
|
|
70
|
+
client: rendered ? o.asset(PAGE_CLIENT) : null,
|
|
71
|
+
data: out.data ?? null,
|
|
72
|
+
frontmatter: frontmatterOf(page),
|
|
73
|
+
plugins: parts.clients,
|
|
74
|
+
messages: parts.messages,
|
|
75
|
+
...o.stamps && { stamps: o.stamps }
|
|
76
|
+
};
|
|
77
|
+
return String(html(_templateObject || (_templateObject = _taggedTemplateLiteral([
|
|
78
|
+
"<!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n <title>",
|
|
79
|
+
"</title>\n <style>\n ",
|
|
80
|
+
"\n </style>\n ",
|
|
81
|
+
"",
|
|
82
|
+
"\n </head>\n <body data-page=\"",
|
|
83
|
+
"\" data-kind=\"",
|
|
84
|
+
"\">\n ",
|
|
85
|
+
"\n <div id=\"wb-root\">",
|
|
86
|
+
"</div>\n <div id=\"wb-dock\" data-wb-slot=\"corner\">",
|
|
87
|
+
"</div>\n <script type=\"application/json\" id=\"wb-page\">\n ",
|
|
88
|
+
"\n <\/script>\n <script type=\"module\" src=\"",
|
|
89
|
+
"\"><\/script>\n ",
|
|
90
|
+
"\n </body>\n </html>"
|
|
91
|
+
])), out.title || page.id || o.title, DOCK_STYLE, raw(String(out.head ?? "")), parts.head, page.id, page.kind, notices.map((n) => html`<pre class="wb-error" role="alert">${n}</pre>`), raw(String(out.html)), slotted(parts.slots.corner), raw(json(handoff)), o.runtime, BODY_SLOTS.map((name) => html`<div data-wb-slot="${name}">${slotted(parts.slots[name])}</div>`)));
|
|
92
|
+
}
|
|
93
|
+
export { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts };
|
package/dist/src/events.js
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import { fromReader } from "./status.js";
|
|
1
|
+
import { CLAIM, PICKED, fromReader, pickedUp } from "./status.js";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import crypto from "node:crypto";
|
|
4
4
|
// src/events.ts
|
|
5
|
-
/**
|
|
6
|
-
* The type of the event `whiteboard new` appends when an agent session creates a page:
|
|
7
|
-
* `{ session }`. The colon keeps it apart from form names, which are event types too.
|
|
8
|
-
*/
|
|
9
|
-
const CLAIM = "whiteboard:claim";
|
|
10
5
|
/** An event id as the log has them: the time in base 36, a dash, random hex. */
|
|
11
6
|
const isEventId = (id) => typeof id === "string" && /^[0-9a-z]{6,12}-[0-9a-f]{6,32}$/.test(id);
|
|
12
7
|
/**
|
|
@@ -222,12 +217,6 @@ function matches(event, { page, type, exact } = {}) {
|
|
|
222
217
|
if (type && event.type !== type) return false;
|
|
223
218
|
return true;
|
|
224
219
|
}
|
|
225
|
-
/** The type of the event that says another event was handed to an agent: `{ event: <its id> }`. */
|
|
226
|
-
const PICKED = "whiteboard:picked";
|
|
227
|
-
/** The ids of the events that were picked up. Only the command line's picks count. */
|
|
228
|
-
function pickedUp(events) {
|
|
229
|
-
return new Set(events.filter((e) => e.type === "whiteboard:picked" && !fromReader(e)).map((e) => String(e.data?.event)));
|
|
230
|
-
}
|
|
231
220
|
/** Record that `event` was handed to an agent: from then on it counts as picked up. */
|
|
232
221
|
function pick(file, event) {
|
|
233
222
|
return appendEvent(file, {
|
|
@@ -253,7 +242,7 @@ const forAgent = (handedOut = /* @__PURE__ */ new Set()) => (type) => !type.incl
|
|
|
253
242
|
* `follow`, or when `signal` aborts.
|
|
254
243
|
*/
|
|
255
244
|
function handOut(file, filter, onEvent, options = {}) {
|
|
256
|
-
const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), skip, recheck } = options;
|
|
245
|
+
const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), skip, recheck, unpicked = false } = options;
|
|
257
246
|
return new Promise((resolve) => {
|
|
258
247
|
let got = 0;
|
|
259
248
|
let stop = () => {};
|
|
@@ -270,6 +259,7 @@ function handOut(file, filter, onEvent, options = {}) {
|
|
|
270
259
|
};
|
|
271
260
|
const left = /* @__PURE__ */ new Map();
|
|
272
261
|
const offer = (e) => {
|
|
262
|
+
if (unpicked && pickedUp(read(file).events).has(e.id)) return true;
|
|
273
263
|
if (skip?.(e)) {
|
|
274
264
|
left.set(e.id, e);
|
|
275
265
|
return true;
|
package/dist/src/hub.js
CHANGED
|
@@ -2,16 +2,30 @@ import { project } from "./config.js";
|
|
|
2
2
|
import { followEntries, machineDir, readMachineConfig, stateDir } from "./entries.js";
|
|
3
3
|
import { VERSION, compareVersions } from "./package.js";
|
|
4
4
|
import { createServer } from "./server.js";
|
|
5
|
+
import { holdStream, listenerOf } from "./listeners.js";
|
|
5
6
|
import fs from "node:fs";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
// src/hub.ts
|
|
8
9
|
function createHub({ dir = machineDir(), state = stateDir(), home, interval, onShutdown, version = VERSION } = {}) {
|
|
9
10
|
const served = /* @__PURE__ */ new Map();
|
|
10
11
|
const fallbacks = /* @__PURE__ */ new Map();
|
|
12
|
+
/** An entry's fallback held on one of its projects, followed there; false when the project refuses it. */
|
|
13
|
+
function hold(s, fb) {
|
|
14
|
+
const off = s.server.addListener(fb.listener);
|
|
15
|
+
if (!off) return false;
|
|
16
|
+
const unfollow = s.server.onListeners(() => fb.tell());
|
|
17
|
+
s.fallback = () => {
|
|
18
|
+
unfollow();
|
|
19
|
+
off();
|
|
20
|
+
delete s.fallback;
|
|
21
|
+
};
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
11
24
|
function sync(projects) {
|
|
12
25
|
setImmediate(() => touch());
|
|
13
26
|
const wanted = new Map(projects.map((p) => [`${p.base}\n${p.dir}`, p]));
|
|
14
27
|
for (const [key, s] of served) if (!wanted.has(key)) {
|
|
28
|
+
s.fallback?.();
|
|
15
29
|
s.server.close();
|
|
16
30
|
served.delete(key);
|
|
17
31
|
console.log(`whiteboard: ${s.base} is gone (${s.dir})`);
|
|
@@ -26,15 +40,17 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
|
|
|
26
40
|
label: [p.group, p.name].filter(Boolean).join(" › "),
|
|
27
41
|
onChange: () => changed(p.base)
|
|
28
42
|
});
|
|
29
|
-
const
|
|
30
|
-
served.set(key, {
|
|
43
|
+
const s = {
|
|
31
44
|
...p,
|
|
32
45
|
project: project$1,
|
|
33
|
-
server
|
|
34
|
-
|
|
35
|
-
|
|
46
|
+
server
|
|
47
|
+
};
|
|
48
|
+
served.set(key, s);
|
|
49
|
+
const fb = fallbacks.get(p.entry);
|
|
50
|
+
if (fb) hold(s, fb);
|
|
36
51
|
console.log(`whiteboard: ${p.base} → ${p.dir}`);
|
|
37
52
|
}
|
|
53
|
+
for (const fb of fallbacks.values()) fb.tell();
|
|
38
54
|
}
|
|
39
55
|
const overviewDir = path.join(state, "overview");
|
|
40
56
|
fs.mkdirSync(path.join(overviewDir, ".whiteboard", "pages"), { recursive: true });
|
|
@@ -230,43 +246,39 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
|
|
|
230
246
|
* The fallback of a whole entry (a `wait` or `watch` without --page in one of its projects): one
|
|
231
247
|
* per entry, refused (409) while another runs, or while a project of it has a fallback of its own
|
|
232
248
|
* (from a whiteboard before entries). Each project holds it as a listener, so its pages say an
|
|
233
|
-
* agent listens;
|
|
249
|
+
* agent listens; its stream is told each project of the entry with who listens there, at once and
|
|
250
|
+
* whenever that or the projects change. The command itself reads the projects' logs.
|
|
234
251
|
*/
|
|
235
252
|
function listenEntry(req, res, q) {
|
|
236
253
|
const entry = q.get("entry");
|
|
237
|
-
const projects = [...served.values()].filter((s) => s.entry === entry);
|
|
238
254
|
if (fallbacks.has(entry)) return sendJson(res, 409, { error: `another agent is the fallback of ${entry} already` });
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
type: q.get("type") || null,
|
|
244
|
-
command: q.get("command") === "wait" ? "wait" : "watch",
|
|
245
|
-
fallback: true
|
|
255
|
+
const mine = () => [...served.values()].filter((s) => s.entry === entry);
|
|
256
|
+
const fb = {
|
|
257
|
+
listener: listenerOf(q, true),
|
|
258
|
+
tell: () => {}
|
|
246
259
|
};
|
|
247
|
-
|
|
248
|
-
for (const s of
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
connection: "keep-alive"
|
|
253
|
-
});
|
|
254
|
-
res.write(": listening\n\n");
|
|
255
|
-
const ping = setInterval(() => res.write(": ping\n\n"), 25e3);
|
|
256
|
-
const end = () => {
|
|
257
|
-
clearInterval(ping);
|
|
258
|
-
if (fallbacks.get(entry) !== l) return;
|
|
259
|
-
fallbacks.delete(entry);
|
|
260
|
-
for (const s of served.values()) {
|
|
261
|
-
s.fallback?.();
|
|
262
|
-
delete s.fallback;
|
|
260
|
+
const held = [];
|
|
261
|
+
for (const s of mine()) {
|
|
262
|
+
if (!hold(s, fb)) {
|
|
263
|
+
for (const h of held) h.fallback?.();
|
|
264
|
+
return sendJson(res, 409, { error: `${s.base} has a fallback of its own already (a wait or watch without --page)` });
|
|
263
265
|
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
266
|
+
held.push(s);
|
|
267
|
+
}
|
|
268
|
+
fallbacks.set(entry, fb);
|
|
269
|
+
const stream = holdStream(req, res, () => {
|
|
270
|
+
closers.delete(stream.end);
|
|
271
|
+
if (fallbacks.get(entry) !== fb) return;
|
|
272
|
+
fallbacks.delete(entry);
|
|
273
|
+
for (const s of mine()) s.fallback?.();
|
|
268
274
|
});
|
|
269
|
-
|
|
275
|
+
fb.tell = () => stream.send("listeners", { projects: mine().map((s) => ({
|
|
276
|
+
dir: s.dir,
|
|
277
|
+
base: s.base,
|
|
278
|
+
listeners: s.server.listeners()
|
|
279
|
+
})) });
|
|
280
|
+
closers.add(stream.end);
|
|
281
|
+
fb.tell();
|
|
270
282
|
}
|
|
271
283
|
const closers = /* @__PURE__ */ new Set();
|
|
272
284
|
return {
|