slatebox-mcp 0.4.0 → 0.5.1
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 +13 -7
- package/generated/client.json +3271 -412
- package/generated/exec-tool.json +1752 -249
- package/generated/guest-client.js +1 -1
- package/generated/slate-viewer.html +589 -0
- package/generated/slatebox.d.ts +1240 -73
- package/package.json +5 -2
- package/src/apps.js +59 -0
- package/src/cli.js +5 -2
- package/src/client/index.js +6 -1
- package/src/describe.js +29 -10
- package/src/mcp.js +23 -2
- package/src/server.js +15 -6
- package/src/typed-tools.js +5 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// The exec guest prelude (one line, so the caller's code starts on line 2) and its trailer.
|
|
3
3
|
// Source run = PRELUDE + "\n" + code + TRAILER, as an async function body named run.js.
|
|
4
4
|
// It needs a global __slatebox.call(name, input) resolving to {ok:true,value} or {ok:false,error}.
|
|
5
|
-
export const PRELUDE = "const __sbx=(()=>{const C=__slatebox;class SlateboxError extends Error{constructor(e){super(String(e&&e.message||\"Slatebox refused the call.\"));this.name=\"SlateboxError\";this.code=String(e&&e.code||\"error\");this.status=Number(e&&e.status)||0;if(e&&e.details!==undefined)this.details=e.details;if(e&&e.retryAfter!==undefined)this.retryAfter=e.retryAfter;}}const plain=v=>v!==null&&typeof v===\"object\"&&!Array.isArray(v)&&(Object.getPrototypeOf(v)===Object.prototype||Object.getPrototypeOf(v)===null);const method=name=>async function(input,...rest){if(rest.length)throw new SlateboxError({code:\"invalid_request\",status:400,message:name+\" takes one object argument.\"});if(input===undefined)input={};if(!plain(input))throw new SlateboxError({code:\"invalid_request\",status:400,message:name+\" takes one plain object as its argument.\"});const r=await C.call(name,input);if(r&&r.ok)return r.value;throw new SlateboxError(r&&r.error);};const tree={};for(const n of [\"account.get\",\"agentTasks.create\",\"agentTasks.list\",\"agentTasks.update\",\"ai.audit.list\",\"ai.bindings.list\",\"ai.bindings.set\",\"ai.check\",\"ai.control.effective\",\"ai.control.get\",\"ai.control.health\",\"ai.control.reset\",\"ai.get\",\"ai.keys.list\",\"ai.keys.test\",\"ai.models.discover\",\"ai.models.save\",\"ai.models.test\",\"ai.prompts.get\",\"ai.prompts.list\",\"ai.prompts.render\",\"ai.prompts.saveDraft\",\"ai.prompts.test\",\"ai.providers.add\",\"ai.providers.save\",\"ai.update\",\"comments.add\",\"comments.list\",\"comments.remove\",\"comments.resolve\",\"components.get\",\"components.list\",\"instance.describe\",\"library.branch\",\"library.comment\",\"library.discard\",\"library.export\",\"library.fork\",\"library.get\",\"library.list\",\"library.mine\",\"library.review.approve\",\"library.review.open\",\"library.review.queue\",\"library.review.refine\",\"library.review.reject\",\"library.review.requestChanges\",\"library.review.unpublish\",\"library.review.update\",\"library.saveDraft\",\"library.stats\",\"library.submit\",\"library.withdraw\",\"media.lookup\",\"presence.plan\",\"presence.step\",\"presentations.create\",\"presentations.get\",\"presentations.setStyle\",\"shapes.apply\",\"shapes.generate\",\"shapes.list\",\"shapes.searchIcons\",\"slates.addMedia\",\"slates.applyOperations\",\"slates.checkMove\",\"slates.copy\",\"slates.create\",\"slates.delete\",\"slates.exportMermaid\",\"slates.get\",\"slates.importMermaid\",\"slates.issueInvite\",\"slates.list\",\"slates.redo\",\"slates.revokeInvite\",\"slates.undo\",\"suggestions.decide\",\"team.export\",\"teamImports.confirm\",\"teamImports.discard\",\"teamImports.get\",\"teamImports.invite\",\"teamImports.list\",\"teamImports.start\"]){const p=n.split(\".\");let t=tree;for(let i=0;i<p.length-1;i++)t=t[p[i]]||(t[p[i]]={});t[p[p.length-1]]=method(n);}const freeze=o=>{for(const k of Object.keys(o))if(typeof o[k]===\"object\")freeze(o[k]);return Object.freeze(o);};const logs=[];let size=0,cut=false;const fmt=a=>{if(typeof a===\"string\")return a;try{const j=JSON.stringify(a);return j===undefined?String(a):j;}catch{return String(a);}};const log=(...a)=>{if(cut)return;const line=a.map(fmt).join(\" \");size+=line.length+1;if(size>16384){cut=true;logs.push(\"[logs cut at 16 KiB]\");return;}logs.push(line);};const base=(()=>{const m=/run\\.js:(\\d+):/.exec(String(new Error().stack||\"\"));return m?Number(m[1]):1;})();const loc=e=>{const re=/run\\.js:(\\d+):(\\d+)/g;const s=String(e&&e.stack||\"\");let m;while((m=re.exec(s))){if(Number(m[1])>base)return{line:Number(m[1])-base,column:Number(m[2])};}return{};};const run=async f=>{try{const v=await f();if(v===undefined)return{ok:true,json:null,logs};let j;try{j=JSON.stringify(v);}catch(e){return{ok:false,error:{code:\"result_not_json\",message:\"Return a JSON value. \"+String(e&&e.message||\"\")},logs};}if(j===undefined)return{ok:false,error:{code:\"result_not_json\",message:\"Return a JSON value, not a function or a symbol.\"},logs};return{ok:true,json:j,logs};}catch(e){if(e&&e.name===\"InternalError\")throw e;const out={code:e instanceof SlateboxError?e.code:\"script_error\",message:String(e&&e.message||e),...loc(e)};if(e instanceof SlateboxError){out.status=e.status;if(e.details!==undefined)out.details=e.details;}return{ok:false,error:out,logs};}};return{slatebox:freeze(tree),SlateboxError,console:Object.freeze({log,info:log,warn:log,error:log,debug:log}),run};})();const slatebox=__sbx.slatebox,SlateboxError=__sbx.SlateboxError,console=__sbx.console;return await __sbx.run(async()=>{"
|
|
5
|
+
export const PRELUDE = "const __sbx=(()=>{const C=__slatebox;class SlateboxError extends Error{constructor(e){super(String(e&&e.message||\"Slatebox refused the call.\"));this.name=\"SlateboxError\";this.code=String(e&&e.code||\"error\");this.status=Number(e&&e.status)||0;if(e&&e.details!==undefined)this.details=e.details;if(e&&e.retryAfter!==undefined)this.retryAfter=e.retryAfter;}}const plain=v=>v!==null&&typeof v===\"object\"&&!Array.isArray(v)&&(Object.getPrototypeOf(v)===Object.prototype||Object.getPrototypeOf(v)===null);const method=name=>async function(input,...rest){if(rest.length)throw new SlateboxError({code:\"invalid_request\",status:400,message:name+\" takes one object argument.\"});if(input===undefined)input={};if(!plain(input))throw new SlateboxError({code:\"invalid_request\",status:400,message:name+\" takes one plain object as its argument.\"});const r=await C.call(name,input);if(r&&r.ok)return r.value;throw new SlateboxError(r&&r.error);};const tree={};for(const n of [\"account.get\",\"agentTasks.create\",\"agentTasks.list\",\"agentTasks.update\",\"ai.audit.list\",\"ai.bindings.list\",\"ai.bindings.set\",\"ai.check\",\"ai.control.effective\",\"ai.control.get\",\"ai.control.health\",\"ai.control.reset\",\"ai.get\",\"ai.keys.list\",\"ai.keys.test\",\"ai.models.discover\",\"ai.models.save\",\"ai.models.test\",\"ai.prompts.get\",\"ai.prompts.list\",\"ai.prompts.render\",\"ai.prompts.saveDraft\",\"ai.prompts.test\",\"ai.providers.add\",\"ai.providers.save\",\"ai.update\",\"comments.add\",\"comments.list\",\"comments.remove\",\"comments.resolve\",\"components.get\",\"components.list\",\"instance.describe\",\"library.branch\",\"library.comment\",\"library.discard\",\"library.export\",\"library.fork\",\"library.get\",\"library.list\",\"library.mine\",\"library.review.approve\",\"library.review.open\",\"library.review.queue\",\"library.review.refine\",\"library.review.reject\",\"library.review.requestChanges\",\"library.review.unpublish\",\"library.review.update\",\"library.saveDraft\",\"library.stats\",\"library.submit\",\"library.withdraw\",\"media.lookup\",\"personal.ideas.build\",\"personal.ideas.dismiss\",\"personal.ideas.list\",\"personal.ideas.refresh\",\"presence.plan\",\"presence.step\",\"presentations.create\",\"presentations.get\",\"presentations.setStyle\",\"profile.facts.add\",\"profile.facts.clear\",\"profile.facts.hide\",\"profile.facts.list\",\"profile.facts.remove\",\"profile.facts.update\",\"profile.settings.get\",\"projects.access\",\"projects.create\",\"projects.delete\",\"projects.get\",\"projects.list\",\"projects.moveSlate\",\"projects.share\",\"projects.slates\",\"projects.update\",\"security.draw\",\"security.get\",\"security.set\",\"shapes.apply\",\"shapes.generate\",\"shapes.list\",\"shapes.searchIcons\",\"slates.addMedia\",\"slates.applyOperations\",\"slates.checkMove\",\"slates.copy\",\"slates.create\",\"slates.delete\",\"slates.exportMermaid\",\"slates.get\",\"slates.importMermaid\",\"slates.issueInvite\",\"slates.list\",\"slates.live\",\"slates.redo\",\"slates.revokeInvite\",\"slates.undo\",\"slates.view\",\"suggestions.decide\",\"team.export\",\"teamImports.confirm\",\"teamImports.discard\",\"teamImports.get\",\"teamImports.invite\",\"teamImports.list\",\"teamImports.start\"]){const p=n.split(\".\");let t=tree;for(let i=0;i<p.length-1;i++)t=t[p[i]]||(t[p[i]]={});t[p[p.length-1]]=method(n);}const freeze=o=>{for(const k of Object.keys(o))if(typeof o[k]===\"object\")freeze(o[k]);return Object.freeze(o);};const logs=[];let size=0,cut=false;const fmt=a=>{if(typeof a===\"string\")return a;try{const j=JSON.stringify(a);return j===undefined?String(a):j;}catch{return String(a);}};const log=(...a)=>{if(cut)return;const line=a.map(fmt).join(\" \");size+=line.length+1;if(size>16384){cut=true;logs.push(\"[logs cut at 16 KiB]\");return;}logs.push(line);};const base=(()=>{const m=/run\\.js:(\\d+):/.exec(String(new Error().stack||\"\"));return m?Number(m[1]):1;})();const loc=e=>{const re=/run\\.js:(\\d+):(\\d+)/g;const s=String(e&&e.stack||\"\");let m;while((m=re.exec(s))){if(Number(m[1])>base)return{line:Number(m[1])-base,column:Number(m[2])};}return{};};const run=async f=>{try{const v=await f();if(v===undefined)return{ok:true,json:null,logs};let j;try{j=JSON.stringify(v);}catch(e){return{ok:false,error:{code:\"result_not_json\",message:\"Return a JSON value. \"+String(e&&e.message||\"\")},logs};}if(j===undefined)return{ok:false,error:{code:\"result_not_json\",message:\"Return a JSON value, not a function or a symbol.\"},logs};return{ok:true,json:j,logs};}catch(e){if(e&&e.name===\"InternalError\")throw e;const out={code:e instanceof SlateboxError?e.code:\"script_error\",message:String(e&&e.message||e),...loc(e)};if(e instanceof SlateboxError){out.status=e.status;if(e.details!==undefined)out.details=e.details;}return{ok:false,error:out,logs};}};return{slatebox:freeze(tree),SlateboxError,console:Object.freeze({log,info:log,warn:log,error:log,debug:log}),run};})();const slatebox=__sbx.slatebox,SlateboxError=__sbx.SlateboxError,console=__sbx.console;return await __sbx.run(async()=>{"
|
|
6
6
|
export const TRAILER = "\n});"
|
|
7
7
|
export const wrap = (code) => PRELUDE + "\n" + code + TRAILER
|
|
8
8
|
export default PRELUDE
|
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<meta name="referrer" content="no-referrer">
|
|
7
|
+
<title>Slatebox slate</title>
|
|
8
|
+
<style>
|
|
9
|
+
:root {
|
|
10
|
+
--sb-bg: var(--color-background-primary, #ffffff);
|
|
11
|
+
--sb-bg2: var(--color-background-secondary, #f4f5f7);
|
|
12
|
+
--sb-text: var(--color-text-primary, #1f2328);
|
|
13
|
+
--sb-muted: var(--color-text-secondary, #5b636e);
|
|
14
|
+
--sb-border: var(--color-border-primary, #d8dce1);
|
|
15
|
+
--sb-accent: #2563eb;
|
|
16
|
+
--sb-font: var(--font-sans, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif);
|
|
17
|
+
color-scheme: light dark;
|
|
18
|
+
}
|
|
19
|
+
:root[data-theme="dark"] {
|
|
20
|
+
--sb-bg: var(--color-background-primary, #1b1d21);
|
|
21
|
+
--sb-bg2: var(--color-background-secondary, #25282d);
|
|
22
|
+
--sb-text: var(--color-text-primary, #eceef1);
|
|
23
|
+
--sb-muted: var(--color-text-secondary, #a4abb5);
|
|
24
|
+
--sb-border: var(--color-border-primary, #3a3f46);
|
|
25
|
+
--sb-accent: #6ea0ff;
|
|
26
|
+
}
|
|
27
|
+
* { box-sizing: border-box; }
|
|
28
|
+
html, body { margin: 0; padding: 0; background: var(--sb-bg); color: var(--sb-text); font: 13px/1.4 var(--sb-font); }
|
|
29
|
+
#app { display: flex; flex-direction: column; height: 460px; }
|
|
30
|
+
header { display: flex; align-items: center; gap: 8px; padding: 6px 8px 6px 12px; border-bottom: 1px solid var(--sb-border); min-height: 40px; }
|
|
31
|
+
#name { font-weight: 600; flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
32
|
+
#status { color: var(--sb-muted); font-size: 12px; white-space: nowrap; display: flex; align-items: center; gap: 5px; }
|
|
33
|
+
#status .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--sb-muted); display: inline-block; }
|
|
34
|
+
#status.live .dot { background: #1a9c55; }
|
|
35
|
+
button { font: inherit; color: var(--sb-text); background: var(--sb-bg2); border: 1px solid var(--sb-border); border-radius: 6px; padding: 4px 9px; cursor: pointer; }
|
|
36
|
+
button:hover { border-color: var(--sb-muted); }
|
|
37
|
+
button:focus-visible { outline: 2px solid var(--sb-accent); outline-offset: 1px; }
|
|
38
|
+
button.primary { background: var(--sb-accent); border-color: var(--sb-accent); color: #fff; }
|
|
39
|
+
button.icon { width: 30px; padding: 4px 0; text-align: center; }
|
|
40
|
+
button[hidden] { display: none; }
|
|
41
|
+
#stage { position: relative; flex: 1 1 auto; min-height: 0; background: var(--sb-bg2); overflow: hidden; touch-action: none; }
|
|
42
|
+
#stage.grabbing { cursor: grabbing; }
|
|
43
|
+
svg#canvas { width: 100%; height: 100%; display: block; user-select: none; -webkit-user-select: none; }
|
|
44
|
+
.note { cursor: pointer; }
|
|
45
|
+
.note text { pointer-events: none; }
|
|
46
|
+
.note.selected .shape { stroke: var(--sb-accent); stroke-width: 3; }
|
|
47
|
+
.label { paint-order: stroke; stroke: var(--sb-bg); stroke-width: 4px; stroke-linejoin: round; font-size: 12px; fill: var(--sb-muted); }
|
|
48
|
+
#message { position: absolute; left: 0; right: 0; top: 40%; text-align: center; color: var(--sb-muted); padding: 0 24px; }
|
|
49
|
+
#message[hidden] { display: none; }
|
|
50
|
+
footer { border-top: 1px solid var(--sb-border); padding: 6px 12px; display: flex; gap: 8px; align-items: center; min-height: 40px; }
|
|
51
|
+
#detail { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--sb-muted); }
|
|
52
|
+
#editor { display: none; flex: 1 1 auto; gap: 8px; align-items: center; }
|
|
53
|
+
#editor.open { display: flex; }
|
|
54
|
+
#editor textarea { flex: 1 1 auto; font: inherit; color: var(--sb-text); background: var(--sb-bg); border: 1px solid var(--sb-border); border-radius: 6px; padding: 4px 6px; resize: none; height: 30px; }
|
|
55
|
+
#note { color: var(--sb-muted); font-size: 12px; }
|
|
56
|
+
#note.error { color: #c62828; }
|
|
57
|
+
.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
|
58
|
+
</style>
|
|
59
|
+
</head>
|
|
60
|
+
<body>
|
|
61
|
+
<div id="app">
|
|
62
|
+
<header>
|
|
63
|
+
<div id="name">Slate</div>
|
|
64
|
+
<div id="status" role="status"><span class="dot"></span><span id="statusText">Loading</span></div>
|
|
65
|
+
<button id="refresh" type="button" hidden>Refresh</button>
|
|
66
|
+
<button id="zoomOut" class="icon" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
|
67
|
+
<button id="zoomIn" class="icon" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
|
68
|
+
<button id="fit" type="button" title="Show the whole slate">Fit</button>
|
|
69
|
+
<button id="expand" type="button" hidden>Full screen</button>
|
|
70
|
+
<button id="open" class="primary" type="button" disabled>Open in Slatebox</button>
|
|
71
|
+
</header>
|
|
72
|
+
<div id="stage">
|
|
73
|
+
<svg id="canvas" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="svgTitle"><title id="svgTitle">Slate</title><g id="world"></g></svg>
|
|
74
|
+
<div id="message">Loading the slate</div>
|
|
75
|
+
</div>
|
|
76
|
+
<footer>
|
|
77
|
+
<div id="detail">Select a note to read it. Drag to move around.</div>
|
|
78
|
+
<div id="editor">
|
|
79
|
+
<label class="sr" for="text">Note text</label>
|
|
80
|
+
<textarea id="text" maxlength="10000"></textarea>
|
|
81
|
+
<button id="save" class="primary" type="button">Save</button>
|
|
82
|
+
<button id="cancel" type="button">Cancel</button>
|
|
83
|
+
</div>
|
|
84
|
+
<button id="edit" type="button" hidden>Edit text</button>
|
|
85
|
+
<span id="note" aria-live="polite"></span>
|
|
86
|
+
</footer>
|
|
87
|
+
</div>
|
|
88
|
+
<script>
|
|
89
|
+
(function () {
|
|
90
|
+
"use strict";
|
|
91
|
+
var SVG_NS = "http://www.w3.org/2000/svg";
|
|
92
|
+
var META_KEY = "com.slatebox/view";
|
|
93
|
+
var POLL_MS = 5000;
|
|
94
|
+
// The view loads no fonts: a note's own font is used when the device has it, else the system sans-serif.
|
|
95
|
+
var SANS = "system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif";
|
|
96
|
+
var $ = function (id) { return document.getElementById(id); };
|
|
97
|
+
var world = $("world");
|
|
98
|
+
var svg = $("canvas");
|
|
99
|
+
|
|
100
|
+
// ---- the host connection (MCP Apps over postMessage) ---------------------------------
|
|
101
|
+
var nextId = 1;
|
|
102
|
+
var pending = {};
|
|
103
|
+
var host = { capabilities: {}, context: {} };
|
|
104
|
+
function post(message) { window.parent.postMessage(message, "*"); }
|
|
105
|
+
function request(method, params) {
|
|
106
|
+
var id = nextId++;
|
|
107
|
+
post({ jsonrpc: "2.0", id: id, method: method, params: params || {} });
|
|
108
|
+
return new Promise(function (resolve, reject) {
|
|
109
|
+
pending[id] = { resolve: resolve, reject: reject };
|
|
110
|
+
setTimeout(function () { if (pending[id]) { delete pending[id]; reject(new Error("The app did not answer.")); } }, 60000);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
function notify(method, params) { post({ jsonrpc: "2.0", method: method, params: params || {} }); }
|
|
114
|
+
function respond(id, result) { post({ jsonrpc: "2.0", id: id, result: result || {} }); }
|
|
115
|
+
|
|
116
|
+
window.addEventListener("message", function (event) {
|
|
117
|
+
if (event.source !== window.parent) return;
|
|
118
|
+
var m = event.data;
|
|
119
|
+
if (!m || typeof m !== "object" || m.jsonrpc !== "2.0") return;
|
|
120
|
+
if (!m.method) {
|
|
121
|
+
var waiting = pending[m.id];
|
|
122
|
+
if (!waiting) return;
|
|
123
|
+
delete pending[m.id];
|
|
124
|
+
if (m.error) waiting.reject(m.error); else waiting.resolve(m.result);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
var params = m.params && typeof m.params === "object" ? m.params : {};
|
|
128
|
+
switch (m.method) {
|
|
129
|
+
case "ui/notifications/tool-input":
|
|
130
|
+
if (params.arguments && typeof params.arguments.shareId === "string") state.shareId = params.arguments.shareId;
|
|
131
|
+
break;
|
|
132
|
+
case "ui/notifications/tool-result": onResult(params); break;
|
|
133
|
+
case "ui/notifications/tool-cancelled": showMessage("The slate was not shown."); setStatus("Stopped", false); break;
|
|
134
|
+
case "ui/notifications/host-context-changed": applyContext(params); break;
|
|
135
|
+
case "ui/resource-teardown": stop(); if (m.id !== undefined) respond(m.id, {}); break;
|
|
136
|
+
case "ping": if (m.id !== undefined) respond(m.id, {}); break;
|
|
137
|
+
default: if (m.id !== undefined) post({ jsonrpc: "2.0", id: m.id, error: { code: -32601, message: "Method not found" } });
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
function applyContext(context) {
|
|
142
|
+
if (!context || typeof context !== "object") return;
|
|
143
|
+
for (var key in context) host.context[key] = context[key];
|
|
144
|
+
var root = document.documentElement;
|
|
145
|
+
if (context.theme === "dark" || context.theme === "light") root.setAttribute("data-theme", context.theme);
|
|
146
|
+
var vars = context.styles && context.styles.variables;
|
|
147
|
+
if (vars && typeof vars === "object") {
|
|
148
|
+
for (var name in vars) {
|
|
149
|
+
var value = vars[name];
|
|
150
|
+
if (/^--[a-z0-9-]{1,60}$/.test(name) && typeof value === "string" && value.length < 200 && !/url\s*\(|expression\s*\(|[<>{};]/i.test(value)) root.style.setProperty(name, value);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
var modes = context.availableDisplayModes;
|
|
154
|
+
$("expand").hidden = !(Array.isArray(modes) && modes.indexOf("fullscreen") >= 0);
|
|
155
|
+
if (context.displayMode) $("expand").textContent = context.displayMode === "fullscreen" ? "Exit full screen" : "Full screen";
|
|
156
|
+
size();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function size() {
|
|
160
|
+
var app = $("app");
|
|
161
|
+
var dims = host.context.containerDimensions || {};
|
|
162
|
+
var height = 460;
|
|
163
|
+
if (host.context.displayMode === "fullscreen") height = typeof dims.height === "number" ? dims.height : window.innerHeight;
|
|
164
|
+
else if (typeof dims.height === "number") height = dims.height;
|
|
165
|
+
else if (typeof dims.maxHeight === "number") height = Math.min(460, dims.maxHeight);
|
|
166
|
+
app.style.height = Math.max(260, Math.round(height)) + "px";
|
|
167
|
+
notify("ui/notifications/size-changed", { width: Math.round(document.documentElement.scrollWidth), height: Math.round(app.getBoundingClientRect().height) });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---- what is shown ------------------------------------------------------------------
|
|
171
|
+
var state = { shareId: null, name: "", url: null, canEdit: false, revision: null, picture: null, selected: null };
|
|
172
|
+
var grant = null; // { token, expiresAt, url }: kept here only
|
|
173
|
+
var pollTimer = null;
|
|
174
|
+
var stopped = false;
|
|
175
|
+
|
|
176
|
+
function setStatus(text, live) {
|
|
177
|
+
$("statusText").textContent = text;
|
|
178
|
+
$("status").className = live ? "live" : "";
|
|
179
|
+
}
|
|
180
|
+
function showMessage(text) { var el = $("message"); el.textContent = text; el.hidden = !text; }
|
|
181
|
+
function say(text, isError) { var el = $("note"); el.textContent = text || ""; el.className = isError ? "error" : ""; }
|
|
182
|
+
function firstText(result) {
|
|
183
|
+
var c = result && Array.isArray(result.content) ? result.content : [];
|
|
184
|
+
for (var i = 0; i < c.length; i++) if (c[i] && c[i].type === "text" && typeof c[i].text === "string") return c[i].text.split("\n")[0].slice(0, 300);
|
|
185
|
+
return "";
|
|
186
|
+
}
|
|
187
|
+
function safeLink(url) {
|
|
188
|
+
try {
|
|
189
|
+
var u = new URL(url);
|
|
190
|
+
if (u.protocol === "https:" || (u.protocol === "http:" && /^(localhost|127\.0\.0\.1)$/.test(u.hostname))) return u.href;
|
|
191
|
+
} catch (e) {}
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function onResult(result) {
|
|
196
|
+
var meta = result && result._meta && result._meta[META_KEY];
|
|
197
|
+
var sc = result && result.structuredContent;
|
|
198
|
+
var data = sc && sc.result && typeof sc.result === "object" ? sc.result : sc;
|
|
199
|
+
if (!result || result.isError || !meta || !data) {
|
|
200
|
+
showMessage(firstText(result) || "The slate could not be shown.");
|
|
201
|
+
setStatus("Not shown", false);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
state.shareId = typeof data.shareId === "string" ? data.shareId : state.shareId;
|
|
205
|
+
state.name = typeof data.name === "string" ? data.name : "";
|
|
206
|
+
state.url = safeLink(data.url);
|
|
207
|
+
state.canEdit = data.canEdit === true;
|
|
208
|
+
state.revision = typeof data.revision === "number" ? data.revision : null;
|
|
209
|
+
grant = typeof meta.token === "string" && typeof meta.url === "string" && safeLink(meta.url)
|
|
210
|
+
? { token: meta.token, expiresAt: Number(meta.expiresAt) || 0, url: safeLink(meta.url) } : null;
|
|
211
|
+
$("name").textContent = state.name || "Untitled slate";
|
|
212
|
+
var count = meta.picture && Array.isArray(meta.picture.nodes) ? meta.picture.nodes.length : 0;
|
|
213
|
+
$("svgTitle").textContent = "Slate: " + (state.name || "Untitled") + ", " + count + " notes";
|
|
214
|
+
$("open").disabled = !state.url;
|
|
215
|
+
$("refresh").hidden = true;
|
|
216
|
+
if (meta.picture) draw(meta.picture, false);
|
|
217
|
+
if (grant) { setStatus("Live", true); schedule(POLL_MS); } else setStatus("Snapshot", false);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function schedule(ms) {
|
|
221
|
+
clearTimeout(pollTimer);
|
|
222
|
+
if (!stopped) pollTimer = setTimeout(poll, ms);
|
|
223
|
+
}
|
|
224
|
+
var failures = 0;
|
|
225
|
+
function poll() {
|
|
226
|
+
if (!grant || stopped) return;
|
|
227
|
+
if (Date.now() >= grant.expiresAt) return paused();
|
|
228
|
+
if (document.visibilityState === "hidden") return schedule(POLL_MS);
|
|
229
|
+
fetch(grant.url, { method: "GET", headers: { Authorization: "Bearer " + grant.token }, cache: "no-store", credentials: "omit", referrerPolicy: "no-referrer", mode: "cors" })
|
|
230
|
+
.then(function (response) {
|
|
231
|
+
if (response.status === 401) { paused(); return null; }
|
|
232
|
+
if (response.status === 429) { schedule(POLL_MS * 2); return null; }
|
|
233
|
+
if (!response.ok) throw new Error(String(response.status));
|
|
234
|
+
return response.json();
|
|
235
|
+
})
|
|
236
|
+
.then(function (body) {
|
|
237
|
+
if (!body) return;
|
|
238
|
+
failures = 0;
|
|
239
|
+
if (body.picture && body.revision !== state.revision) { state.revision = body.revision; draw(body.picture, true); }
|
|
240
|
+
setStatus("Live", true);
|
|
241
|
+
schedule(POLL_MS);
|
|
242
|
+
})
|
|
243
|
+
.catch(function () {
|
|
244
|
+
failures++;
|
|
245
|
+
setStatus(failures > 3 ? "Updates are off here" : "Reconnecting", false);
|
|
246
|
+
if (failures <= 3) schedule(POLL_MS * 2);
|
|
247
|
+
else showRefresh();
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
function paused() {
|
|
251
|
+
grant = null;
|
|
252
|
+
setStatus("Paused", false);
|
|
253
|
+
showRefresh();
|
|
254
|
+
}
|
|
255
|
+
function showRefresh() {
|
|
256
|
+
$("refresh").hidden = !(host.capabilities && host.capabilities.serverTools && state.shareId);
|
|
257
|
+
if ($("refresh").hidden) say("Ask again to see the latest.");
|
|
258
|
+
}
|
|
259
|
+
function stop() { stopped = true; clearTimeout(pollTimer); grant = null; }
|
|
260
|
+
|
|
261
|
+
$("refresh").addEventListener("click", function () {
|
|
262
|
+
if (!state.shareId) return;
|
|
263
|
+
$("refresh").disabled = true;
|
|
264
|
+
setStatus("Refreshing", false);
|
|
265
|
+
request("tools/call", { name: "show_slate", arguments: { shareId: state.shareId } })
|
|
266
|
+
.then(function (result) { onResult(result); say(""); })
|
|
267
|
+
.catch(function () { setStatus("Paused", false); say("The slate could not be refreshed.", true); })
|
|
268
|
+
.then(function () { $("refresh").disabled = false; });
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
$("open").addEventListener("click", function () {
|
|
272
|
+
if (!state.url) return;
|
|
273
|
+
var url = state.url;
|
|
274
|
+
request("ui/open-link", { url: url })
|
|
275
|
+
.then(function (result) { if (result && result.isError) say("Open it at " + url); })
|
|
276
|
+
.catch(function () { say("Open it at " + url); });
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
$("expand").addEventListener("click", function () {
|
|
280
|
+
var mode = host.context.displayMode === "fullscreen" ? "inline" : "fullscreen";
|
|
281
|
+
request("ui/request-display-mode", { mode: mode }).then(function (result) {
|
|
282
|
+
if (result && result.mode) applyContext({ displayMode: result.mode });
|
|
283
|
+
}).catch(function () {});
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
// ---- the drawing --------------------------------------------------------------------
|
|
287
|
+
var POLYGONS = {
|
|
288
|
+
star: [[.5,0],[.618,.382],[1,.382],[.691,.618],[.809,1],[.5,.764],[.191,1],[.309,.618],[0,.382],[.382,.382]],
|
|
289
|
+
triangle: [[.5,0],[1,1],[0,1]],
|
|
290
|
+
pentagon: [[.5,0],[.976,.381],[.794,1],[.206,1],[.024,.381]],
|
|
291
|
+
hexagon: [[.25,0],[.75,0],[1,.5],[.75,1],[.25,1],[0,.5]],
|
|
292
|
+
octagon: [[.293,0],[.707,0],[1,.293],[1,.707],[.707,1],[.293,1],[0,.707],[0,.293]],
|
|
293
|
+
trapezium: [[.2,0],[.8,0],[1,1],[0,1]],
|
|
294
|
+
parallelogram: [[.2,0],[1,0],[.8,1],[0,1]],
|
|
295
|
+
rarrow: [[0,.25],[.7,.25],[.7,0],[1,.5],[.7,1],[.7,.75],[0,.75]],
|
|
296
|
+
larrow: [[1,.25],[.3,.25],[.3,0],[0,.5],[.3,1],[.3,.75],[1,.75]],
|
|
297
|
+
diamond: [[.5,0],[1,.5],[.5,1],[0,.5]]
|
|
298
|
+
};
|
|
299
|
+
var view = { x: 0, y: 0, k: 1 };
|
|
300
|
+
var byId = {};
|
|
301
|
+
|
|
302
|
+
function el(name, attrs, parent) {
|
|
303
|
+
var node = document.createElementNS(SVG_NS, name);
|
|
304
|
+
for (var key in attrs) if (attrs[key] !== null && attrs[key] !== undefined) node.setAttribute(key, String(attrs[key]));
|
|
305
|
+
if (parent) parent.appendChild(node);
|
|
306
|
+
return node;
|
|
307
|
+
}
|
|
308
|
+
function n(v, d) { return typeof v === "number" && isFinite(v) ? v : d; }
|
|
309
|
+
|
|
310
|
+
function shapeFor(node, g) {
|
|
311
|
+
var x = node.x, y = node.y, w = node.w, h = node.h;
|
|
312
|
+
var paint = { "class": "shape", fill: node.fill || "#ffffff", stroke: node.stroke || "#9aa3ae", "stroke-width": node.strokeWidth === null ? 1 : node.strokeWidth };
|
|
313
|
+
if (node.dash === "dashed") paint["stroke-dasharray"] = "8 5";
|
|
314
|
+
if (node.dash === "dotted") paint["stroke-dasharray"] = "2 4";
|
|
315
|
+
if (node.shape === "ellipse" || node.shape === "circle") {
|
|
316
|
+
paint.cx = x + w / 2; paint.cy = y + h / 2; paint.rx = w / 2; paint.ry = h / 2;
|
|
317
|
+
return el("ellipse", paint, g);
|
|
318
|
+
}
|
|
319
|
+
var points = POLYGONS[node.shape];
|
|
320
|
+
if (points) {
|
|
321
|
+
paint.points = points.map(function (p) { return (x + p[0] * w).toFixed(1) + "," + (y + p[1] * h).toFixed(1); }).join(" ");
|
|
322
|
+
return el("polygon", paint, g);
|
|
323
|
+
}
|
|
324
|
+
paint.x = x; paint.y = y; paint.width = w; paint.height = h;
|
|
325
|
+
paint.rx = node.shape === "roundedrectangle" ? Math.min(12, w / 4, h / 4) : node.shape === "stickynote" ? 3 : 2;
|
|
326
|
+
return el("rect", paint, g);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function wrap(text, maxChars, maxLines) {
|
|
330
|
+
var out = [];
|
|
331
|
+
var paragraphs = String(text || "").split(/\r?\n/);
|
|
332
|
+
for (var p = 0; p < paragraphs.length && out.length < maxLines; p++) {
|
|
333
|
+
var words = paragraphs[p].split(/\s+/).filter(Boolean);
|
|
334
|
+
var line = "";
|
|
335
|
+
if (!words.length) { out.push(""); continue; }
|
|
336
|
+
for (var i = 0; i < words.length; i++) {
|
|
337
|
+
var word = words[i];
|
|
338
|
+
while (word.length > maxChars) {
|
|
339
|
+
if (line) { out.push(line); line = ""; }
|
|
340
|
+
out.push(word.slice(0, maxChars)); word = word.slice(maxChars);
|
|
341
|
+
if (out.length >= maxLines) break;
|
|
342
|
+
}
|
|
343
|
+
if (out.length >= maxLines) break;
|
|
344
|
+
var next = line ? line + " " + word : word;
|
|
345
|
+
if (next.length > maxChars) { out.push(line); line = word; } else line = next;
|
|
346
|
+
if (out.length >= maxLines) break;
|
|
347
|
+
}
|
|
348
|
+
if (line && out.length < maxLines) out.push(line);
|
|
349
|
+
}
|
|
350
|
+
var all = String(text || "").replace(/\s+/g, " ").trim();
|
|
351
|
+
var shown = out.join(" ").replace(/\s+/g, " ").trim();
|
|
352
|
+
if (out.length && shown.length < all.length) out[out.length - 1] = out[out.length - 1].replace(/.?$/, "…");
|
|
353
|
+
while (out.length && out[out.length - 1] === "") out.pop();
|
|
354
|
+
return out;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function textFor(node, g) {
|
|
358
|
+
if (!node.text) return;
|
|
359
|
+
var size = n(node.fontSize, 16);
|
|
360
|
+
var lineHeight = size * 1.25;
|
|
361
|
+
var pad = 8;
|
|
362
|
+
var maxChars = Math.max(1, Math.floor((node.w - pad * 2) / (size * 0.56)));
|
|
363
|
+
var maxLines = Math.max(1, Math.floor((node.h - pad) / lineHeight));
|
|
364
|
+
var lines = wrap(node.text, maxChars, maxLines);
|
|
365
|
+
if (!lines.length) return;
|
|
366
|
+
var anchor = node.alignX === "left" ? "start" : node.alignX === "right" ? "end" : "middle";
|
|
367
|
+
var tx = node.alignX === "left" ? node.x + pad : node.alignX === "right" ? node.x + node.w - pad : node.x + node.w / 2;
|
|
368
|
+
var block = lines.length * lineHeight;
|
|
369
|
+
var top = node.alignY === "top" ? node.y + pad : node.alignY === "bottom" ? node.y + node.h - pad - block : node.y + (node.h - block) / 2;
|
|
370
|
+
var t = el("text", { x: tx, y: top, "text-anchor": anchor, "font-size": size, fill: node.color || "#1f2328",
|
|
371
|
+
"font-family": (node.fontFamily ? node.fontFamily + ", " : "") + SANS, "font-weight": node.bold ? "700" : null, "font-style": node.italic ? "italic" : null }, g);
|
|
372
|
+
for (var i = 0; i < lines.length; i++) {
|
|
373
|
+
var span = el("tspan", { x: tx, dy: i === 0 ? size : lineHeight }, t);
|
|
374
|
+
span.textContent = lines[i];
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function edgePoint(box, toward) {
|
|
379
|
+
var cx = box.x + box.w / 2, cy = box.y + box.h / 2;
|
|
380
|
+
var dx = toward.x - cx, dy = toward.y - cy;
|
|
381
|
+
if (!dx && !dy) return { x: cx, y: cy };
|
|
382
|
+
var sx = dx ? (box.w / 2) / Math.abs(dx) : Infinity;
|
|
383
|
+
var sy = dy ? (box.h / 2) / Math.abs(dy) : Infinity;
|
|
384
|
+
var s = Math.min(sx, sy);
|
|
385
|
+
return { x: cx + dx * s, y: cy + dy * s };
|
|
386
|
+
}
|
|
387
|
+
function arrow(at, from, color, width, parent) {
|
|
388
|
+
var angle = Math.atan2(at.y - from.y, at.x - from.x);
|
|
389
|
+
var len = 8 + width * 2, spread = 0.45;
|
|
390
|
+
var p1 = { x: at.x - len * Math.cos(angle - spread), y: at.y - len * Math.sin(angle - spread) };
|
|
391
|
+
var p2 = { x: at.x - len * Math.cos(angle + spread), y: at.y - len * Math.sin(angle + spread) };
|
|
392
|
+
el("polygon", { points: [at, p1, p2].map(function (p) { return p.x.toFixed(1) + "," + p.y.toFixed(1); }).join(" "), fill: color }, parent);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function drawLine(line, parent) {
|
|
396
|
+
var a = byId[line.from], b = byId[line.to];
|
|
397
|
+
if (!a || !b) return;
|
|
398
|
+
var ca = { x: a.x + a.w / 2, y: a.y + a.h / 2 }, cb = { x: b.x + b.w / 2, y: b.y + b.h / 2 };
|
|
399
|
+
var start = edgePoint(a, cb), end = edgePoint(b, ca);
|
|
400
|
+
var color = line.color || "#6b7280";
|
|
401
|
+
var width = line.width === null ? 2 : line.width;
|
|
402
|
+
var d, c1, c2;
|
|
403
|
+
if (line.straight) { d = "M" + start.x + "," + start.y + " L" + end.x + "," + end.y; c1 = start; c2 = end; }
|
|
404
|
+
else {
|
|
405
|
+
var horizontal = Math.abs(cb.x - ca.x) >= Math.abs(cb.y - ca.y);
|
|
406
|
+
c1 = horizontal ? { x: (start.x + end.x) / 2, y: start.y } : { x: start.x, y: (start.y + end.y) / 2 };
|
|
407
|
+
c2 = horizontal ? { x: (start.x + end.x) / 2, y: end.y } : { x: end.x, y: (start.y + end.y) / 2 };
|
|
408
|
+
d = "M" + start.x + "," + start.y + " C" + c1.x + "," + c1.y + " " + c2.x + "," + c2.y + " " + end.x + "," + end.y;
|
|
409
|
+
}
|
|
410
|
+
var g = el("g", { opacity: line.opacity === null ? null : line.opacity }, parent);
|
|
411
|
+
var path = el("path", { d: d, fill: "none", stroke: color, "stroke-width": width, "stroke-linecap": "round" }, g);
|
|
412
|
+
if (line.dash === "dashed") path.setAttribute("stroke-dasharray", "8 6");
|
|
413
|
+
if (line.dash === "dotted") path.setAttribute("stroke-dasharray", "2 5");
|
|
414
|
+
if (line.arrowEnd) arrow(end, c2, color, width, g);
|
|
415
|
+
if (line.arrowStart) arrow(start, c1, color, width, g);
|
|
416
|
+
if (line.label) {
|
|
417
|
+
var label = el("text", { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 - 4, "text-anchor": "middle", "class": "label" }, g);
|
|
418
|
+
label.textContent = line.label;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function draw(picture, keepView) {
|
|
423
|
+
if (!picture || !Array.isArray(picture.nodes)) return;
|
|
424
|
+
state.picture = picture;
|
|
425
|
+
byId = {};
|
|
426
|
+
while (world.firstChild) world.removeChild(world.firstChild);
|
|
427
|
+
var svgBg = picture.background || null;
|
|
428
|
+
$("stage").style.background = svgBg || "";
|
|
429
|
+
var nodes = picture.nodes, lines = Array.isArray(picture.lines) ? picture.lines : [];
|
|
430
|
+
for (var i = 0; i < nodes.length; i++) byId[nodes[i].id] = nodes[i];
|
|
431
|
+
var lineLayer = el("g", {}, world);
|
|
432
|
+
var noteLayer = el("g", {}, world);
|
|
433
|
+
for (var j = 0; j < lines.length; j++) drawLine(lines[j], lineLayer);
|
|
434
|
+
for (var k = 0; k < nodes.length; k++) {
|
|
435
|
+
var node = nodes[k];
|
|
436
|
+
var cx = node.x + node.w / 2, cy = node.y + node.h / 2;
|
|
437
|
+
var g = el("g", { "class": "note" + (state.selected === node.id ? " selected" : ""), transform: node.rotate ? "rotate(" + node.rotate + " " + cx + " " + cy + ")" : null, opacity: node.opacity === null ? null : node.opacity }, noteLayer);
|
|
438
|
+
g.setAttribute("data-id", node.id);
|
|
439
|
+
shapeFor(node, g);
|
|
440
|
+
textFor(node, g);
|
|
441
|
+
if (node.picture) {
|
|
442
|
+
var badge = el("text", { x: node.x + node.w - 6, y: node.y + node.h - 6, "text-anchor": "end", "font-size": 10, fill: "#6b7280", "font-style": "italic" }, g);
|
|
443
|
+
badge.textContent = "picture";
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
showMessage(nodes.length ? "" : "This slate has no notes yet.");
|
|
447
|
+
if (picture.truncated) say("Showing the first " + nodes.length + " notes. Open it in Slatebox for all of them.");
|
|
448
|
+
if (state.selected && !byId[state.selected]) select(null);
|
|
449
|
+
else if (state.selected) select(state.selected);
|
|
450
|
+
if (!keepView) fit(); else apply();
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function bounds() {
|
|
454
|
+
var nodes = state.picture ? state.picture.nodes : [];
|
|
455
|
+
if (!nodes.length) return { x: 0, y: 0, w: 800, h: 400 };
|
|
456
|
+
var x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;
|
|
457
|
+
for (var i = 0; i < nodes.length; i++) {
|
|
458
|
+
x1 = Math.min(x1, nodes[i].x); y1 = Math.min(y1, nodes[i].y);
|
|
459
|
+
x2 = Math.max(x2, nodes[i].x + nodes[i].w); y2 = Math.max(y2, nodes[i].y + nodes[i].h);
|
|
460
|
+
}
|
|
461
|
+
return { x: x1, y: y1, w: Math.max(1, x2 - x1), h: Math.max(1, y2 - y1) };
|
|
462
|
+
}
|
|
463
|
+
function fit() {
|
|
464
|
+
var box = bounds();
|
|
465
|
+
var r = svg.getBoundingClientRect();
|
|
466
|
+
var W = r.width || 600, H = r.height || 380, pad = 24;
|
|
467
|
+
var k = Math.min((W - pad * 2) / box.w, (H - pad * 2) / box.h, 2);
|
|
468
|
+
view.k = Math.max(0.02, k);
|
|
469
|
+
view.x = (W - box.w * view.k) / 2 - box.x * view.k;
|
|
470
|
+
view.y = (H - box.h * view.k) / 2 - box.y * view.k;
|
|
471
|
+
apply();
|
|
472
|
+
}
|
|
473
|
+
function apply() { world.setAttribute("transform", "translate(" + view.x.toFixed(2) + " " + view.y.toFixed(2) + ") scale(" + view.k.toFixed(4) + ")"); }
|
|
474
|
+
function zoomAt(factor, px, py) {
|
|
475
|
+
var k = Math.min(8, Math.max(0.02, view.k * factor));
|
|
476
|
+
view.x = px - (px - view.x) * (k / view.k);
|
|
477
|
+
view.y = py - (py - view.y) * (k / view.k);
|
|
478
|
+
view.k = k;
|
|
479
|
+
apply();
|
|
480
|
+
}
|
|
481
|
+
function center() { var r = svg.getBoundingClientRect(); return { x: r.width / 2, y: r.height / 2 }; }
|
|
482
|
+
$("zoomIn").addEventListener("click", function () { var c = center(); zoomAt(1.25, c.x, c.y); });
|
|
483
|
+
$("zoomOut").addEventListener("click", function () { var c = center(); zoomAt(0.8, c.x, c.y); });
|
|
484
|
+
$("fit").addEventListener("click", fit);
|
|
485
|
+
// The page scrolls with the wheel; zoom is a pinch (ctrl + wheel) or the buttons.
|
|
486
|
+
svg.addEventListener("wheel", function (event) {
|
|
487
|
+
if (!event.ctrlKey && !event.metaKey) return;
|
|
488
|
+
event.preventDefault();
|
|
489
|
+
var r = svg.getBoundingClientRect();
|
|
490
|
+
zoomAt(Math.exp(-event.deltaY * 0.01), event.clientX - r.left, event.clientY - r.top);
|
|
491
|
+
}, { passive: false });
|
|
492
|
+
|
|
493
|
+
var drag = null;
|
|
494
|
+
svg.addEventListener("pointerdown", function (event) {
|
|
495
|
+
drag = { x: event.clientX, y: event.clientY, vx: view.x, vy: view.y, moved: false, target: event.target };
|
|
496
|
+
svg.setPointerCapture(event.pointerId);
|
|
497
|
+
});
|
|
498
|
+
svg.addEventListener("pointermove", function (event) {
|
|
499
|
+
if (!drag) return;
|
|
500
|
+
var dx = event.clientX - drag.x, dy = event.clientY - drag.y;
|
|
501
|
+
if (!drag.moved && Math.abs(dx) + Math.abs(dy) < 4) return;
|
|
502
|
+
drag.moved = true;
|
|
503
|
+
$("stage").className = "grabbing";
|
|
504
|
+
view.x = drag.vx + dx; view.y = drag.vy + dy;
|
|
505
|
+
apply();
|
|
506
|
+
});
|
|
507
|
+
svg.addEventListener("pointerup", function (event) {
|
|
508
|
+
var was = drag;
|
|
509
|
+
drag = null;
|
|
510
|
+
$("stage").className = "";
|
|
511
|
+
if (!was || was.moved) return;
|
|
512
|
+
var hit = document.elementFromPoint(event.clientX, event.clientY);
|
|
513
|
+
var g = hit && hit.closest ? hit.closest(".note") : null;
|
|
514
|
+
select(g ? g.getAttribute("data-id") : null);
|
|
515
|
+
});
|
|
516
|
+
window.addEventListener("resize", function () { size(); });
|
|
517
|
+
document.addEventListener("keydown", function (event) { if (event.key === "Escape" && !$("editor").classList.contains("open")) select(null); });
|
|
518
|
+
|
|
519
|
+
// ---- reading and editing one note --------------------------------------------------
|
|
520
|
+
function select(id) {
|
|
521
|
+
var notes = world.querySelectorAll(".note");
|
|
522
|
+
for (var i = 0; i < notes.length; i++) notes[i].classList.toggle("selected", notes[i].getAttribute("data-id") === id);
|
|
523
|
+
var changed = state.selected !== id;
|
|
524
|
+
state.selected = id && byId[id] ? id : null;
|
|
525
|
+
var node = state.selected ? byId[state.selected] : null;
|
|
526
|
+
$("detail").textContent = node ? (node.text || "(no text)") : "Select a note to read it. Drag to move around.";
|
|
527
|
+
$("edit").hidden = !(node && state.canEdit && host.capabilities.serverTools);
|
|
528
|
+
if (changed && node && host.capabilities.updateModelContext) {
|
|
529
|
+
request("ui/update-model-context", { content: [{ type: "text", text: "On the slate " + state.shareId + " the person selected the note " + node.id + ": " + JSON.stringify(String(node.text || "").slice(0, 300)) }] }).catch(function () {});
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
function closeEditor() { $("editor").classList.remove("open"); $("detail").hidden = false; select(state.selected); }
|
|
533
|
+
$("edit").addEventListener("click", function () {
|
|
534
|
+
var node = state.selected && byId[state.selected];
|
|
535
|
+
if (!node) return;
|
|
536
|
+
$("text").value = node.text || "";
|
|
537
|
+
$("detail").hidden = true;
|
|
538
|
+
$("edit").hidden = true;
|
|
539
|
+
$("editor").classList.add("open");
|
|
540
|
+
$("text").focus();
|
|
541
|
+
say("");
|
|
542
|
+
});
|
|
543
|
+
$("cancel").addEventListener("click", closeEditor);
|
|
544
|
+
$("text").addEventListener("keydown", function (event) {
|
|
545
|
+
if (event.key === "Escape") closeEditor();
|
|
546
|
+
if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); $("save").click(); }
|
|
547
|
+
});
|
|
548
|
+
$("save").addEventListener("click", function () {
|
|
549
|
+
var id = state.selected;
|
|
550
|
+
if (!id || state.revision === null) return;
|
|
551
|
+
var text = $("text").value;
|
|
552
|
+
$("save").disabled = true;
|
|
553
|
+
say("Saving");
|
|
554
|
+
request("tools/call", { name: "edit_slate", arguments: {
|
|
555
|
+
shareId: state.shareId, expectedRevision: state.revision, userMessage: "Changed a note's text in the view of the slate.",
|
|
556
|
+
plan: { message: "Change the text of one note.", operations: [{ kind: "update_nodes", target: { ids: [id] }, changes: { text: text } }] }
|
|
557
|
+
} }).then(function (result) {
|
|
558
|
+
var sc = result && result.structuredContent;
|
|
559
|
+
var out = sc && sc.result;
|
|
560
|
+
if (!result || result.isError || !sc || sc.status === "failed") return say(firstText(result) || "The change was not saved.", true);
|
|
561
|
+
if (sc.status === "confirmation_required") return say("This change waits for you to agree in the conversation.");
|
|
562
|
+
closeEditor();
|
|
563
|
+
if (out && out.outcome === "suggested") say("Suggested on the slate: people there keep or discard it.");
|
|
564
|
+
else say("Saved.");
|
|
565
|
+
if (out && typeof out.revision === "number" && byId[id] && out.outcome !== "suggested") { byId[id].text = text; state.revision = out.revision; draw(state.picture, true); }
|
|
566
|
+
if (grant) schedule(1600);
|
|
567
|
+
}, function () { say("The change was not saved.", true); }).then(function () { $("save").disabled = false; });
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
// ---- start ----------------------------------------------------------------------------
|
|
571
|
+
request("ui/initialize", {
|
|
572
|
+
appInfo: { name: "slatebox-slate-viewer", version: "1.0.0" },
|
|
573
|
+
appCapabilities: { availableDisplayModes: ["inline", "fullscreen"] },
|
|
574
|
+
protocolVersion: "2026-01-26"
|
|
575
|
+
}).then(function (result) {
|
|
576
|
+
host.capabilities = (result && result.hostCapabilities) || {};
|
|
577
|
+
applyContext((result && result.hostContext) || {});
|
|
578
|
+
}, function () {}).then(function () {
|
|
579
|
+
notify("ui/notifications/initialized", {});
|
|
580
|
+
size();
|
|
581
|
+
});
|
|
582
|
+
// ChatGPT's own globals, when its bridge gave the result before this page listened.
|
|
583
|
+
if (window.openai && window.openai.toolResponseMetadata && window.openai.toolResponseMetadata[META_KEY]) {
|
|
584
|
+
onResult({ _meta: window.openai.toolResponseMetadata, structuredContent: window.openai.toolOutput });
|
|
585
|
+
}
|
|
586
|
+
})();
|
|
587
|
+
</script>
|
|
588
|
+
</body>
|
|
589
|
+
</html>
|