@loomcycle/explorer 0.16.0 → 0.16.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/dist/index.cjs +6 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +206 -198
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=require("react/jsx-runtime"),u=require("@loomcycle/client"),d=require("react-markdown");d=s(d,1);let f=require("remark-gfm");f=s(f,1);var p=`loomcycle.explorer.navigator`;function m(e){try{return e?.getItem(`loomcycle.explorer.navigator`)===`stars`?`stars`:`tree`}catch{return`tree`}}function h(e,t){try{e?.setItem(p,t)}catch{}}function g(e){return!!e&&!e.parent_id&&!!e.entity?.natural_key}function _(e){let t=e?.classes;if(!Array.isArray(t))return[];let n=new Set;for(let e of t){let{name:t,kind:r}=e??{};typeof t==`string`&&t!==``&&r!==`document`&&n.add(t)}return[...n].sort((e,t)=>e.localeCompare(t))}function v(e,t){let n=t??``;return n===``||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[n,...e]}function y(e){let t={op:e.op===`copy`?`copy_documents`:`move_documents`,scope:e.scope,to_scope:e.toScope,dry_run:e.dryRun};e.documentId&&(t.document_ids=[e.documentId]),e.underPath&&(t.under_path=e.underPath);let n=C(e.from),r=C(e.to);return n&&r&&n!==r&&(t.path_map={[n]:r}),e.op===`move`&&(e.dropDangling&&(t.dangling=`drop`),e.dryRun||(t.expect_count=e.expectCount??0)),t}function b(e){let t=e.to.trim();return t.startsWith(`/`)?e.op===`move`&&e.toScope===e.scope?`a move goes to another scope; to rename within this one, use rename / move`:e.op===`copy`&&e.toScope===e.scope&&C(t)===C(e.from)?`a copy into the same scope needs a new path`:null:`the new path must start with /`}function x(e,t){let n=t.counts??{},r=n.documents??0,i=e===`copy`?`copied`:`moved`,a=[],o=`${n.chunks??0} parts, ${n.revisions??0} revisions, ${n.statements??0} relations, ${n.assets??0} images`;if(t.dry_run)a.push(`${r} ${w(r,`document`)} would be ${i}: ${o}.`),t.to_finish?.length&&a.push(`${t.to_finish.length} ${w(t.to_finish.length,`document`)} left by an earlier interrupted move will be finished.`);else if(e===`move`){let e=t.moved?.length??0;a.push(`${e} ${w(e,`document`)} moved: ${o}.`)}else a.push(`${r} ${w(r,`document`)} copied: ${o}.`);let s=t.refused_count??t.refused?.length??0;if(s>0){a.push(`${s} ${w(s,`document`)} refused:`);for(let e of t.refused??[])a.push(` ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}`)}if(t.dangling_count>0){e===`copy`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set stay behind.`):t.dropped===void 0?t.blocked_by===`dangling_relations`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} join these documents to ones outside the set. A relation cannot span two scopes: include the other documents, or drop these relations.`):a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set will be dropped.`):a.push(`${t.dropped} ${w(t.dropped,`relation`)} to documents outside the set were dropped.`);for(let e of t.dangling??[])a.push(` ${e.kind}: ${e.from} → ${e.to} (outside: ${e.outside})`)}for(let e of t.unfinished??[])a.push(`not finished: ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}. Run the move again.`);for(let e of t.name_failures??[])a.push(`no name ${e.path} for ${e.document_id}: ${e.error}`);return t.body_failures&&a.push(`${t.body_failures} ${w(t.body_failures,`body`,`bodies`)} could not be written.`),t.statements_failed&&a.push(`${t.statements_failed} ${w(t.statements_failed,`relation`)} could not be written${t.statement_error?`: ${t.statement_error}`:``}.`),a}function S(e,t,n){return e===`move`&&t.dangling_count>0&&!n||(t.counts?.documents??0)===0&&!(t.to_finish?.length??0)}function C(e){let t=e.trim(),n=t.length;for(;n>1&&t[n-1]===`/`;)n--;return t.slice(0,n)}function w(e,t,n=t+`s`){return e===1?t:n}var T=4,E=5e3;function D(e,t,n){return{...O(e,n),pathLs:(t,n,r,i,a)=>e.path({op:`ls`,path:t,scope:n,recursive:r,...a?.limit?{limit:a.limit}:{},...a?.cursor?{cursor:a.cursor}:{}},i),pathIsStored:(t,n,r)=>e.path({op:`stat`,path:t,scope:n},r).then(()=>!0,e=>{if(e?.name===`SubstrateToolRefusedError`)return!1;throw e}),documentPath:async(t,n,r)=>{let i;for(let a=0;a<T;a++){let a=await e.path({op:`ls`,path:`/`,scope:n,recursive:!0,kind_filter:`document`,limit:E,...i?{cursor:i}:{}},r),o=(a.entries??[]).find(e=>e.resource_ref?.document_id===t);if(o)return o.full_path;if(i=a.next_cursor||void 0,!i)return}},pathMkdir:(t,n,r)=>e.path({op:`mkdir`,path:t,scope:n},r),pathMv:(t,n,r,i)=>e.path({op:`mv`,path:t,to:n,scope:r},i),pathRm:(t,n,r,i)=>e.path({op:`rm`,path:t,scope:n,recursive:r},i),documentCreate:(t,n,r,i)=>e.document({op:`create_document`,title:t,path:n,scope:r},i),documentDelete:(t,n,r)=>e.document({op:`delete_document`,id:t,scope:n},r),documentsTransfer:(t,n)=>e.document(y(t),n),documentGet:(t,n,r)=>e.document({op:`get_document`,id:t,scope:n},r),documentsSummary:(t,n,r)=>e.document({op:`documents_summary`,scope:n,...t.documentIds?{document_ids:t.documentIds}:{},...t.underPath?{under_path:t.underPath}:{}},r),documentQueryChunks:(t,n,r)=>e.document({op:`query_chunks`,document_id:t,scope:n,limit:1e3},r),documentGetChunk:(t,n,r)=>e.document({op:`get_chunk`,id:t,scope:n},r),documentCreateChunk:(t,n,r,i,a,o)=>e.document({op:`create_chunk`,document_id:t,parent_id:n,scope:i,...o?{after_id:o}:{},...r},a),documentReorderChunk:(t,n,r,i)=>e.document({op:`reorder_chunk`,id:t,direction:n,scope:r},i),documentDeleteChunk:(t,n,r)=>e.document({op:`delete_chunk`,id:t,scope:n},r),documentSetAsset:(t,n,r,i,a,o)=>e.document({op:`set_asset`,id:t,media_type:n,data:r,...i?{filename:i}:{},scope:a},o),documentGetEdges:(t,n,r,i)=>e.document({op:`get_edges`,document_id:t,scope:n,...i?.after?{after:i.after}:{}},r),documentGetEdge:(t,n,r)=>e.document({op:`get_edge`,id:t,scope:n},r),documentAcceptStatement:(t,n,r,i)=>e.document({op:`accept_statement`,id:t,scope:n,...i?{reason:i}:{}},r),documentRejectStatement:(t,n,r,i)=>e.document({op:`reject_statement`,id:t,reason:n,scope:r},i),documentListStatements:(t,n,r)=>e.document({op:`list_statements`,scope:t,...r?.status?{status:r.status}:{},...r?.kind?{kind:r.kind}:{},...r?.limit?{limit:r.limit}:{},...r?.after?{after:r.after}:{}},n),documentClassify:(t,n,r,i)=>e.document({op:`classify`,document_id:t,write:n,scope:r},i),documentEntityTypes:(t,n)=>e.document({op:`describe_ontology`,scope:t},n).then(_),documentAcceptClassification:(t,n,r)=>e.document({op:`accept_classification`,document_id:t,scope:n},r),documentUpdateChunk:(t,n,r,i,a)=>e.document({op:`update_chunk`,id:t,revision:n,scope:i,...r},a),documentExportMd:(t,n,r,i)=>e.document({op:`export_md`,document_id:t,scope:n,include_metadata:r},i),documentBacklinks:(t,n,r)=>e.document({op:`backlinks`,id:t,scope:n},r),documentRelated:(t,n,r,i)=>e.document({op:`related`,id:t,scope:n,...i?{limit:i}:{}},r),documentUnlinkedMentions:(t,n,r,i)=>e.document({op:`unlinked_mentions`,id:t,scope:n,...i?{limit:i}:{}},r),documentHistory:(t,n,r,i)=>e.document({op:`history`,id:t,scope:n,...i?{limit:i}:{}},r),documentGetVersion:(t,n,r,i)=>e.document({op:`get_version`,id:t,revision:n,scope:r},i),documentDiff:(t,n,r,i,a)=>e.document({op:`diff`,id:t,from_revision:n,to_revision:r,scope:i},a),documentExportCanvas:(t,n,r)=>e.document({op:`export_canvas`,document_id:t,scope:n},r),...t?{documentAssetObjectUrl:async(e,n,r)=>{let i=new URLSearchParams({scope:n});r?.scopeId&&i.set(`scope_id`,r.scopeId),r?.tenant&&i.set(`tenant`,r.tenant);let a=await t(`/v1/_document/asset/${encodeURIComponent(e)}?${i.toString()}`);if(!a.ok)throw Error(`asset fetch failed: ${a.status}`);let o=await a.blob();return URL.createObjectURL(o)}}:{}}}function O(e,t){let n=e,r=e=>e?.tenant?`?tenant=${encodeURIComponent(e.tenant)}`:``,i={};typeof n.ruleStatements==`function`?i.documentRuleStatements=(e,t)=>n.ruleStatements(e.action,e.ids?{ids:e.ids}:{filter:e.filter},{reason:e.reason,dryRun:e.dry_run,expectCount:e.expect_count,max:e.max,scope:e.scope,scopeId:e.scope_id,tenant:t?.tenant}):t&&(i.documentRuleStatements=(e,n)=>t(`/v1/_statements/rule${r(n)}`,e));let a=(e,t)=>e===`user`&&t?.scopeId?t.scopeId:void 0;return typeof n.revertRuling==`function`?i.documentRevertRuling=(e,t,r)=>n.revertRuling(e,{scope:t,scopeId:a(t,r),tenant:r?.tenant}):t&&(i.documentRevertRuling=(e,n,i)=>{let o=a(n,i);return t(`/v1/_statements/revert${r(i)}`,{ruling_id:e,scope:n,...o?{scope_id:o}:{}})}),i}var k=(0,c.createContext)(null);function A({value:e,children:t}){return(0,l.jsx)(k.Provider,{value:e,children:t})}function j(){let e=(0,c.useContext)(k);if(!e)throw Error(`useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)`);return e}var M=5e3;function N(e){return e===``?`/`:e}function ee(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function te(e){let t=[``],n=e.split(`/`).filter(Boolean),r=``;for(let e=0;e<n.length-1;e++)r=`${r}/${n[e]}`,t.push(r);return t}function P(e){return e instanceof Error?e.message:String(e)}function F(e,t){return{entries:[...t,...e.entries??[]],nextCursor:e.next_cursor||void 0,loaded:!0,loading:!1}}var ne=class{data;scope;browse;pageLimit;dirs=new Map;snapshot=new Map;listeners=new Set;inflight=new Map;epoch=new Map;constructor(e,t,n,r=500){this.data=e,this.scope=t,this.browse=n,this.pageLimit=r}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});publish(){this.snapshot=new Map(this.dirs),this.listeners.forEach(e=>e())}set(e,t){this.dirs.set(e,t),this.publish()}track(e,t){let n=t.finally(()=>{this.inflight.get(e)===n&&this.inflight.delete(e)});return this.inflight.set(e,n),n}loadDir(e){return this.inflight.get(e)||(this.dirs.get(e)?.loaded?Promise.resolve():this.fetchFirst(e,this.pageLimit))}reload(e){let t=this.dirs.get(e),n=t?.entries.length??0,r=t?.loaded&&!t.nextCursor?n+this.pageLimit:n;return this.fetchFirst(e,Math.min(M,Math.max(this.pageLimit,r)))}fetchFirst(e,t){let n=(this.epoch.get(e)??0)+1;this.epoch.set(e,n);let r=this.dirs.get(e);this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!0});let i=this.data.pathLs(N(e),this.scope,!1,this.browse,{limit:t}).then(t=>{this.epoch.get(e)===n&&this.set(e,F(t,[]))},t=>{throw this.epoch.get(e)===n&&this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!1,error:P(t)}),t});return this.track(e,i)}loadMore(e){let t=this.inflight.get(e);if(t)return t;let n=this.dirs.get(e);if(!n?.nextCursor)return Promise.resolve();let r=this.epoch.get(e)??0;this.set(e,{...n,loading:!0,error:void 0});let i=this.data.pathLs(N(e),this.scope,!1,this.browse,{limit:this.pageLimit,cursor:n.nextCursor}).then(t=>{this.epoch.get(e)===r&&this.set(e,F(t,n.entries))},t=>{throw this.epoch.get(e)===r&&this.set(e,{...n,loading:!1,error:P(t)}),t});return this.track(e,i)}async reveal(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){for(await this.loadDir(n);;){let t=this.dirs.get(n);if(!t)return!1;if(t.entries.some(t=>t.name===e))break;let r=t.entries[t.entries.length-1];if(!t.nextCursor||r&&r.name>e)return!1;let i=t.nextCursor;if(await this.loadMore(n),this.dirs.get(n)?.nextCursor===i)return!1}n=`${n}/${e}`}return!0}async invalidate(e,t){if(t?.dropSubtree){for(let t of[...this.dirs.keys()])(t===e||t.startsWith(`${e}/`))&&(this.dirs.delete(t),this.epoch.set(t,(this.epoch.get(t)??0)+1),this.inflight.delete(t));this.publish()}let n=te(e).filter(e=>this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}async refresh(e){let t=new Set(e);t.add(``);for(let e of[...this.dirs.keys()])t.has(e)||(this.dirs.delete(e),this.epoch.set(e,(this.epoch.get(e)??0)+1),this.inflight.delete(e));this.publish();let n=[...t].filter(e=>e===``||this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}};async function re(e,t,n,r){let i=[],a;for(;;){let o=await e.pathLs(N(t),n,!0,r,{limit:M,cursor:a});i.push(...o.entries??[]);let s=o.next_cursor||void 0;if(!s||s===a)return i;a=s}}function ie(e){let t=[];for(let n of e){if(n.kind!==`document`)continue;let e=n.resource_ref?.document_id;e&&t.push(e)}return t}function I(e){let t=e.fetch;return new u.LoomcycleClient({baseUrl:e.baseUrl,authToken:e.token||void 0,fetch:(e,n)=>t?t(e,n):fetch(e,n)})}function L(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return t=>{let r={};return e.token&&(r.Authorization=`Bearer ${e.token}`),n(e.baseUrl+t,{headers:r})}}var R=class extends Error{status;code;constructor(e,t,n){super(e),this.name=`RequestError`,this.status=t,this.code=n}};function z(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return async(t,r)=>{let i={"Content-Type":`application/json`,Accept:`application/json`};e.token&&(i.Authorization=`Bearer ${e.token}`);let a=await n(e.baseUrl+t,{method:`POST`,headers:i,body:JSON.stringify(r)}),o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!a.ok){let e=s&&typeof s==`object`?s:{};throw new R(typeof e.error==`string`&&e.error?e.error:`${a.status} ${a.statusText}`.trim(),a.status,typeof e.code==`string`?e.code:void 0)}return s}}function ae(e){let{dataLayer:t,client:n,connection:r}=e;return(0,c.useMemo)(()=>t||(n?D(n):r?D(I(r),L(r),z(r)):null),[t,n,r?.baseUrl,r?.token,r?.fetch])}function oe({theme:e,dataLayer:t,children:n}){let r=e?{"data-theme":e}:{};return t?(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsx)(A,{value:t,children:n})}):(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsxs)(`div`,{className:`error-banner`,children:[`@loomcycle/explorer: provide a `,(0,l.jsx)(`code`,{children:`connection`}),`, `,(0,l.jsx)(`code`,{children:`client`}),`, or`,` `,(0,l.jsx)(`code`,{children:`dataLayer`}),` prop.`]})})}function se(e,t,n){let r=e[e.length-1];return[...r&&r.documentId===t.documentId?[...e.slice(0,-1),{...r,...V(t)}]:[...e,t],n]}function B(e,t){return t<0||t>=e.length-1?e:e.slice(0,t+1)}function ce(e,t,n){let r=e[e.length-1];if(!r||r.documentId!==t)return e;let i={...r,...V(n)};return i.title===r.title&&i.path===r.path?e:[...e.slice(0,-1),i]}function V(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function H(e){return e.title?e.title:e.path?e.path.slice(e.path.lastIndexOf(`/`)+1)||e.path:e.documentId.slice(0,8)}function U(e,t=4){let n=Array.from({length:e},(e,t)=>({kind:`crumb`,index:t}));if(e<=t||t<3)return n;let r=t-1,i=Array.from({length:e-1-r},(e,t)=>t+1);return[n[0],{kind:`gap`,hidden:i},...n.slice(e-r)]}function le(e,t){for(let n of e.values()){let e=n.entries.find(e=>ue(e)===t);if(e)return e.full_path}}function ue(e){if(e.kind===`document`)return e.resource_ref?.document_id||void 0}function de(e,t){return t&&e.some(e=>e.id===t)?t:e.find(e=>!e.parent_id)?.id}function fe({trail:e,onJump:t}){let[n,r]=(0,c.useState)(!1);if(e.length<2)return null;let i=e.length-1,a=e[i-1],o=U(e.length,n?e.length:void 0);return(0,l.jsxs)(`nav`,{className:`doc-trail`,"aria-label":`Documents you came through`,children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-back`,onClick:()=>t(i-1),title:`Back to ${H(a)}`,children:`← Back`}),(0,l.jsx)(`ol`,{className:`doc-trail-list`,children:o.map(n=>n.kind===`gap`?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-gap`,onClick:()=>r(!0),title:`Show ${n.hidden.length} more: ${n.hidden.map(t=>H(e[t])).join(` › `)}`,"aria-label":`Show ${n.hidden.length} hidden documents`,children:`…`})},`gap`):n.index===i?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`page`,title:H(e[i]),children:H(e[i])})},n.index):(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>t(n.index),title:H(e[n.index]),children:H(e[n.index])})},n.index))})]})}function pe({data:e,scope:t,browse:n,documentId:r,underPath:i,fromPath:a,onClose:o,onDone:s}){let[u,d]=(0,c.useState)(`copy`),[f,p]=(0,c.useState)(t===`tenant`?`user`:`tenant`),[m,h]=(0,c.useState)(a),[g,_]=(0,c.useState)(!1),[v,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(!1),[O,k]=(0,c.useState)(null),A=(0,c.useMemo)(()=>({op:u,scope:t,toScope:f,documentId:r,underPath:i,from:a,to:m,dropDangling:g,dryRun:!0}),[u,t,f,r,i,a,m,g]),j=JSON.stringify(y(A)),M=b(A),N=v&&v.key===j?v.res:null,ee=N?S(u,N,g):!1,te=N?u===`move`?(N.counts?.documents??0)+(N.to_finish?.length??0):N.counts?.documents??0:0,P=async t=>{if(t.preventDefault(),w)o();else if(!M&&e.documentsTransfer){D(!0),k(null);try{if(!N)C({key:j,res:await e.documentsTransfer(A,n)});else{let t={...A,dryRun:!1,expectCount:N.counts?.documents??0},r=await e.documentsTransfer(t,n);T(r),s(t,r)}}catch(e){k(e instanceof Error?e.message:String(e))}finally{D(!1)}}},F=w?`close`:E?`working…`:N?`${u} ${te} document${te===1?``:`s`}`:`check`,ne=w??N;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:E?void 0:o,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:P,children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`Copy or move the `,r?`document`:`documents under`,` `,a]}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[!w&&(0,l.jsx)(`button`,{type:`button`,onClick:o,disabled:E,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:N&&u===`move`&&!w?`danger`:`primary`,disabled:E||!w&&(!!M||ee),children:F})]})]}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`A copy gets new ids and leaves the source as it is. A move keeps every id and removes the documents from `,(0,l.jsx)(`code`,{children:t}),`. Relations between the documents go with them.`]}),(0,l.jsx)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Copy or move`,children:[`copy`,`move`].map(e=>(0,l.jsx)(`button`,{type:`button`,"aria-pressed":u===e,className:u===e?`active`:void 0,disabled:E||!!w,onClick:()=>d(e),children:e},e))}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`To scope`}),(0,l.jsxs)(`select`,{value:f,disabled:E||!!w,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`New path`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:m,disabled:E||!!w,onChange:e=>h(e.target.value)})]}),u===`move`&&(0,l.jsx)(`label`,{className:`path-field`,children:(0,l.jsxs)(`span`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:g,disabled:E||!!w,onChange:e=>_(e.target.checked)}),` `,`Drop relations to documents outside the set`]})}),M&&(0,l.jsx)(`div`,{className:`modal-err`,children:M}),ne&&(0,l.jsx)(`div`,{className:`modal-context`,"aria-live":`polite`,children:x(u,ne).map((e,t)=>e.startsWith(` `)?(0,l.jsx)(`div`,{children:(0,l.jsx)(`code`,{children:e.trim()})},t):(0,l.jsx)(`div`,{children:e},t))}),O&&(0,l.jsx)(`div`,{className:`modal-err`,children:O})]})})}var W=6;function me({children:e,defaultLeftWidth:t=380,minLeftWidth:n=180,minRightWidth:r=240,storageKey:i,className:a,hideRight:o=!1}){let s=()=>{if(i){let e=localStorage.getItem(i),t=e?parseInt(e,10):NaN;if(Number.isFinite(t)&&t>=n)return t}return t},[u,d]=(0,c.useState)(s),[f,p]=(0,c.useState)(i);f!==i&&(p(i),d(s()));let m=(0,c.useRef)(null),[h,g]=(0,c.useState)(!1);(0,c.useEffect)(()=>{i&&!h&&f===i&&localStorage.setItem(i,String(Math.round(u)))},[i,f,u,h]);let _=(0,c.useCallback)(e=>{e.preventDefault(),g(!0),e.target.setPointerCapture(e.pointerId)},[]),v=(0,c.useCallback)(e=>{if(!h||!m.current)return;let t=m.current.getBoundingClientRect(),i=e.clientX-t.left,a=t.width-r-W;d(Math.max(n,Math.min(i,a)))},[h,n,r]),y=(0,c.useCallback)(e=>{g(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:m,className:`splitter ${a??``} ${h?`dragging`:``}`,style:{gridTemplateColumns:o?`1fr 0 0`:`min(${u}px, calc(100% - ${r+W}px)) ${W}px 1fr`},children:[(0,l.jsx)(`div`,{className:`splitter-pane splitter-left`,children:e[0]}),(0,l.jsx)(`div`,{hidden:o,className:`splitter-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-valuenow":Math.round(u),onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:y}),(0,l.jsx)(`div`,{className:`splitter-pane splitter-right`,hidden:o,children:e[1]})]})}var he=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`];function G(e){return he.includes(e)}function ge(e){return new Promise((t,n)=>{if(!G(e.type)){n(Error(`unsupported image type "${e.type||`unknown`}" (png, jpeg, gif, webp only)`));return}let r=new FileReader;r.onerror=()=>n(r.error??Error(`failed to read file`)),r.onload=()=>{let i=String(r.result??``),a=i.indexOf(`,`);a<0?n(Error(`could not decode image data`)):t({mediaType:e.type,data:i.slice(a+1)})},r.readAsDataURL(e)})}function _e(e){if(!e)return null;for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`file`&&G(n.type)){let e=n.getAsFile();if(e)return e}}return null}var ve=20;async function K(e,t,n,r,i=20){let a=[],o;for(let s=0;s<i;s++){let i=await e.documentGetEdges(t,n,r,o?{after:o}:void 0);if(o&&i.next_cursor===o)return{edges:a,incomplete:!0};if(a.push(...i.edges??[]),!i.truncated)return{edges:a,incomplete:!1};if(!i.next_cursor)return{edges:a,incomplete:!0};o=i.next_cursor}return{edges:a,incomplete:!0}}function ye(e,t){if(!t)return[];let n=new Map(e.map(e=>[e.id,e])),r=new Set([t]),i=[],a=n.get(t)?.parent_id;for(;a&&!r.has(a);){let e=n.get(a);if(!e)break;r.add(a),i.push(e),a=e.parent_id}return i.reverse()}var be=new Set([`manual`,`wikilink`]),xe=280;function Se(e){return e.status&&e.status!==`asserted`?e.status:void 0}function Ce(e){return e.method&&!be.has(e.method)?e.method:void 0}function we(e){return e.status===`proposed`&&!!e.id}function q(e){return new Date(Math.floor(e/1e6)).toISOString().slice(0,10)}function Te(e){let t=e.valid_at==null?void 0:q(e.valid_at),n=e.invalid_at==null?void 0:q(e.invalid_at);if(t&&n)return`valid ${t} → ${n}`;if(t)return`valid from ${t}`;if(n)return`valid until ${n}`}function Ee(e){if(e.judged_at==null)return;let t=`judged by ${e.judged_by||`a judge`} on ${q(e.judged_at)}`;return e.judge_reason?`${t}: ${e.judge_reason}`:t}function De(e,t=3){let n=(e.evidence??[]).slice(0,t),r=Math.max(e.evidence_count??0,e.evidence?.length??0);return{rows:n,more:Math.max(0,r-n.length)}}function Oe(e,t=xe){let n=e.replace(/\s+/g,` `).trim();return n.length>t?n.slice(0,t-1)+`…`:n}var J=1e3,Y=3,X=1e3;function ke(e){return!!e&&typeof e==`object`&&e.code===`queue_changed`}async function Ae(e,t,n={}){let r={action:t.action,...t.ids?{ids:t.ids}:{filter:t.filter??{}},...t.reason?{reason:t.reason}:{},...t.scope&&t.scope!==`tenant`?{scope:t.scope}:{},...t.scope===`user`&&t.scopeId?{scope_id:t.scopeId}:{}},i={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[]},a=async()=>{let t=await e.rule({...r,dry_run:!0});return i.skipped=t.skipped,t},o=async(e,t)=>!n.confirm||await n.confirm(e,t)?(i.total=i.ruled+e.matched,!0):(i.cancelled=!0,!1),s;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`first`))return i;let c=0;for(let t=0;t<X&&s.to_rule!==0;t++){let t;try{t=await e.rule({...r,dry_run:!1,expect_count:s.matched})}catch(e){if(!ke(e)||c>=3)return i.error=e,i;c++;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`queue_changed`))return i;continue}t.ruling_id&&i.rulingIds.push(t.ruling_id),i.ruled+=t.ruled,i.failed+=t.failed;for(let e of t.items??[])e.error&&i.failures.push(e);if(n.onProgress?.({ruled:i.ruled,failed:i.failed,total:i.total,chunks:i.rulingIds.length}),t.ruled===0||t.matched<=t.selected)break;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0)break;if(s.matched>i.total-i.ruled&&!await o(s,`grew`))return i}return i}async function je(e,t){let n={reverted:0,changed:0,errors:[]};for(let r of[...t].reverse())try{let t=await e(r);n.reverted+=t.reverted,n.changed+=t.changed}catch(e){n.errors.push(e instanceof Error?e.message:String(e))}return n}function Me(e){return Math.max(1,Math.ceil(e/J))}function Z(e){return e===`tenant`||e===`user`?e:void 0}function Ne(e,t){return e.documentRuleStatements?Z(t):void 0}function Pe(e,t){return e.filter(e=>we(e)&&!!e.id&&e.from_document_id===t)}function Fe(e,t,n,r){return e?{proposals:t,scope:e,incomplete:n,onChanged:r}:void 0}function Ie(e,t,n){return e.documentRuleStatements?Ae({rule:n=>e.documentRuleStatements(n,t.browse)},{action:t.action,...t.ids&&t.ids.length>0?{ids:t.ids}:{filter:{from_document_id:t.documentId}},...t.reason?{reason:t.reason}:{},scope:t.scope,...t.scope===`user`&&t.browse?.scopeId?{scopeId:t.browse.scopeId}:{}},n):Promise.reject(Error(`this data layer cannot rule in bulk`))}function Le(e,t){let n=e=>e.toLocaleString(`en-US`),r=[`${e===`accept`?`Accepted`:`Rejected`} ${n(t.ruled)} statement${t.ruled===1?``:`s`}`];return t.failed>0&&r.push(`${n(t.failed)} did not take the ruling`),t.skipped>0&&r.push(`${n(t.skipped)} skipped: not yours to rule`),r.join(`; `)+`.`}var Q={"doc.rfc.draft":`#c99a3a`,"doc.rfc.review":`#6a7bd6`,"doc.rfc.confirmed":`#3a9ad6`,"doc.rfc.done":`#3aa06a`,"doc.plan.draft":`#c99a3a`,"doc.plan.review":`#6a7bd6`,"doc.plan.confirmed":`#3a9ad6`,"doc.plan.done":`#3aa06a`,"doc.document.done":`#3aa06a`,"doc.research.done":`#8a6ad6`,"doc.publication.draft":`#c99a3a`,"chunk.draft":`#c99a3a`,"chunk.review":`#6a7bd6`,"chunk.confirmed":`#3a9ad6`,"chunk.done":`#3aa06a`,"chunk.backlog":`#8a8f98`,"chunk.implementation":`#d1863a`,"chunk.merged":`#3aa06a`},Re=.16;function ze(e){return e&&Object.keys(e).length>0?e:Q}function Be(e,t,n){let r=e??``,i=t??``;if(r&&i&&n[`doc.${r}.${i}`])return n[`doc.${r}.${i}`];if(r&&n[`doc.${r}`])return n[`doc.${r}`]}function $(e,t){let n=e??``;return n?t[`chunk.${n}`]:void 0}function Ve(e){let t=String(e[`chunk.inherit`]??``).trim().toLowerCase();return t!==`false`&&t!==`none`&&t!==`off`&&t!==`0`}function He(e,t=Re){let n=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!n)return;let r=n[1];return r.length===3&&(r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]),`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}function Ue(e){if(!e)return;let t=He(e);if(t)return{background:t,borderLeft:`3px solid ${e}`}}function We(e){if(!e)return;let t=He(e,Re/2);return t?{background:t}:void 0}function Ge(e){let{status:t,isRoot:n,documentColor:r,scheme:i}=e;if(i)return n?Ue(r)??Ue($(t,i)):Ue($(t,i))??(Ve(i)?We(r):void 0)}async function Ke(e){try{return typeof navigator>`u`||!navigator.clipboard?!1:(await navigator.clipboard.writeText(e),!0)}catch{return!1}}function qe({value:e,label:t,compact:n,title:r}){let[i,a]=(0,c.useState)(`idle`),o=async t=>{t.stopPropagation(),t.preventDefault();let n=await Ke(e);a(n?`copied`:`error`),window.setTimeout(()=>a(`idle`),n?1200:1500)},s=i===`copied`?`✓`:i===`error`?`✗`:`⎘`,u=r??`Copy ${t??`id`}: ${e}`,d=(0,l.jsx)(`button`,{type:`button`,className:`id-copy-btn id-copy-${i}`,onClick:o,title:u,"aria-label":u,children:s});return n?d:(0,l.jsxs)(`span`,{className:`id-copy`,children:[t&&(0,l.jsx)(`span`,{className:`id-copy-label`,children:t}),(0,l.jsx)(`code`,{className:`id-copy-value`,title:e,children:e}),d]})}function Je(e){let t=new Map;e.forEach(e=>t.set(e.id,{row:e,children:[]}));let n=[];e.forEach(e=>{let r=t.get(e.id);e.parent_id&&t.has(e.parent_id)?t.get(e.parent_id).children.push(r):n.push(r)});let r=e=>{e.sort((e,t)=>e.row.position-t.row.position),e.forEach(e=>r(e.children))};return r(n),n}function Ye(e){return e===`image`?`🖼`:e===`mermaid`?`📊`:``}function Xe(e,t){for(let n of e){if(n.row.id===t)return n;let e=Xe(n.children,t);if(e)return e}}function Ze({tree:e,selectedId:t,onSelect:n,colorEnabled:r,scheme:i,documentColor:a,linkedIds:o}){let[s,u]=(0,c.useState)(()=>new Map),d=(0,c.useCallback)(e=>{u(t=>{let n=new Map(t);return n.set(e,t.get(e)===!1),n})},[]);(0,c.useEffect)(()=>{if(!t)return;let n=Qe(e,t);n.length!==0&&u(e=>{let t=!1,r=new Map(e);for(let e of n)r.get(e)===!1&&(r.set(e,!0),t=!0);return t?r:e})},[e,t]);let f=r?ze(i):null;return e.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`No chunks.`})}):(0,l.jsx)(`ul`,{className:`tree chunk-tree`,children:e.map(e=>(0,l.jsx)($e,{node:e,expanded:s,toggle:d,selectedId:t,onSelect:n,tintScheme:f,documentColor:a,isRoot:!0,linkedIds:o},e.row.id))})}function Qe(e,t){let n=[],r=(e,i)=>{for(let a of e){if(a.row.id===t)return n.push(...i),!0;if(r(a.children,[...i,a.row.id]))return!0}return!1};return r(e,[]),n}function $e({node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,isRoot:s=!1,linkedIds:c}){let u=e.children.length>0,d=t.get(e.row.id)!==!1,f=r===e.row.id,p=Ge({status:e.row.status,isRoot:s,documentColor:o,scheme:a}),m=c?.has(e.row.id);return(0,l.jsxs)(`li`,{className:`node chunk-node ${f?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row chunk-row`,style:p,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":d?`collapse`:`expand`,disabled:!u,onClick:t=>{t.stopPropagation(),u&&n(e.row.id)},children:u?d?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`chunk-link`,onClick:()=>i(e),title:e.row.title,children:[Ye(e.row.type)&&(0,l.jsx)(`span`,{className:`chunk-type-icon`,"aria-hidden":!0,children:Ye(e.row.type)}),(0,l.jsx)(`span`,{className:`chunk-title`,children:e.row.title||`(untitled)`}),e.row.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:e.row.type}),e.row.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:e.row.status}),m&&(0,l.jsx)(`span`,{className:`chunk-link-badge`,title:`Has cross-reference links`,"aria-label":`linked`,children:`🔗`})]}),(0,l.jsx)(qe,{value:e.row.id,compact:!0,title:`Copy chunk id: ${e.row.id}`})]}),u&&d&&(0,l.jsx)(`ul`,{className:`children chunk-children`,children:e.children.map(e=>(0,l.jsx)($e,{node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,linkedIds:c},e.row.id))})]})}var et=0;function tt(e){let t=e?.closest(`g.node`);return t?/flowchart-(.+)-\d+$/.exec(t.id)?.[1]:void 0}function nt({code:e,onNodeClick:t}){let n=(0,c.useRef)(null),[r,i]=(0,c.useState)({});return(0,c.useEffect)(()=>{let t=!1;return(async()=>{try{let r=(await import(`mermaid`)).default,a=n.current?.closest(`[data-theme]`)?.getAttribute(`data-theme`),o=!a||a===`dark`;r.initialize({startOnLoad:!1,theme:o?`dark`:`default`,securityLevel:`strict`});let{svg:s}=await r.render(`lc-mmd-${et++}`,e);t||i({svg:s})}catch{t||i({err:!0})}})(),()=>{t=!0}},[e]),r.err?(0,l.jsx)(`pre`,{className:`md-pre md-mermaid-error`,title:`diagram failed to render`,children:(0,l.jsx)(`code`,{children:e})}):r.svg?(0,l.jsx)(`div`,{ref:n,className:t?`md-mermaid md-mermaid-nav`:`md-mermaid`,onClick:t&&(e=>{let n=tt(e.target);n&&t(n)}),dangerouslySetInnerHTML:{__html:r.svg}}):(0,l.jsx)(`div`,{ref:n,className:`md-mermaid md-mermaid-loading`,children:`rendering diagram…`})}function rt({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=j(),[o,s]=(0,c.useState)(e.title),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(e.status??``),[m,h]=(0,c.useState)(e.body??``),[g,_]=(0,c.useState)(e.fields?JSON.stringify(e.fields,null,2):``),[v,y]=(0,c.useState)((e.tags??[]).join(`, `)),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(!1),E=u===`mermaid`,D=u===`image`||!!e.asset,[O,k]=(0,c.useState)(m);(0,c.useEffect)(()=>{if(!E)return;let e=setTimeout(()=>k(m),400);return()=>clearTimeout(e)},[m,E]);let A=async o=>{C(null),x(!0);try{let{mediaType:s,data:c}=await ge(o);i(await a.documentSetAsset(e.id,s,c,o.name,t,n)),r()}catch(e){C(e instanceof Error?e.message:String(e)),x(!1)}},M=E?`Mermaid source`:D?`Caption (optional)`:`Body (Markdown)`;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal chunk-editor`,onClick:e=>e.stopPropagation(),onSubmit:async s=>{s.preventDefault(),C(null),T(!1);let c={body:m,title:o,type:u,status:f,tags:v.split(`,`).map(e=>e.trim()).filter(e=>e!==``)};if(g.trim()!==``)try{c.fields=JSON.parse(g)}catch{C(`fields must be valid JSON`);return}x(!0);try{i(await a.documentUpdateChunk(e.id,e.revision,c,t,n)),r()}catch(e){let t=e instanceof Error?e.message:String(e);C(t),T(/revision conflict/i.test(t)),x(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:`Edit chunk`}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:b,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:b,children:b?`saving…`:`save`})]})]}),S&&(0,l.jsxs)(`div`,{className:`modal-err`,children:[S,w&&` — reopen the chunk to load the latest, then reapply your edit.`]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Title`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:o,onChange:e=>s(e.target.value)})]}),(0,l.jsxs)(`div`,{className:`chunk-editor-row`,children:[(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:u,placeholder:`(none)`,onChange:e=>d(e.target.value)})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Status`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:f,placeholder:`(none)`,onChange:e=>p(e.target.value)})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Tags`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:v,placeholder:`comma-separated, nest with a slash: area/sub, priority/high`,onChange:e=>y(e.target.value)})]}),D&&(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Replace image`}),(0,l.jsx)(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:b,onChange:e=>{let t=e.target.files?.[0];t&&A(t)}})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:M}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-body-input`,rows:E?8:12,value:m,onChange:e=>h(e.target.value)})]}),E&&(0,l.jsxs)(`div`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Preview`}),(0,l.jsx)(`div`,{className:`chunk-mermaid-preview`,children:O.trim()?(0,l.jsx)(nt,{code:O}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(enter Mermaid source above)`})})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Fields (JSON, optional)`}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-fields-input`,rows:4,value:g,placeholder:`{}`,onChange:e=>_(e.target.value)})]})]})})}function it({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=j(),[o,s]=(0,c.useState)(null),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(null);(0,c.useEffect)(()=>{let e=!1;return a.documentEntityTypes?.(t,n).then(t=>{e||s(t)}).catch(t=>{e||h(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[a,t,n]);let y=o?v(o,e.type):[],b=u.toLowerCase()===(e.type??``).toLowerCase();return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async o=>{if(o.preventDefault(),!(b||f)){h(null),p(!0);try{let o=await a.documentUpdateChunk(e.id,e.revision,{type:u},t,n);if(i(o),o.not_announced){_(o.not_announced),p(!1);return}r()}catch(e){h(e instanceof Error?e.message:String(e)),p(!1)}}},children:[(0,l.jsx)(`h3`,{children:`Change type`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`“`,e.title||`(untitled)`,`” is a subject (`,(0,l.jsx)(`code`,{children:e.entity?.natural_key}),`). Its key stays as it is; relations about it are re-checked against the new type.`]}),m&&(0,l.jsx)(`div`,{className:`modal-err`,children:m}),g?(0,l.jsxs)(`div`,{className:`modal-err`,children:[`The type was changed, but subscribers were not told: `,g]}):(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),o===null?(0,l.jsx)(`span`,{className:`doc-empty-body`,children:m?``:`loading types…`}):(0,l.jsx)(`select`,{className:`path-modal-input`,value:u,disabled:f,onChange:e=>d(e.target.value),children:y.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:f,children:g?`close`:`cancel`}),!g&&(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:f||b||o===null,children:f?`saving…`:`change type`})]})]})})}function at(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function ot(e){if(!e||typeof e!=`object`)return;let t=e.classification;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t,r={};return typeof n.by==`string`&&(r.by=n.by),typeof n.at==`number`&&(r.at=n.at),typeof n.applied_type==`string`&&n.applied_type&&(r.applied_type=n.applied_type),typeof n.proposed_type==`string`&&n.proposed_type&&(r.proposed_type=n.proposed_type),n.proposed_fields&&typeof n.proposed_fields==`object`&&!Array.isArray(n.proposed_fields)&&(r.proposed_fields=n.proposed_fields),at(n.proposed_tags)&&(r.proposed_tags=n.proposed_tags),at(n.statements)&&(r.statements=n.statements),r}function st(e){let t=ot(e);if(!t)return;let n=t.proposed_tags??[],r=t.statements?.length??0;if(t.proposed_type||n.length!==0||r!==0)return{proposedType:t.proposed_type,proposedTags:n,statementCount:r}}function ct(e){let t=e.write===`report`;switch(e.result){case`classified`:return t?`would be classified`:`classified`;case`proposed`:return t?`would be proposed for review`:`proposed — waits for review`;case`kept`:return`kept — the type was set by hand`;case`unclassified`:return`unclassified — nothing decided`;default:return String(e.result)}}function lt(e){if(!e.class)return;if(e.result===`kept`)return`not applied`;let t=e.write===`report`;return e.live?t?`would be applied`:`applied`:t?`would be proposed`:`proposed`}function ut(e){return e.write===`report`?e.result===`classified`||e.result===`proposed`||(e.concepts?.length??0)>0||(e.issued_by?.length??0)>0:!1}function dt(e){return e==null||!Number.isFinite(e)?``:`${Math.round(e*100)}%`}var ft={rules:`Rules`,vote:`Neighbourhood vote`,model:`Model`};function pt(e){return ft[e]??e}function mt(e){let t=[];e.quote&&t.push(e.from?`“${e.quote}” (${e.from})`:`“${e.quote}”`),e.votes!=null&&t.push(`${e.votes} vote${e.votes===1?``:`s`}`);let n=dt(e.share);return n&&t.push(n),t.join(` · `)}function ht(e){return{label:pt(e.step),...e.chosen?{chosen:e.chosen}:{},...e.method?{method:e.method}:{},...e.neighbours?{neighbours:e.neighbours}:{},...e.reason?{reason:e.reason}:{},candidates:(e.candidates??[]).map(e=>({class:e.class,detail:mt(e)}))}}function gt(e){let t=[];e.type&&t.push(`type ${e.type}`);let n=e.accepted_statements?.length??0;n>0&&t.push(`${n} statement${n===1?``:`s`}`),e.tags&&e.tags.length>0&&t.push(`tags ${e.tags.join(`, `)}`);let r=[];e.type_pending&&r.push(`The proposed class stays pending: another document already holds its identity.`),e.skipped_type&&r.push(`Class ${e.skipped_type} was not applied: it is not a declared document class.`);let i=e.skipped_statements?.length??0;return i>0&&r.push(`${i} statement${i===1?` was`:`s were`} skipped (already ruled on, or not this document's proposal).`),e.skipped_tags&&e.skipped_tags.length>0&&r.push(`Tags not applied (not concepts of the ontology): ${e.skipped_tags.join(`, `)}.`),r.push(...e.warnings??[]),{applied:t.length>0?`Accepted ${t.join(`, `)}.`:`Nothing was accepted.`,notices:r}}function _t(e){let t=e instanceof Error?e.message:String(e);return t.includes(`nothing_pending`)?`Nothing is pending for this document — it may already have been accepted.`:t}function vt({documentId:e,scope:t,browse:n,rootFields:r,requestKey:i,onClose:a,onChanged:o}){let s=j(),[u,d]=(0,c.useState)(null),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(!1),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),S=(0,c.useMemo)(()=>s.documentAcceptClassification?st(r):void 0,[s,r]);(0,c.useEffect)(()=>{if(i===0||!s.documentClassify)return;let r=!1;return p(!0),h(null),d(null),s.documentClassify(e,`report`,t,n).then(e=>!r&&d(e)).catch(e=>!r&&h(_t(e))).finally(()=>!r&&p(!1)),()=>{r=!0}},[s,e,t,n,i]);let C=async()=>{if(s.documentClassify){p(!0),h(null);try{d(await s.documentClassify(e,`propose`,t,n)),o()}catch(e){h(_t(e))}finally{p(!1)}}},w=async()=>{if(s.documentAcceptClassification){_(!0),y(null);try{x(await s.documentAcceptClassification(e,t,n)),o()}catch(e){y(_t(e))}finally{_(!1)}}},T=i>0;if(!T&&!S&&!b&&!v)return null;let E=b?gt(b):void 0;return(0,l.jsxs)(`div`,{className:`doc-classify`,children:[S&&(0,l.jsxs)(`div`,{className:`doc-classify-pending`,children:[(0,l.jsx)(`span`,{className:`doc-classify-label`,children:`Pending classification`}),S.proposedType&&(0,l.jsxs)(`span`,{children:[`class `,(0,l.jsx)(`strong`,{children:S.proposedType})]}),S.proposedTags.length>0&&(0,l.jsxs)(`span`,{children:[`tags`,` `,S.proposedTags.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e))]}),S.statementCount>0&&(0,l.jsxs)(`span`,{children:[S.statementCount,` proposed statement`,S.statementCount===1?``:`s`]}),(0,l.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>void w(),children:g?`Accepting…`:`Accept`})]}),v&&(0,l.jsxs)(`div`,{className:`doc-classify-err`,role:`alert`,children:[v,(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>y(null),"aria-label":`Dismiss`,children:`×`})]}),E&&(0,l.jsxs)(`div`,{className:`doc-classify-notice`,role:`status`,children:[(0,l.jsx)(`span`,{children:E.applied}),E.notices.map((e,t)=>(0,l.jsx)(`span`,{className:`doc-classify-warn`,children:e},t)),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>x(null),"aria-label":`Dismiss`,children:`×`})]}),T&&(0,l.jsxs)(`div`,{className:`doc-classify-panel`,children:[(0,l.jsxs)(`div`,{className:`doc-classify-head`,children:[(0,l.jsx)(`h4`,{children:`Classify`}),u&&(0,l.jsx)(`span`,{className:`doc-classify-result ${u.result}`,children:ct(u)}),u?.write===`report`&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:`report only — nothing written`}),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:a,"aria-label":`Close`,children:`×`})]}),!u&&!m&&(0,l.jsx)(`p`,{className:`doc-classify-hint`,children:`Classifying…`}),m&&(0,l.jsx)(`p`,{className:`doc-classify-err`,role:`alert`,children:m}),u&&(0,l.jsx)(yt,{answer:u}),u&&ut(u)&&(0,l.jsx)(`div`,{className:`doc-classify-actions`,children:(0,l.jsx)(`button`,{type:`button`,disabled:f,onClick:()=>void C(),title:`Apply a unique rule match to the document; file everything else for review`,children:f?`Applying…`:`Apply`})})]})]})}function yt({answer:e}){let t=lt(e),n=Object.entries(e.fields??{}),r=e.issued_by??[],i=e.concepts??[],a=(e.steps??[]).map(ht),o=e.statements?.length??0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`dl`,{className:`doc-classify-rows`,children:[e.class&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`class`}),(0,l.jsxs)(`dd`,{children:[(0,l.jsx)(`strong`,{children:e.class}),t&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` (`,t,`)`]})]})]}),e.work_key&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`work key`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:e.work_key})]}),n.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`fields`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:n.map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`).join(` · `)})]}),r.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`issued by`}),(0,l.jsx)(`dd`,{children:r.map((e,t)=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.quote,children:[e.instance,e.quote&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` “`,e.quote,`”`]})]},`${e.instance}-${t}`))})]}),i.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`concepts`}),(0,l.jsx)(`dd`,{children:i.map(e=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.tag,children:[e.concept,(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,dt(e.share)]})]},e.tag))})]}),o>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`statements`}),(0,l.jsxs)(`dd`,{children:[o,` written`,e.statements.some(e=>e.status===`proposed`)&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` (proposed ones wait for review)`})]})]})]}),a.length>0&&(0,l.jsx)(`ol`,{className:`doc-classify-steps`,children:a.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`span`,{className:`doc-classify-step`,children:e.label}),e.method&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` [`,e.method,`]`]}),e.chosen?(0,l.jsxs)(l.Fragment,{children:[` → `,(0,l.jsx)(`strong`,{children:e.chosen})]}):(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` no choice`}),e.neighbours!=null&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` · `,e.neighbours,` neighbours`]}),e.reason&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` — `,e.reason]}),e.candidates.length>0&&(0,l.jsxs)(`details`,{className:`doc-classify-candidates`,children:[(0,l.jsxs)(`summary`,{children:[e.candidates.length,` candidate`,e.candidates.length===1?``:`s`]}),(0,l.jsx)(`ul`,{children:e.candidates.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`strong`,{children:e.class}),e.detail&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,e.detail]})]},`${e.class}-${t}`))})]})]},`${e.label}-${t}`))}),e.warnings&&e.warnings.length>0&&(0,l.jsx)(`ul`,{className:`doc-classify-warnings`,children:e.warnings.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-classify-warn`,children:e},t))})]})}function bt(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((e??``).trim());if(!t)return`#888888`;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`#`+n.toLowerCase()}function xt({documentId:e,rootChunkId:t,docType:n,docStatus:r,chunkStatuses:i,scope:a,browse:o,onClose:s,onSaved:u}){let d=j(),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(!1),[g,_]=(0,c.useState)({}),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),w=(0,c.useMemo)(()=>{let e=new Set(Object.keys(Q));n&&e.add(`doc.${n}.${r||`draft`}`);for(let t of i)t&&e.add(`chunk.${t}`);return[...e].sort()},[n,r,i]);(0,c.useEffect)(()=>{let e=!1;return d.documentGetChunk(t,a,o).then(t=>{if(e)return;p(t);let n=t.fields??{};h(n.color_enabled===!0);let r=n.color_scheme??{};_({...Q,...r})}).catch(t=>!e&&C(t instanceof Error?t.message:String(t))),()=>{e=!0}},[d,t,a,o]);let T=(e,t)=>_(n=>({...n,[e]:t})),E=e=>({...e??{},color_enabled:m,color_scheme:g}),D=async()=>{if(f){y(!0),C(null),x(null);try{await d.documentUpdateChunk(t,f.revision,{fields:E(f.fields)},a,o),u(),s()}catch(e){C(e instanceof Error?e.message:String(e)),y(!1)}}},O=async()=>{if(!n)C(`this document has no type to match`);else{y(!0),C(null),x(null);try{let{documents:t}=await d.documentsSummary({underPath:`/`},a,o),r=(t??[]).filter(t=>t.type===n&&t.document_id!==e&&t.root_chunk_id),i=0;for(let e of r)try{let t=await d.documentGetChunk(e.root_chunk_id,a,o);await d.documentUpdateChunk(e.root_chunk_id,t.revision,{fields:E(t.fields)},a,o),i++}catch{}x(`Applied to ${i} other ${n} document(s).`),u()}catch(e){C(e instanceof Error?e.message:String(e))}finally{y(!1)}}},k=w.filter(e=>e.startsWith(`doc.`)),A=w.filter(e=>e.startsWith(`chunk.`));return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:s,children:(0,l.jsxs)(`div`,{className:`modal scheme-editor`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`scheme-editor-head`,children:[(0,l.jsx)(`h3`,{children:`Document colors`}),(0,l.jsxs)(`div`,{className:`scheme-editor-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:s,disabled:v,children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`primary`,onClick:()=>void D(),disabled:v||!f,children:v?`saving…`:`save`})]})]}),S&&(0,l.jsx)(`div`,{className:`modal-err`,children:S}),f?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`label`,{className:`scheme-toggle`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked)}),(0,l.jsx)(`span`,{children:`Enable coloring for this document`})]}),(0,l.jsx)(`p`,{className:`modal-context`,children:`Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable.`}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Document (type · status)`}),k.map(e=>(0,l.jsx)(St,{label:e.slice(4),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Chunks (status)`}),A.map(e=>(0,l.jsx)(St,{label:e.slice(6),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-editor-foot`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>void O(),disabled:v||!n,title:n?`Apply this palette to every other ${n} document`:`This document has no type`,children:[`copy to all `,n||`same-type`,` documents`]}),b&&(0,l.jsx)(`span`,{className:`scheme-status`,children:b})]})]}):(0,l.jsx)(`p`,{className:`modal-context`,children:`Loading…`})]})})}function St({label:e,value:t,onChange:n}){let r=bt(t);return(0,l.jsxs)(`label`,{className:`scheme-row`,children:[(0,l.jsx)(`input`,{type:`color`,value:r,onChange:e=>n(e.target.value)}),(0,l.jsx)(`span`,{className:`scheme-key`,children:e}),(0,l.jsx)(`code`,{className:`scheme-hex`,children:r})]})}function Ct({id:e,title:t,targetDocumentId:n,documentId:r,onSelectChunk:i,onOpenDocument:a}){let o=t||e.slice(0,8);return!n||n===r?(0,l.jsx)(`button`,{type:`button`,className:`doc-ref-target`,onClick:()=>i(e),children:o}):a?(0,l.jsxs)(`button`,{type:`button`,className:`doc-ref-target external`,title:`In another document — opens it at this chunk`,onClick:()=>a(n,e,t),children:[o,` ↗`]}):(0,l.jsxs)(`span`,{className:`doc-ref-target external`,title:`In another document`,children:[o,` ↗`]})}function wt({statement:e}){let t=Se(e),n=Ce(e),r=Ee(e),i=Te(e),{rows:a,more:o}=De(e);return(0,l.jsxs)(l.Fragment,{children:[t&&(0,l.jsx)(`span`,{className:`doc-stmt-status ${t}`,children:t}),n&&(0,l.jsx)(`span`,{className:`doc-stmt-method`,title:`how this relation was made`,children:n}),r&&(0,l.jsx)(`span`,{className:`doc-stmt-verdict`,title:r,children:`judged`}),i&&(0,l.jsx)(`span`,{className:`doc-stmt-valid`,children:i}),a.length>0&&(0,l.jsxs)(`ul`,{className:`doc-stmt-evidence`,children:[a.map(e=>(0,l.jsxs)(`li`,{title:e.quote,children:[`“`,Oe(e.quote),`”`,e.stale&&(0,l.jsx)(`span`,{className:`doc-stmt-stale`,children:` (source changed)`})]},e.id)),o>0&&(0,l.jsxs)(`li`,{className:`doc-stmt-more`,children:[`+`,o,` more`]})]})]})}function Tt({id:e,onRule:t}){let[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=async n=>{s(!0),d(null);try{await t(e,n,n?void 0:i.trim()),r(!1),a(``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{s(!1)}};return(0,l.jsxs)(`span`,{className:`doc-stmt-review`,children:[n?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:i,disabled:o,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i.trim()&&f(!1),e.key===`Escape`&&r(!1)},autoFocus:!0}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:o||!i.trim(),onClick:()=>void f(!1),children:`Reject`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!1),children:`Cancel`})]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>void f(!0),children:`Accept`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!0),children:`Reject…`})]}),u&&(0,l.jsx)(`span`,{className:`doc-stmt-err`,role:`alert`,children:u})]})}var Et=3;function Dt({documentId:e,proposals:t,incomplete:n,scope:r,browse:i,onChanged:a,onSelectChunk:o,onOpenDocument:s}){let u=j(),[d,f]=(0,c.useState)(new Set),[p,m]=(0,c.useState)({kind:`idle`}),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useRef)(null),S=new Set(t.map(e=>e.id)),C=[...d].filter(e=>S.has(e)),w=p.kind!==`idle`&&p.kind!==`reason`,T=(e,t)=>{v(null),b(null),e===`reject`?m({kind:`reason`,action:e,all:t}):E(e,t,``)},E=async(t,n,o)=>{m({kind:`counting`,action:t,all:n});let s;try{s=await Ie(u,{documentId:e,action:t,ids:n?void 0:C,reason:o.trim()||void 0,scope:r,browse:i},{confirm:(e,r)=>new Promise(i=>{x.current=i,m({kind:`confirm`,action:t,all:n,dry:e,changed:r!==`first`})}),onProgress:e=>m({kind:`ruling`,action:t,ruled:e.ruled,total:e.total})})}catch(e){s={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[],error:e}}x.current=null,m({kind:`idle`}),g(``),s.rulingIds.length>0?(f(new Set),b({text:Le(t,s),rulingIds:s.rulingIds}),a()):s.error===void 0&&!s.cancelled&&b({text:`Nothing to rule: no proposals match.`,rulingIds:[]}),s.error!==void 0&&v(s.error instanceof Error?s.error.message:String(s.error))},D=e=>{e&&p.kind===`confirm`&&m({kind:`ruling`,action:p.action}),x.current?.(e)},O=async()=>{if(!y||!u.documentRevertRuling)return;let e=y,t=await je(e=>u.documentRevertRuling(e,r,i),e.rulingIds),n=[`${t.reverted} came back to review`];t.changed>0&&n.push(`${t.changed} changed since and left as ruled`),t.errors.length>0&&n.push(`not undone: ${t.errors.join(`; `)}`),b({...e,undone:!0,text:n.join(`; `)+`.`}),a()},k=e=>f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),A=t.length>0&&C.length===t.length,M=t.length===0&&!n;return(0,l.jsxs)(`div`,{className:`doc-conn-group doc-bulk`,children:[(0,l.jsxs)(`h5`,{children:[`Proposals from this document (`,t.length,`)`]}),(0,l.jsxs)(`div`,{className:`doc-bulk-bar`,children:[(0,l.jsxs)(`label`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select every proposal shown`,checked:A,disabled:w||t.length===0,onChange:()=>f(A?new Set:new Set(S))}),` `,`all shown`]}),(0,l.jsxs)(`button`,{type:`button`,disabled:w||C.length===0,onClick:()=>T(`accept`,!1),children:[`Accept selected (`,C.length,`)`]}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||C.length===0,onClick:()=>T(`reject`,!1),children:`Reject selected…`}),(0,l.jsx)(`button`,{type:`button`,disabled:w||M,onClick:()=>T(`accept`,!0),children:`Accept all from this document`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||M,onClick:()=>T(`reject`,!0),children:`Reject all…`})]}),p.kind===`reason`&&(0,l.jsxs)(`form`,{className:`doc-bulk-step`,onSubmit:e=>{e.preventDefault(),h.trim()&&E(p.action,p.all,h)},children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:h,onChange:e=>g(e.target.value),autoFocus:!0}),(0,l.jsx)(`button`,{type:`submit`,className:`danger`,disabled:!h.trim(),children:`Count`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>m({kind:`idle`}),children:`Cancel`})]}),p.kind===`counting`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`counting…`}),p.kind===`confirm`&&(0,l.jsx)(Ot,{step:p,onAnswer:D}),p.kind===`ruling`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:p.total?`ruled ${p.ruled??0} of ${p.total}…`:`ruling…`}),_&&(0,l.jsx)(`p`,{className:`doc-stmt-err`,role:`alert`,children:_}),y&&(0,l.jsxs)(`p`,{className:`doc-bulk-result`,role:`status`,children:[y.text,y.rulingIds.length>0&&!y.undone&&u.documentRevertRuling&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>void O(),children:`Undo`})]}),t.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:t.map(t=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select ${t.from_title??t.from_id} ${t.kind} ${t.to_title??t.to_id}`,checked:d.has(t.id),disabled:w,onChange:()=>k(t.id)}),(0,l.jsx)(Ct,{id:t.from_id,title:t.from_title,targetDocumentId:t.from_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:t.kind}),(0,l.jsx)(Ct,{id:t.to_id,title:t.to_title,targetDocumentId:t.to_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(wt,{statement:t})]},t.id))})]})}function Ot({step:e,onAnswer:t}){let{dry:n}=e,r=e.action===`accept`?`Accept`:`Reject`,i=Me(n.matched);return(0,l.jsxs)(`div`,{className:`doc-bulk-step doc-bulk-confirm`,children:[e.changed&&(0,l.jsx)(`p`,{className:`doc-bulk-warn`,children:`The proposals changed since the last count; counted again.`}),(0,l.jsxs)(`p`,{children:[r,` `,n.matched,` statement`,n.matched===1?``:`s`,e.all?` filed from this document`:``,i>1?`, in ${i} rulings of up to 1,000`:``,`?`,n.skipped>0&&` ${n.skipped} of them are not yours to rule and will be skipped.`]}),(n.sample??[]).length>0&&(0,l.jsx)(`ul`,{className:`doc-bulk-sample`,children:(n.sample??[]).slice(0,Et).map(e=>(0,l.jsxs)(`li`,{children:[e.from_title||e.from_id,` `,(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),` `,e.to_title||e.to_id]},e.id))}),(0,l.jsxs)(`button`,{type:`button`,className:e.action===`reject`?`danger`:void 0,onClick:()=>t(!0),children:[r,` `,n.matched]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>t(!1),children:`Cancel`})]})}var kt=8,At=20;function jt(e){return/embedder|embedding|vector|semantic|not configured/i.test(e)}function Mt({documentId:e,selectedId:t,scope:n,browse:r,onSelectChunk:i,onOpenDocument:a,refreshKey:o,review:s}){let u=j(),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(void 0),[_,v]=(0,c.useState)([]),[y,b]=(0,c.useState)([]),[x,S]=(0,c.useState)(null),[C,w]=(0,c.useState)([]),[T,E]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(!d||!t)return;let e=t,i=!1;return m(!0),Promise.allSettled([u.documentBacklinks(e,n,r),u.documentRelated(e,n,r,kt),u.documentUnlinkedMentions(e,n,r,At)]).then(([t,n,r])=>{if(!i){if(v(t.status===`fulfilled`?t.value.backlinks??[]:[]),n.status===`fulfilled`)b(n.value.related??[]),S(null);else{b([]);let e=n.reason instanceof Error?n.reason.message:String(n.reason);S(jt(e)?`semantic search not configured`:e)}r.status===`fulfilled`?(w(r.value.unlinked_mentions??[]),E(!!r.value.truncated)):(w([]),E(!1)),g(e),m(!1)}}),()=>{i=!0}},[u,d,t,n,r,o]);let D=(t,n,r)=>(0,l.jsx)(Ct,{id:t,title:n,targetDocumentId:r,documentId:e,onSelectChunk:i,onOpenDocument:a}),O=!!(d&&t&&!p&&h===t);return(0,l.jsxs)(`div`,{className:`doc-conn`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-conn-toggle`,onClick:()=>f(e=>!e),children:[d?`▼`:`▶`,` Connections`]}),d&&(0,l.jsxs)(`div`,{className:`doc-conn-body`,children:[s&&(0,l.jsx)(Dt,{documentId:e,proposals:s.proposals,incomplete:s.incomplete,scope:s.scope,browse:r,onChanged:s.onChanged,onSelectChunk:i,onOpenDocument:a}),t?O?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Backlinks`}),_.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:_.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.from_id,e.from_title,e.from_document_id),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),e.auto&&(0,l.jsx)(`span`,{className:`doc-conn-auto`,title:`Auto-linked from a [[wikilink]]`,children:`auto`}),(0,l.jsx)(wt,{statement:e})]},`${e.from_id}-${e.kind}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Related`}),x?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:x}):y.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:y.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.chunk_id,e.title,e.document_id),(0,l.jsx)(`span`,{className:`doc-conn-score`,title:`similarity score`,children:e.score.toFixed(2)})]},`${e.chunk_id}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Unlinked mentions`}),C.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsxs)(`ul`,{className:`doc-conn-list`,children:[C.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-conn-row`,children:D(e.chunk_id,e.title,e.document_id)},`${e.chunk_id}-${t}`)),T&&(0,l.jsx)(`li`,{className:`doc-conn-more`,"aria-hidden":!0,children:`(more…)`})]})]})]}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`loading…`}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`Select a chunk.`})]})]})}var Nt=24;function Pt({edges:e,documentId:t,selectedId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a,incomplete:o}){let[s,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(!1);if(e.length===0)return null;let p=n?e.filter(e=>e.from_id===n||e.to_id===n):[],m=d?e:e.slice(0,Nt),h=It(m);return(0,l.jsxs)(`div`,{className:`doc-refs`,children:[o&&(0,l.jsxs)(`p`,{className:`doc-refs-incomplete`,children:[`Showing the first `,e.length,` links of this document; it has more, which are not shown here or in the graph.`]}),n&&(0,l.jsxs)(`div`,{className:`doc-refs-list-wrap`,children:[(0,l.jsx)(`h4`,{children:`References`}),p.length===0?(0,l.jsx)(`p`,{className:`doc-refs-empty`,children:`This chunk has no links.`}):(0,l.jsx)(`ul`,{className:`doc-refs-list`,children:p.map((e,o)=>(0,l.jsx)(Ft,{edge:e,selectedId:n,documentId:t,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a},`${e.from_id}-${e.to_id}-${e.kind}-${o}`))})]}),(0,l.jsxs)(`div`,{className:`doc-graph`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-graph-toggle`,onClick:()=>u(e=>!e),children:[s?`▼`:`▶`,` relationship graph (`,e.length,`)`]}),s&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(nt,{code:h,onNodeClick:e=>{let n=Lt(m,e);n&&(!n.documentId||n.documentId===t?r(n.id):i?.(n.documentId,n.id,n.title))}}),e.length>Nt&&(0,l.jsx)(`button`,{type:`button`,className:`doc-graph-more`,onClick:()=>f(e=>!e),children:d?`show top ${Nt}`:`show all ${e.length}`})]})]})]})}function Ft({edge:e,selectedId:t,documentId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a}){let o=e.from_id===t,s=o?e.to_id:e.from_id,c=o?e.to_title:e.from_title,u=o?e.to_document_id:e.from_document_id;return(0,l.jsxs)(`li`,{className:`doc-ref`,children:[(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),(0,l.jsx)(`span`,{className:`doc-ref-arrow`,"aria-hidden":!0,children:o?`→`:`←`}),(0,l.jsx)(Ct,{id:s,title:c,targetDocumentId:u,documentId:n,onSelectChunk:r,onOpenDocument:i}),(0,l.jsx)(wt,{statement:e}),a&&we(e)&&(0,l.jsx)(Tt,{id:e.id,onRule:a})]})}function It(e){let t=[`graph LR`];for(let n of e){let e=`${Rt(n.from_id)}["${zt(n.from_title,n.from_id)}"]`,r=`${Rt(n.to_id)}["${zt(n.to_title,n.to_id)}"]`,i=(n.kind||`link`).replace(/[|"]/g,` `),a=n.status===`proposed`?`-.->`:`-->`;t.push(` ${e} ${a}|${i}| ${r}`)}return t.join(`
|
|
2
|
-
`)}function
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=require("react/jsx-runtime"),u=require("@loomcycle/client"),d=require("react-markdown");d=s(d,1);let f=require("remark-gfm");f=s(f,1);var p=`loomcycle.explorer.navigator`;function m(e){try{return e?.getItem(`loomcycle.explorer.navigator`)===`stars`?`stars`:`tree`}catch{return`tree`}}function h(e,t){try{e?.setItem(p,t)}catch{}}function g(e){return!!e&&!e.parent_id&&!!e.entity?.natural_key}function _(e){let t=e?.classes;if(!Array.isArray(t))return[];let n=new Set;for(let e of t){let{name:t,kind:r}=e??{};typeof t==`string`&&t!==``&&r!==`document`&&n.add(t)}return[...n].sort((e,t)=>e.localeCompare(t))}function v(e,t){let n=t??``;return n===``||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[n,...e]}function y(e){let t={op:e.op===`copy`?`copy_documents`:`move_documents`,scope:e.scope,to_scope:e.toScope,dry_run:e.dryRun};e.documentId&&(t.document_ids=[e.documentId]),e.underPath&&(t.under_path=e.underPath);let n=C(e.from),r=C(e.to);return n&&r&&n!==r&&(t.path_map={[n]:r}),e.op===`move`&&(e.dropDangling&&(t.dangling=`drop`),e.dryRun||(t.expect_count=e.expectCount??0)),t}function b(e){let t=e.to.trim();return t.startsWith(`/`)?e.op===`move`&&e.toScope===e.scope?`a move goes to another scope; to rename within this one, use rename / move`:e.op===`copy`&&e.toScope===e.scope&&C(t)===C(e.from)?`a copy into the same scope needs a new path`:null:`the new path must start with /`}function x(e,t){let n=t.counts??{},r=n.documents??0,i=e===`copy`?`copied`:`moved`,a=[],o=`${n.chunks??0} parts, ${n.revisions??0} revisions, ${n.statements??0} relations, ${n.assets??0} images`;if(t.dry_run)a.push(`${r} ${w(r,`document`)} would be ${i}: ${o}.`),t.to_finish?.length&&a.push(`${t.to_finish.length} ${w(t.to_finish.length,`document`)} left by an earlier interrupted move will be finished.`);else if(e===`move`){let e=t.moved?.length??0;a.push(`${e} ${w(e,`document`)} moved: ${o}.`)}else a.push(`${r} ${w(r,`document`)} copied: ${o}.`);let s=t.refused_count??t.refused?.length??0;if(s>0){a.push(`${s} ${w(s,`document`)} refused:`);for(let e of t.refused??[])a.push(` ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}`)}if(t.dangling_count>0){e===`copy`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set stay behind.`):t.dropped===void 0?t.blocked_by===`dangling_relations`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} join these documents to ones outside the set. A relation cannot span two scopes: include the other documents, or drop these relations.`):a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set will be dropped.`):a.push(`${t.dropped} ${w(t.dropped,`relation`)} to documents outside the set were dropped.`);for(let e of t.dangling??[])a.push(` ${e.kind}: ${e.from} → ${e.to} (outside: ${e.outside})`)}for(let e of t.unfinished??[])a.push(`not finished: ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}. Run the move again.`);for(let e of t.name_failures??[])a.push(`no name ${e.path} for ${e.document_id}: ${e.error}`);return t.body_failures&&a.push(`${t.body_failures} ${w(t.body_failures,`body`,`bodies`)} could not be written.`),t.statements_failed&&a.push(`${t.statements_failed} ${w(t.statements_failed,`relation`)} could not be written${t.statement_error?`: ${t.statement_error}`:``}.`),a}function S(e,t,n){return e===`move`&&t.dangling_count>0&&!n||(t.counts?.documents??0)===0&&!(t.to_finish?.length??0)}function C(e){let t=e.trim(),n=t.length;for(;n>1&&t[n-1]===`/`;)n--;return t.slice(0,n)}function w(e,t,n=t+`s`){return e===1?t:n}var T=4,E=5e3;function D(e,t,n){return{...O(e,n),pathLs:(t,n,r,i,a)=>e.path({op:`ls`,path:t,scope:n,recursive:r,...a?.limit?{limit:a.limit}:{},...a?.cursor?{cursor:a.cursor}:{}},i),pathIsStored:(t,n,r)=>e.path({op:`stat`,path:t,scope:n},r).then(()=>!0,e=>{if(e?.name===`SubstrateToolRefusedError`)return!1;throw e}),documentPath:async(t,n,r)=>{let i;for(let a=0;a<T;a++){let a=await e.path({op:`ls`,path:`/`,scope:n,recursive:!0,kind_filter:`document`,limit:E,...i?{cursor:i}:{}},r),o=(a.entries??[]).find(e=>e.resource_ref?.document_id===t);if(o)return o.full_path;if(i=a.next_cursor||void 0,!i)return}},pathMkdir:(t,n,r)=>e.path({op:`mkdir`,path:t,scope:n},r),pathMv:(t,n,r,i)=>e.path({op:`mv`,path:t,to:n,scope:r},i),pathRm:(t,n,r,i)=>e.path({op:`rm`,path:t,scope:n,recursive:r},i),documentCreate:(t,n,r,i)=>e.document({op:`create_document`,title:t,path:n,scope:r},i),documentDelete:(t,n,r)=>e.document({op:`delete_document`,id:t,scope:n},r),documentsTransfer:(t,n)=>e.document(y(t),n),documentGet:(t,n,r)=>e.document({op:`get_document`,id:t,scope:n},r),documentsSummary:(t,n,r)=>e.document({op:`documents_summary`,scope:n,...t.documentIds?{document_ids:t.documentIds}:{},...t.underPath?{under_path:t.underPath}:{}},r),documentQueryChunks:(t,n,r)=>e.document({op:`query_chunks`,document_id:t,scope:n,limit:1e3},r),documentGetChunk:(t,n,r)=>e.document({op:`get_chunk`,id:t,scope:n},r),documentCreateChunk:(t,n,r,i,a,o)=>e.document({op:`create_chunk`,document_id:t,parent_id:n,scope:i,...o?{after_id:o}:{},...r},a),documentReorderChunk:(t,n,r,i)=>e.document({op:`reorder_chunk`,id:t,direction:n,scope:r},i),documentDeleteChunk:(t,n,r)=>e.document({op:`delete_chunk`,id:t,scope:n},r),documentSetAsset:(t,n,r,i,a,o)=>e.document({op:`set_asset`,id:t,media_type:n,data:r,...i?{filename:i}:{},scope:a},o),documentGetEdges:(t,n,r,i)=>e.document({op:`get_edges`,document_id:t,scope:n,...i?.after?{after:i.after}:{}},r),documentGetEdge:(t,n,r)=>e.document({op:`get_edge`,id:t,scope:n},r),documentAcceptStatement:(t,n,r,i)=>e.document({op:`accept_statement`,id:t,scope:n,...i?{reason:i}:{}},r),documentRejectStatement:(t,n,r,i)=>e.document({op:`reject_statement`,id:t,reason:n,scope:r},i),documentListStatements:(t,n,r)=>e.document({op:`list_statements`,scope:t,...r?.status?{status:r.status}:{},...r?.kind?{kind:r.kind}:{},...r?.limit?{limit:r.limit}:{},...r?.after?{after:r.after}:{}},n),documentClassify:(t,n,r,i)=>e.document({op:`classify`,document_id:t,write:n,scope:r},i),documentEntityTypes:(t,n)=>e.document({op:`describe_ontology`,scope:t},n).then(_),documentAcceptClassification:(t,n,r)=>e.document({op:`accept_classification`,document_id:t,scope:n},r),documentUpdateChunk:(t,n,r,i,a)=>e.document({op:`update_chunk`,id:t,revision:n,scope:i,...r},a),documentExportMd:(t,n,r,i)=>e.document({op:`export_md`,document_id:t,scope:n,include_metadata:r},i),documentBacklinks:(t,n,r)=>e.document({op:`backlinks`,id:t,scope:n},r),documentRelated:(t,n,r,i)=>e.document({op:`related`,id:t,scope:n,...i?{limit:i}:{}},r),documentUnlinkedMentions:(t,n,r,i)=>e.document({op:`unlinked_mentions`,id:t,scope:n,...i?{limit:i}:{}},r),documentHistory:(t,n,r,i)=>e.document({op:`history`,id:t,scope:n,...i?{limit:i}:{}},r),documentGetVersion:(t,n,r,i)=>e.document({op:`get_version`,id:t,revision:n,scope:r},i),documentDiff:(t,n,r,i,a)=>e.document({op:`diff`,id:t,from_revision:n,to_revision:r,scope:i},a),documentExportCanvas:(t,n,r)=>e.document({op:`export_canvas`,document_id:t,scope:n},r),...t?{documentAssetObjectUrl:async(e,n,r)=>{let i=new URLSearchParams({scope:n});r?.scopeId&&i.set(`scope_id`,r.scopeId),r?.tenant&&i.set(`tenant`,r.tenant);let a=await t(`/v1/_document/asset/${encodeURIComponent(e)}?${i.toString()}`);if(!a.ok)throw Error(`asset fetch failed: ${a.status}`);let o=await a.blob();return URL.createObjectURL(o)}}:{}}}function O(e,t){let n=e,r=e=>e?.tenant?`?tenant=${encodeURIComponent(e.tenant)}`:``,i={};typeof n.ruleStatements==`function`?i.documentRuleStatements=(e,t)=>n.ruleStatements(e.action,e.ids?{ids:e.ids}:{filter:e.filter},{reason:e.reason,dryRun:e.dry_run,expectCount:e.expect_count,max:e.max,scope:e.scope,scopeId:e.scope_id,tenant:t?.tenant}):t&&(i.documentRuleStatements=(e,n)=>t(`/v1/_statements/rule${r(n)}`,e));let a=(e,t)=>e===`user`&&t?.scopeId?t.scopeId:void 0;return typeof n.revertRuling==`function`?i.documentRevertRuling=(e,t,r)=>n.revertRuling(e,{scope:t,scopeId:a(t,r),tenant:r?.tenant}):t&&(i.documentRevertRuling=(e,n,i)=>{let o=a(n,i);return t(`/v1/_statements/revert${r(i)}`,{ruling_id:e,scope:n,...o?{scope_id:o}:{}})}),i}var k=(0,c.createContext)(null);function A({value:e,children:t}){return(0,l.jsx)(k.Provider,{value:e,children:t})}function j(){let e=(0,c.useContext)(k);if(!e)throw Error(`useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)`);return e}var M=5e3;function N(e){return e===``?`/`:e}function ee(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function te(e){let t=[``],n=e.split(`/`).filter(Boolean),r=``;for(let e=0;e<n.length-1;e++)r=`${r}/${n[e]}`,t.push(r);return t}function P(e){return e instanceof Error?e.message:String(e)}function F(e,t){return{entries:[...t,...e.entries??[]],nextCursor:e.next_cursor||void 0,loaded:!0,loading:!1}}var ne=class{data;scope;browse;pageLimit;dirs=new Map;snapshot=new Map;listeners=new Set;inflight=new Map;epoch=new Map;constructor(e,t,n,r=500){this.data=e,this.scope=t,this.browse=n,this.pageLimit=r}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});publish(){this.snapshot=new Map(this.dirs),this.listeners.forEach(e=>e())}set(e,t){this.dirs.set(e,t),this.publish()}track(e,t){let n=t.finally(()=>{this.inflight.get(e)===n&&this.inflight.delete(e)});return this.inflight.set(e,n),n}loadDir(e){return this.inflight.get(e)||(this.dirs.get(e)?.loaded?Promise.resolve():this.fetchFirst(e,this.pageLimit))}reload(e){let t=this.dirs.get(e),n=t?.entries.length??0,r=t?.loaded&&!t.nextCursor?n+this.pageLimit:n;return this.fetchFirst(e,Math.min(M,Math.max(this.pageLimit,r)))}fetchFirst(e,t){let n=(this.epoch.get(e)??0)+1;this.epoch.set(e,n);let r=this.dirs.get(e);this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!0});let i=this.data.pathLs(N(e),this.scope,!1,this.browse,{limit:t}).then(t=>{this.epoch.get(e)===n&&this.set(e,F(t,[]))},t=>{throw this.epoch.get(e)===n&&this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!1,error:P(t)}),t});return this.track(e,i)}loadMore(e){let t=this.inflight.get(e);if(t)return t;let n=this.dirs.get(e);if(!n?.nextCursor)return Promise.resolve();let r=this.epoch.get(e)??0;this.set(e,{...n,loading:!0,error:void 0});let i=this.data.pathLs(N(e),this.scope,!1,this.browse,{limit:this.pageLimit,cursor:n.nextCursor}).then(t=>{this.epoch.get(e)===r&&this.set(e,F(t,n.entries))},t=>{throw this.epoch.get(e)===r&&this.set(e,{...n,loading:!1,error:P(t)}),t});return this.track(e,i)}async reveal(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){for(await this.loadDir(n);;){let t=this.dirs.get(n);if(!t)return!1;if(t.entries.some(t=>t.name===e))break;let r=t.entries[t.entries.length-1];if(!t.nextCursor||r&&r.name>e)return!1;let i=t.nextCursor;if(await this.loadMore(n),this.dirs.get(n)?.nextCursor===i)return!1}n=`${n}/${e}`}return!0}async invalidate(e,t){if(t?.dropSubtree){for(let t of[...this.dirs.keys()])(t===e||t.startsWith(`${e}/`))&&(this.dirs.delete(t),this.epoch.set(t,(this.epoch.get(t)??0)+1),this.inflight.delete(t));this.publish()}let n=te(e).filter(e=>this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}async refresh(e){let t=new Set(e);t.add(``);for(let e of[...this.dirs.keys()])t.has(e)||(this.dirs.delete(e),this.epoch.set(e,(this.epoch.get(e)??0)+1),this.inflight.delete(e));this.publish();let n=[...t].filter(e=>e===``||this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}};async function re(e,t,n,r){let i=[],a;for(;;){let o=await e.pathLs(N(t),n,!0,r,{limit:M,cursor:a});i.push(...o.entries??[]);let s=o.next_cursor||void 0;if(!s||s===a)return i;a=s}}function ie(e){let t=[];for(let n of e){if(n.kind!==`document`)continue;let e=n.resource_ref?.document_id;e&&t.push(e)}return t}function I(e){let t=e.fetch;return new u.LoomcycleClient({baseUrl:e.baseUrl,authToken:e.token||void 0,fetch:(e,n)=>t?t(e,n):fetch(e,n)})}function L(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return t=>{let r={};return e.token&&(r.Authorization=`Bearer ${e.token}`),n(e.baseUrl+t,{headers:r})}}var R=class extends Error{status;code;constructor(e,t,n){super(e),this.name=`RequestError`,this.status=t,this.code=n}};function z(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return async(t,r)=>{let i={"Content-Type":`application/json`,Accept:`application/json`};e.token&&(i.Authorization=`Bearer ${e.token}`);let a=await n(e.baseUrl+t,{method:`POST`,headers:i,body:JSON.stringify(r)}),o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!a.ok){let e=s&&typeof s==`object`?s:{};throw new R(typeof e.error==`string`&&e.error?e.error:`${a.status} ${a.statusText}`.trim(),a.status,typeof e.code==`string`?e.code:void 0)}return s}}function ae(e){let{dataLayer:t,client:n,connection:r}=e;return(0,c.useMemo)(()=>t||(n?D(n):r?D(I(r),L(r),z(r)):null),[t,n,r?.baseUrl,r?.token,r?.fetch])}function oe({theme:e,dataLayer:t,children:n}){let r=e?{"data-theme":e}:{};return t?(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsx)(A,{value:t,children:n})}):(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsxs)(`div`,{className:`error-banner`,children:[`@loomcycle/explorer: provide a `,(0,l.jsx)(`code`,{children:`connection`}),`, `,(0,l.jsx)(`code`,{children:`client`}),`, or`,` `,(0,l.jsx)(`code`,{children:`dataLayer`}),` prop.`]})})}function se(e,t,n){let r=e[e.length-1];return[...r&&r.documentId===t.documentId?[...e.slice(0,-1),{...r,...B(t)}]:[...e,t],n]}function ce(e,t){return t<0||t>=e.length-1?e:e.slice(0,t+1)}function le(e,t,n){let r=e[e.length-1];if(!r||r.documentId!==t)return e;let i={...r,...B(n)};return i.title===r.title&&i.path===r.path?e:[...e.slice(0,-1),i]}function B(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function ue(e){return e.title?e.title:e.path?e.path.slice(e.path.lastIndexOf(`/`)+1)||e.path:e.documentId.slice(0,8)}function V(e,t=4){let n=Array.from({length:e},(e,t)=>({kind:`crumb`,index:t}));if(e<=t||t<3)return n;let r=t-1,i=Array.from({length:e-1-r},(e,t)=>t+1);return[n[0],{kind:`gap`,hidden:i},...n.slice(e-r)]}function de(e,t){for(let n of e.values()){let e=n.entries.find(e=>fe(e)===t);if(e)return e.full_path}}function fe(e){if(e.kind===`document`)return e.resource_ref?.document_id||void 0}function pe(e,t){return t&&e.some(e=>e.id===t)?t:e.find(e=>!e.parent_id)?.id}function me({trail:e,onJump:t}){let[n,r]=(0,c.useState)(!1);if(e.length<2)return null;let i=e.length-1,a=e[i-1],o=V(e.length,n?e.length:void 0);return(0,l.jsxs)(`nav`,{className:`doc-trail`,"aria-label":`Documents you came through`,children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-back`,onClick:()=>t(i-1),title:`Back to ${ue(a)}`,children:`← Back`}),(0,l.jsx)(`ol`,{className:`doc-trail-list`,children:o.map(n=>n.kind===`gap`?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-gap`,onClick:()=>r(!0),title:`Show ${n.hidden.length} more: ${n.hidden.map(t=>ue(e[t])).join(` › `)}`,"aria-label":`Show ${n.hidden.length} hidden documents`,children:`…`})},`gap`):n.index===i?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`page`,title:ue(e[i]),children:ue(e[i])})},n.index):(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>t(n.index),title:ue(e[n.index]),children:ue(e[n.index])})},n.index))})]})}function he({data:e,scope:t,browse:n,documentId:r,underPath:i,fromPath:a,onClose:o,onDone:s}){let[u,d]=(0,c.useState)(`copy`),[f,p]=(0,c.useState)(t===`tenant`?`user`:`tenant`),[m,h]=(0,c.useState)(a),[g,_]=(0,c.useState)(!1),[v,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(!1),[O,k]=(0,c.useState)(null),A=(0,c.useMemo)(()=>({op:u,scope:t,toScope:f,documentId:r,underPath:i,from:a,to:m,dropDangling:g,dryRun:!0}),[u,t,f,r,i,a,m,g]),j=JSON.stringify(y(A)),M=b(A),N=v&&v.key===j?v.res:null,ee=N?S(u,N,g):!1,te=N?u===`move`?(N.counts?.documents??0)+(N.to_finish?.length??0):N.counts?.documents??0:0,P=async t=>{if(t.preventDefault(),w)o();else if(!M&&e.documentsTransfer){D(!0),k(null);try{if(!N)C({key:j,res:await e.documentsTransfer(A,n)});else{let t={...A,dryRun:!1,expectCount:N.counts?.documents??0},r=await e.documentsTransfer(t,n);T(r),s(t,r)}}catch(e){k(e instanceof Error?e.message:String(e))}finally{D(!1)}}},F=w?`close`:E?`working…`:N?`${u} ${te} document${te===1?``:`s`}`:`check`,ne=w??N;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:E?void 0:o,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:P,children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`Copy or move the `,r?`document`:`documents under`,` `,a]}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[!w&&(0,l.jsx)(`button`,{type:`button`,onClick:o,disabled:E,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:N&&u===`move`&&!w?`danger`:`primary`,disabled:E||!w&&(!!M||ee),children:F})]})]}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`A copy gets new ids and leaves the source as it is. A move keeps every id and removes the documents from `,(0,l.jsx)(`code`,{children:t}),`. Relations between the documents go with them.`]}),(0,l.jsx)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Copy or move`,children:[`copy`,`move`].map(e=>(0,l.jsx)(`button`,{type:`button`,"aria-pressed":u===e,className:u===e?`active`:void 0,disabled:E||!!w,onClick:()=>d(e),children:e},e))}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`To scope`}),(0,l.jsxs)(`select`,{value:f,disabled:E||!!w,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`New path`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:m,disabled:E||!!w,onChange:e=>h(e.target.value)})]}),u===`move`&&(0,l.jsx)(`label`,{className:`path-field`,children:(0,l.jsxs)(`span`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:g,disabled:E||!!w,onChange:e=>_(e.target.checked)}),` `,`Drop relations to documents outside the set`]})}),M&&(0,l.jsx)(`div`,{className:`modal-err`,children:M}),ne&&(0,l.jsx)(`div`,{className:`modal-context`,"aria-live":`polite`,children:x(u,ne).map((e,t)=>e.startsWith(` `)?(0,l.jsx)(`div`,{children:(0,l.jsx)(`code`,{children:e.trim()})},t):(0,l.jsx)(`div`,{children:e},t))}),O&&(0,l.jsx)(`div`,{className:`modal-err`,children:O})]})})}var H=6;function ge({children:e,defaultLeftWidth:t=380,minLeftWidth:n=180,minRightWidth:r=240,storageKey:i,className:a,hideRight:o=!1}){let s=()=>{if(i){let e=localStorage.getItem(i),t=e?parseInt(e,10):NaN;if(Number.isFinite(t)&&t>=n)return t}return t},[u,d]=(0,c.useState)(s),[f,p]=(0,c.useState)(i);f!==i&&(p(i),d(s()));let m=(0,c.useRef)(null),[h,g]=(0,c.useState)(!1);(0,c.useEffect)(()=>{i&&!h&&f===i&&localStorage.setItem(i,String(Math.round(u)))},[i,f,u,h]);let _=(0,c.useCallback)(e=>{e.preventDefault(),g(!0),e.target.setPointerCapture(e.pointerId)},[]),v=(0,c.useCallback)(e=>{if(!h||!m.current)return;let t=m.current.getBoundingClientRect(),i=e.clientX-t.left,a=t.width-r-H;d(Math.max(n,Math.min(i,a)))},[h,n,r]),y=(0,c.useCallback)(e=>{g(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:m,className:`splitter ${a??``} ${h?`dragging`:``}`,style:{gridTemplateColumns:o?`1fr 0 0`:`min(${u}px, calc(100% - ${r+H}px)) ${H}px 1fr`},children:[(0,l.jsx)(`div`,{className:`splitter-pane splitter-left`,children:e[0]}),(0,l.jsx)(`div`,{hidden:o,className:`splitter-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-valuenow":Math.round(u),onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:y}),(0,l.jsx)(`div`,{className:`splitter-pane splitter-right`,hidden:o,children:e[1]})]})}var _e=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`];function U(e){return _e.includes(e)}function ve(e){return new Promise((t,n)=>{if(!U(e.type)){n(Error(`unsupported image type "${e.type||`unknown`}" (png, jpeg, gif, webp only)`));return}let r=new FileReader;r.onerror=()=>n(r.error??Error(`failed to read file`)),r.onload=()=>{let i=String(r.result??``),a=i.indexOf(`,`);a<0?n(Error(`could not decode image data`)):t({mediaType:e.type,data:i.slice(a+1)})},r.readAsDataURL(e)})}function ye(e){if(!e)return null;for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`file`&&U(n.type)){let e=n.getAsFile();if(e)return e}}return null}var be=20;async function W(e,t,n,r,i=20){let a=[],o;for(let s=0;s<i;s++){let i=await e.documentGetEdges(t,n,r,o?{after:o}:void 0);if(o&&i.next_cursor===o)return{edges:a,incomplete:!0};if(a.push(...i.edges??[]),!i.truncated)return{edges:a,incomplete:!1};if(!i.next_cursor)return{edges:a,incomplete:!0};o=i.next_cursor}return{edges:a,incomplete:!0}}function xe(e,t){if(!t)return[];let n=new Map(e.map(e=>[e.id,e])),r=new Set([t]),i=[],a=n.get(t)?.parent_id;for(;a&&!r.has(a);){let e=n.get(a);if(!e)break;r.add(a),i.push(e),a=e.parent_id}return i.reverse()}var Se=new Set([`manual`,`wikilink`]),Ce=280;function we(e){return e.status&&e.status!==`asserted`?e.status:void 0}function Te(e){return e.method&&!Se.has(e.method)?e.method:void 0}function G(e){return e.status===`proposed`&&!!e.id}function K(e){return new Date(Math.floor(e/1e6)).toISOString().slice(0,10)}function Ee(e){let t=e.valid_at==null?void 0:K(e.valid_at),n=e.invalid_at==null?void 0:K(e.invalid_at);if(t&&n)return`valid ${t} → ${n}`;if(t)return`valid from ${t}`;if(n)return`valid until ${n}`}function De(e){if(e.judged_at==null)return;let t=`judged by ${e.judged_by||`a judge`} on ${K(e.judged_at)}`;return e.judge_reason?`${t}: ${e.judge_reason}`:t}function Oe(e,t=3){let n=(e.evidence??[]).slice(0,t),r=Math.max(e.evidence_count??0,e.evidence?.length??0);return{rows:n,more:Math.max(0,r-n.length)}}function ke(e,t=Ce){let n=e.replace(/\s+/g,` `).trim();return n.length>t?n.slice(0,t-1)+`…`:n}var q=1e3,J=3,Y=1e3;function Ae(e){return!!e&&typeof e==`object`&&e.code===`queue_changed`}async function je(e,t,n={}){let r={action:t.action,...t.ids?{ids:t.ids}:{filter:t.filter??{}},...t.reason?{reason:t.reason}:{},...t.scope&&t.scope!==`tenant`?{scope:t.scope}:{},...t.scope===`user`&&t.scopeId?{scope_id:t.scopeId}:{}},i={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[]},a=async()=>{let t=await e.rule({...r,dry_run:!0});return i.skipped=t.skipped,t},o=async(e,t)=>!n.confirm||await n.confirm(e,t)?(i.total=i.ruled+e.matched,!0):(i.cancelled=!0,!1),s;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`first`))return i;let c=0;for(let t=0;t<Y&&s.to_rule!==0;t++){let t;try{t=await e.rule({...r,dry_run:!1,expect_count:s.matched})}catch(e){if(!Ae(e)||c>=3)return i.error=e,i;c++;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`queue_changed`))return i;continue}t.ruling_id&&i.rulingIds.push(t.ruling_id),i.ruled+=t.ruled,i.failed+=t.failed;for(let e of t.items??[])e.error&&i.failures.push(e);if(n.onProgress?.({ruled:i.ruled,failed:i.failed,total:i.total,chunks:i.rulingIds.length}),t.ruled===0||t.matched<=t.selected)break;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0)break;if(s.matched>i.total-i.ruled&&!await o(s,`grew`))return i}return i}async function Me(e,t){let n={reverted:0,changed:0,errors:[]};for(let r of[...t].reverse())try{let t=await e(r);n.reverted+=t.reverted,n.changed+=t.changed}catch(e){n.errors.push(e instanceof Error?e.message:String(e))}return n}function Ne(e){return Math.max(1,Math.ceil(e/q))}function X(e){return e===`tenant`||e===`user`?e:void 0}function Pe(e,t){return e.documentRuleStatements?X(t):void 0}function Fe(e,t){return e.filter(e=>G(e)&&!!e.id&&e.from_document_id===t)}function Ie(e,t,n,r){return e?{proposals:t,scope:e,incomplete:n,onChanged:r}:void 0}function Le(e,t,n){return e.documentRuleStatements?je({rule:n=>e.documentRuleStatements(n,t.browse)},{action:t.action,...t.ids&&t.ids.length>0?{ids:t.ids}:{filter:{from_document_id:t.documentId}},...t.reason?{reason:t.reason}:{},scope:t.scope,...t.scope===`user`&&t.browse?.scopeId?{scopeId:t.browse.scopeId}:{}},n):Promise.reject(Error(`this data layer cannot rule in bulk`))}function Re(e,t){let n=e=>e.toLocaleString(`en-US`),r=[`${e===`accept`?`Accepted`:`Rejected`} ${n(t.ruled)} statement${t.ruled===1?``:`s`}`];return t.failed>0&&r.push(`${n(t.failed)} did not take the ruling`),t.skipped>0&&r.push(`${n(t.skipped)} skipped: not yours to rule`),r.join(`; `)+`.`}var Z={"doc.rfc.draft":`#c99a3a`,"doc.rfc.review":`#6a7bd6`,"doc.rfc.confirmed":`#3a9ad6`,"doc.rfc.done":`#3aa06a`,"doc.plan.draft":`#c99a3a`,"doc.plan.review":`#6a7bd6`,"doc.plan.confirmed":`#3a9ad6`,"doc.plan.done":`#3aa06a`,"doc.document.done":`#3aa06a`,"doc.research.done":`#8a6ad6`,"doc.publication.draft":`#c99a3a`,"doc.*.draft":`#c99a3a`,"doc.*.review":`#6a7bd6`,"doc.*.confirmed":`#3a9ad6`,"doc.*.done":`#3aa06a`,"chunk.draft":`#c99a3a`,"chunk.review":`#6a7bd6`,"chunk.confirmed":`#3a9ad6`,"chunk.done":`#3aa06a`,"chunk.backlog":`#8a8f98`,"chunk.implementation":`#d1863a`,"chunk.merged":`#3aa06a`},ze=.16;function Be(e){return e&&Object.keys(e).length>0?e:Z}function Ve(e,t){if(Object.prototype.hasOwnProperty.call(e,t)&&e[t])return e[t];let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n&&e[t])return e[t]}function Q(e,t,n){let r=e??``,i=t??``;return(r&&i?Ve(n,`doc.${r}.${i}`):void 0)??(r?Ve(n,`doc.${r}`):void 0)??(i?Ve(n,`doc.*.${i}`):void 0)??Ve(n,`doc.*`)}function He(e,t){let n=e??``;return n?Ve(t,`chunk.${n}`):void 0}function Ue(e){let t=String(e[`chunk.inherit`]??``).trim().toLowerCase();return t!==`false`&&t!==`none`&&t!==`off`&&t!==`0`}function We(e,t=ze){let n=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!n)return;let r=n[1];return r.length===3&&(r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]),`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}function $(e){if(!e)return;let t=We(e);if(t)return{background:t,borderLeft:`3px solid ${e}`}}function Ge(e){if(!e)return;let t=We(e,ze/2);return t?{background:t}:void 0}function Ke(e){let{status:t,isRoot:n,documentColor:r,scheme:i}=e;if(i)return n?$(r)??$(He(t,i)):$(He(t,i))??(Ue(i)?Ge(r):void 0)}async function qe(e){try{return typeof navigator>`u`||!navigator.clipboard?!1:(await navigator.clipboard.writeText(e),!0)}catch{return!1}}function Je({value:e,label:t,compact:n,title:r}){let[i,a]=(0,c.useState)(`idle`),o=async t=>{t.stopPropagation(),t.preventDefault();let n=await qe(e);a(n?`copied`:`error`),window.setTimeout(()=>a(`idle`),n?1200:1500)},s=i===`copied`?`✓`:i===`error`?`✗`:`⎘`,u=r??`Copy ${t??`id`}: ${e}`,d=(0,l.jsx)(`button`,{type:`button`,className:`id-copy-btn id-copy-${i}`,onClick:o,title:u,"aria-label":u,children:s});return n?d:(0,l.jsxs)(`span`,{className:`id-copy`,children:[t&&(0,l.jsx)(`span`,{className:`id-copy-label`,children:t}),(0,l.jsx)(`code`,{className:`id-copy-value`,title:e,children:e}),d]})}function Ye(e){let t=new Map;e.forEach(e=>t.set(e.id,{row:e,children:[]}));let n=[];e.forEach(e=>{let r=t.get(e.id);e.parent_id&&t.has(e.parent_id)?t.get(e.parent_id).children.push(r):n.push(r)});let r=e=>{e.sort((e,t)=>e.row.position-t.row.position),e.forEach(e=>r(e.children))};return r(n),n}function Xe(e){return e===`image`?`🖼`:e===`mermaid`?`📊`:``}function Ze(e,t){for(let n of e){if(n.row.id===t)return n;let e=Ze(n.children,t);if(e)return e}}function Qe({tree:e,selectedId:t,onSelect:n,colorEnabled:r,scheme:i,documentColor:a,linkedIds:o}){let[s,u]=(0,c.useState)(()=>new Map),d=(0,c.useCallback)(e=>{u(t=>{let n=new Map(t);return n.set(e,t.get(e)===!1),n})},[]);(0,c.useEffect)(()=>{if(!t)return;let n=$e(e,t);n.length!==0&&u(e=>{let t=!1,r=new Map(e);for(let e of n)r.get(e)===!1&&(r.set(e,!0),t=!0);return t?r:e})},[e,t]);let f=r?Be(i):null;return e.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`No chunks.`})}):(0,l.jsx)(`ul`,{className:`tree chunk-tree`,children:e.map(e=>(0,l.jsx)(et,{node:e,expanded:s,toggle:d,selectedId:t,onSelect:n,tintScheme:f,documentColor:a,isRoot:!0,linkedIds:o},e.row.id))})}function $e(e,t){let n=[],r=(e,i)=>{for(let a of e){if(a.row.id===t)return n.push(...i),!0;if(r(a.children,[...i,a.row.id]))return!0}return!1};return r(e,[]),n}function et({node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,isRoot:s=!1,linkedIds:c}){let u=e.children.length>0,d=t.get(e.row.id)!==!1,f=r===e.row.id,p=Ke({status:e.row.status,isRoot:s,documentColor:o,scheme:a}),m=c?.has(e.row.id);return(0,l.jsxs)(`li`,{className:`node chunk-node ${f?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row chunk-row`,style:p,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":d?`collapse`:`expand`,disabled:!u,onClick:t=>{t.stopPropagation(),u&&n(e.row.id)},children:u?d?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`chunk-link`,onClick:()=>i(e),title:e.row.title,children:[Xe(e.row.type)&&(0,l.jsx)(`span`,{className:`chunk-type-icon`,"aria-hidden":!0,children:Xe(e.row.type)}),(0,l.jsx)(`span`,{className:`chunk-title`,children:e.row.title||`(untitled)`}),e.row.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:e.row.type}),e.row.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:e.row.status}),m&&(0,l.jsx)(`span`,{className:`chunk-link-badge`,title:`Has cross-reference links`,"aria-label":`linked`,children:`🔗`})]}),(0,l.jsx)(Je,{value:e.row.id,compact:!0,title:`Copy chunk id: ${e.row.id}`})]}),u&&d&&(0,l.jsx)(`ul`,{className:`children chunk-children`,children:e.children.map(e=>(0,l.jsx)(et,{node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,linkedIds:c},e.row.id))})]})}var tt=0;function nt(e){let t=e?.closest(`g.node`);return t?/flowchart-(.+)-\d+$/.exec(t.id)?.[1]:void 0}function rt({code:e,onNodeClick:t}){let n=(0,c.useRef)(null),[r,i]=(0,c.useState)({});return(0,c.useEffect)(()=>{let t=!1;return(async()=>{try{let r=(await import(`mermaid`)).default,a=n.current?.closest(`[data-theme]`)?.getAttribute(`data-theme`),o=!a||a===`dark`;r.initialize({startOnLoad:!1,theme:o?`dark`:`default`,securityLevel:`strict`});let{svg:s}=await r.render(`lc-mmd-${tt++}`,e);t||i({svg:s})}catch{t||i({err:!0})}})(),()=>{t=!0}},[e]),r.err?(0,l.jsx)(`pre`,{className:`md-pre md-mermaid-error`,title:`diagram failed to render`,children:(0,l.jsx)(`code`,{children:e})}):r.svg?(0,l.jsx)(`div`,{ref:n,className:t?`md-mermaid md-mermaid-nav`:`md-mermaid`,onClick:t&&(e=>{let n=nt(e.target);n&&t(n)}),dangerouslySetInnerHTML:{__html:r.svg}}):(0,l.jsx)(`div`,{ref:n,className:`md-mermaid md-mermaid-loading`,children:`rendering diagram…`})}function it({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=j(),[o,s]=(0,c.useState)(e.title),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(e.status??``),[m,h]=(0,c.useState)(e.body??``),[g,_]=(0,c.useState)(e.fields?JSON.stringify(e.fields,null,2):``),[v,y]=(0,c.useState)((e.tags??[]).join(`, `)),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(!1),E=u===`mermaid`,D=u===`image`||!!e.asset,[O,k]=(0,c.useState)(m);(0,c.useEffect)(()=>{if(!E)return;let e=setTimeout(()=>k(m),400);return()=>clearTimeout(e)},[m,E]);let A=async o=>{C(null),x(!0);try{let{mediaType:s,data:c}=await ve(o);i(await a.documentSetAsset(e.id,s,c,o.name,t,n)),r()}catch(e){C(e instanceof Error?e.message:String(e)),x(!1)}},M=E?`Mermaid source`:D?`Caption (optional)`:`Body (Markdown)`;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal chunk-editor`,onClick:e=>e.stopPropagation(),onSubmit:async s=>{s.preventDefault(),C(null),T(!1);let c={body:m,title:o,type:u,status:f,tags:v.split(`,`).map(e=>e.trim()).filter(e=>e!==``)};if(g.trim()!==``)try{c.fields=JSON.parse(g)}catch{C(`fields must be valid JSON`);return}x(!0);try{i(await a.documentUpdateChunk(e.id,e.revision,c,t,n)),r()}catch(e){let t=e instanceof Error?e.message:String(e);C(t),T(/revision conflict/i.test(t)),x(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:`Edit chunk`}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:b,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:b,children:b?`saving…`:`save`})]})]}),S&&(0,l.jsxs)(`div`,{className:`modal-err`,children:[S,w&&` — reopen the chunk to load the latest, then reapply your edit.`]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Title`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:o,onChange:e=>s(e.target.value)})]}),(0,l.jsxs)(`div`,{className:`chunk-editor-row`,children:[(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:u,placeholder:`(none)`,onChange:e=>d(e.target.value)})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Status`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:f,placeholder:`(none)`,onChange:e=>p(e.target.value)})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Tags`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:v,placeholder:`comma-separated, nest with a slash: area/sub, priority/high`,onChange:e=>y(e.target.value)})]}),D&&(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Replace image`}),(0,l.jsx)(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:b,onChange:e=>{let t=e.target.files?.[0];t&&A(t)}})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:M}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-body-input`,rows:E?8:12,value:m,onChange:e=>h(e.target.value)})]}),E&&(0,l.jsxs)(`div`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Preview`}),(0,l.jsx)(`div`,{className:`chunk-mermaid-preview`,children:O.trim()?(0,l.jsx)(rt,{code:O}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(enter Mermaid source above)`})})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Fields (JSON, optional)`}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-fields-input`,rows:4,value:g,placeholder:`{}`,onChange:e=>_(e.target.value)})]})]})})}function at({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=j(),[o,s]=(0,c.useState)(null),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(null);(0,c.useEffect)(()=>{let e=!1;return a.documentEntityTypes?.(t,n).then(t=>{e||s(t)}).catch(t=>{e||h(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[a,t,n]);let y=o?v(o,e.type):[],b=u.toLowerCase()===(e.type??``).toLowerCase();return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async o=>{if(o.preventDefault(),!(b||f)){h(null),p(!0);try{let o=await a.documentUpdateChunk(e.id,e.revision,{type:u},t,n);if(i(o),o.not_announced){_(o.not_announced),p(!1);return}r()}catch(e){h(e instanceof Error?e.message:String(e)),p(!1)}}},children:[(0,l.jsx)(`h3`,{children:`Change type`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`“`,e.title||`(untitled)`,`” is a subject (`,(0,l.jsx)(`code`,{children:e.entity?.natural_key}),`). Its key stays as it is; relations about it are re-checked against the new type.`]}),m&&(0,l.jsx)(`div`,{className:`modal-err`,children:m}),g?(0,l.jsxs)(`div`,{className:`modal-err`,children:[`The type was changed, but subscribers were not told: `,g]}):(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),o===null?(0,l.jsx)(`span`,{className:`doc-empty-body`,children:m?``:`loading types…`}):(0,l.jsx)(`select`,{className:`path-modal-input`,value:u,disabled:f,onChange:e=>d(e.target.value),children:y.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:f,children:g?`close`:`cancel`}),!g&&(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:f||b||o===null,children:f?`saving…`:`change type`})]})]})})}function ot(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function st(e){if(!e||typeof e!=`object`)return;let t=e.classification;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t,r={};return typeof n.by==`string`&&(r.by=n.by),typeof n.at==`number`&&(r.at=n.at),typeof n.applied_type==`string`&&n.applied_type&&(r.applied_type=n.applied_type),typeof n.proposed_type==`string`&&n.proposed_type&&(r.proposed_type=n.proposed_type),n.proposed_fields&&typeof n.proposed_fields==`object`&&!Array.isArray(n.proposed_fields)&&(r.proposed_fields=n.proposed_fields),ot(n.proposed_tags)&&(r.proposed_tags=n.proposed_tags),ot(n.statements)&&(r.statements=n.statements),r}function ct(e){let t=st(e);if(!t)return;let n=t.proposed_tags??[],r=t.statements?.length??0;if(t.proposed_type||n.length!==0||r!==0)return{proposedType:t.proposed_type,proposedTags:n,statementCount:r}}function lt(e){let t=e.write===`report`;switch(e.result){case`classified`:return t?`would be classified`:`classified`;case`proposed`:return t?`would be proposed for review`:`proposed — waits for review`;case`kept`:return`kept — the type was set by hand`;case`unclassified`:return`unclassified — nothing decided`;default:return String(e.result)}}function ut(e){if(!e.class)return;if(e.result===`kept`)return`not applied`;let t=e.write===`report`;return e.live?t?`would be applied`:`applied`:t?`would be proposed`:`proposed`}function dt(e){return e.write===`report`?e.result===`classified`||e.result===`proposed`||(e.concepts?.length??0)>0||(e.issued_by?.length??0)>0:!1}function ft(e){return e==null||!Number.isFinite(e)?``:`${Math.round(e*100)}%`}var pt={rules:`Rules`,vote:`Neighbourhood vote`,model:`Model`};function mt(e){return pt[e]??e}function ht(e){let t=[];e.quote&&t.push(e.from?`“${e.quote}” (${e.from})`:`“${e.quote}”`),e.votes!=null&&t.push(`${e.votes} vote${e.votes===1?``:`s`}`);let n=ft(e.share);return n&&t.push(n),t.join(` · `)}function gt(e){return{label:mt(e.step),...e.chosen?{chosen:e.chosen}:{},...e.method?{method:e.method}:{},...e.neighbours?{neighbours:e.neighbours}:{},...e.reason?{reason:e.reason}:{},candidates:(e.candidates??[]).map(e=>({class:e.class,detail:ht(e)}))}}function _t(e){let t=[];e.type&&t.push(`type ${e.type}`);let n=e.accepted_statements?.length??0;n>0&&t.push(`${n} statement${n===1?``:`s`}`),e.tags&&e.tags.length>0&&t.push(`tags ${e.tags.join(`, `)}`);let r=[];e.type_pending&&r.push(`The proposed class stays pending: another document already holds its identity.`),e.skipped_type&&r.push(`Class ${e.skipped_type} was not applied: it is not a declared document class.`);let i=e.skipped_statements?.length??0;return i>0&&r.push(`${i} statement${i===1?` was`:`s were`} skipped (already ruled on, or not this document's proposal).`),e.skipped_tags&&e.skipped_tags.length>0&&r.push(`Tags not applied (not concepts of the ontology): ${e.skipped_tags.join(`, `)}.`),r.push(...e.warnings??[]),{applied:t.length>0?`Accepted ${t.join(`, `)}.`:`Nothing was accepted.`,notices:r}}function vt(e){let t=e instanceof Error?e.message:String(e);return t.includes(`nothing_pending`)?`Nothing is pending for this document — it may already have been accepted.`:t}function yt({documentId:e,scope:t,browse:n,rootFields:r,requestKey:i,onClose:a,onChanged:o}){let s=j(),[u,d]=(0,c.useState)(null),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(!1),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),S=(0,c.useMemo)(()=>s.documentAcceptClassification?ct(r):void 0,[s,r]);(0,c.useEffect)(()=>{if(i===0||!s.documentClassify)return;let r=!1;return p(!0),h(null),d(null),s.documentClassify(e,`report`,t,n).then(e=>!r&&d(e)).catch(e=>!r&&h(vt(e))).finally(()=>!r&&p(!1)),()=>{r=!0}},[s,e,t,n,i]);let C=async()=>{if(s.documentClassify){p(!0),h(null);try{d(await s.documentClassify(e,`propose`,t,n)),o()}catch(e){h(vt(e))}finally{p(!1)}}},w=async()=>{if(s.documentAcceptClassification){_(!0),y(null);try{x(await s.documentAcceptClassification(e,t,n)),o()}catch(e){y(vt(e))}finally{_(!1)}}},T=i>0;if(!T&&!S&&!b&&!v)return null;let E=b?_t(b):void 0;return(0,l.jsxs)(`div`,{className:`doc-classify`,children:[S&&(0,l.jsxs)(`div`,{className:`doc-classify-pending`,children:[(0,l.jsx)(`span`,{className:`doc-classify-label`,children:`Pending classification`}),S.proposedType&&(0,l.jsxs)(`span`,{children:[`class `,(0,l.jsx)(`strong`,{children:S.proposedType})]}),S.proposedTags.length>0&&(0,l.jsxs)(`span`,{children:[`tags`,` `,S.proposedTags.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e))]}),S.statementCount>0&&(0,l.jsxs)(`span`,{children:[S.statementCount,` proposed statement`,S.statementCount===1?``:`s`]}),(0,l.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>void w(),children:g?`Accepting…`:`Accept`})]}),v&&(0,l.jsxs)(`div`,{className:`doc-classify-err`,role:`alert`,children:[v,(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>y(null),"aria-label":`Dismiss`,children:`×`})]}),E&&(0,l.jsxs)(`div`,{className:`doc-classify-notice`,role:`status`,children:[(0,l.jsx)(`span`,{children:E.applied}),E.notices.map((e,t)=>(0,l.jsx)(`span`,{className:`doc-classify-warn`,children:e},t)),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>x(null),"aria-label":`Dismiss`,children:`×`})]}),T&&(0,l.jsxs)(`div`,{className:`doc-classify-panel`,children:[(0,l.jsxs)(`div`,{className:`doc-classify-head`,children:[(0,l.jsx)(`h4`,{children:`Classify`}),u&&(0,l.jsx)(`span`,{className:`doc-classify-result ${u.result}`,children:lt(u)}),u?.write===`report`&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:`report only — nothing written`}),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:a,"aria-label":`Close`,children:`×`})]}),!u&&!m&&(0,l.jsx)(`p`,{className:`doc-classify-hint`,children:`Classifying…`}),m&&(0,l.jsx)(`p`,{className:`doc-classify-err`,role:`alert`,children:m}),u&&(0,l.jsx)(bt,{answer:u}),u&&dt(u)&&(0,l.jsx)(`div`,{className:`doc-classify-actions`,children:(0,l.jsx)(`button`,{type:`button`,disabled:f,onClick:()=>void C(),title:`Apply a unique rule match to the document; file everything else for review`,children:f?`Applying…`:`Apply`})})]})]})}function bt({answer:e}){let t=ut(e),n=Object.entries(e.fields??{}),r=e.issued_by??[],i=e.concepts??[],a=(e.steps??[]).map(gt),o=e.statements?.length??0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`dl`,{className:`doc-classify-rows`,children:[e.class&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`class`}),(0,l.jsxs)(`dd`,{children:[(0,l.jsx)(`strong`,{children:e.class}),t&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` (`,t,`)`]})]})]}),e.work_key&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`work key`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:e.work_key})]}),n.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`fields`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:n.map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`).join(` · `)})]}),r.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`issued by`}),(0,l.jsx)(`dd`,{children:r.map((e,t)=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.quote,children:[e.instance,e.quote&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` “`,e.quote,`”`]})]},`${e.instance}-${t}`))})]}),i.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`concepts`}),(0,l.jsx)(`dd`,{children:i.map(e=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.tag,children:[e.concept,(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,ft(e.share)]})]},e.tag))})]}),o>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`statements`}),(0,l.jsxs)(`dd`,{children:[o,` written`,e.statements.some(e=>e.status===`proposed`)&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` (proposed ones wait for review)`})]})]})]}),a.length>0&&(0,l.jsx)(`ol`,{className:`doc-classify-steps`,children:a.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`span`,{className:`doc-classify-step`,children:e.label}),e.method&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` [`,e.method,`]`]}),e.chosen?(0,l.jsxs)(l.Fragment,{children:[` → `,(0,l.jsx)(`strong`,{children:e.chosen})]}):(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` no choice`}),e.neighbours!=null&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` · `,e.neighbours,` neighbours`]}),e.reason&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` — `,e.reason]}),e.candidates.length>0&&(0,l.jsxs)(`details`,{className:`doc-classify-candidates`,children:[(0,l.jsxs)(`summary`,{children:[e.candidates.length,` candidate`,e.candidates.length===1?``:`s`]}),(0,l.jsx)(`ul`,{children:e.candidates.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`strong`,{children:e.class}),e.detail&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,e.detail]})]},`${e.class}-${t}`))})]})]},`${e.label}-${t}`))}),e.warnings&&e.warnings.length>0&&(0,l.jsx)(`ul`,{className:`doc-classify-warnings`,children:e.warnings.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-classify-warn`,children:e},t))})]})}function xt(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((e??``).trim());if(!t)return`#888888`;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`#`+n.toLowerCase()}function St({documentId:e,rootChunkId:t,docType:n,docStatus:r,chunkStatuses:i,scope:a,browse:o,onClose:s,onSaved:u}){let d=j(),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(!1),[g,_]=(0,c.useState)({}),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),w=(0,c.useMemo)(()=>{let e=new Set(Object.keys(Z));n&&e.add(`doc.${n}.${r||`draft`}`);for(let t of i)t&&e.add(`chunk.${t}`);return[...e].sort()},[n,r,i]);(0,c.useEffect)(()=>{let e=!1;return d.documentGetChunk(t,a,o).then(t=>{if(e)return;p(t);let n=t.fields??{};h(n.color_enabled===!0);let r=n.color_scheme??{};_({...Z,...r})}).catch(t=>!e&&C(t instanceof Error?t.message:String(t))),()=>{e=!0}},[d,t,a,o]);let T=(e,t)=>_(n=>({...n,[e]:t})),E=e=>({...e??{},color_enabled:m,color_scheme:g}),D=async()=>{if(f){y(!0),C(null),x(null);try{await d.documentUpdateChunk(t,f.revision,{fields:E(f.fields)},a,o),u(),s()}catch(e){C(e instanceof Error?e.message:String(e)),y(!1)}}},O=async()=>{if(!n)C(`this document has no type to match`);else{y(!0),C(null),x(null);try{let{documents:t}=await d.documentsSummary({underPath:`/`},a,o),r=(t??[]).filter(t=>t.type===n&&t.document_id!==e&&t.root_chunk_id),i=0;for(let e of r)try{let t=await d.documentGetChunk(e.root_chunk_id,a,o);await d.documentUpdateChunk(e.root_chunk_id,t.revision,{fields:E(t.fields)},a,o),i++}catch{}x(`Applied to ${i} other ${n} document(s).`),u()}catch(e){C(e instanceof Error?e.message:String(e))}finally{y(!1)}}},k=w.filter(e=>e.startsWith(`doc.`)),A=w.filter(e=>e.startsWith(`chunk.`));return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:s,children:(0,l.jsxs)(`div`,{className:`modal scheme-editor`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`scheme-editor-head`,children:[(0,l.jsx)(`h3`,{children:`Document colors`}),(0,l.jsxs)(`div`,{className:`scheme-editor-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:s,disabled:v,children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`primary`,onClick:()=>void D(),disabled:v||!f,children:v?`saving…`:`save`})]})]}),S&&(0,l.jsx)(`div`,{className:`modal-err`,children:S}),f?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`label`,{className:`scheme-toggle`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked)}),(0,l.jsx)(`span`,{children:`Enable coloring for this document`})]}),(0,l.jsx)(`p`,{className:`modal-context`,children:`Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable.`}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Document (type · status)`}),k.map(e=>(0,l.jsx)(Ct,{label:e.slice(4),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Chunks (status)`}),A.map(e=>(0,l.jsx)(Ct,{label:e.slice(6),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-editor-foot`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>void O(),disabled:v||!n,title:n?`Apply this palette to every other ${n} document`:`This document has no type`,children:[`copy to all `,n||`same-type`,` documents`]}),b&&(0,l.jsx)(`span`,{className:`scheme-status`,children:b})]})]}):(0,l.jsx)(`p`,{className:`modal-context`,children:`Loading…`})]})})}function Ct({label:e,value:t,onChange:n}){let r=xt(t);return(0,l.jsxs)(`label`,{className:`scheme-row`,children:[(0,l.jsx)(`input`,{type:`color`,value:r,onChange:e=>n(e.target.value)}),(0,l.jsx)(`span`,{className:`scheme-key`,children:e}),(0,l.jsx)(`code`,{className:`scheme-hex`,children:r})]})}function wt({id:e,title:t,targetDocumentId:n,documentId:r,onSelectChunk:i,onOpenDocument:a}){let o=t||e.slice(0,8);return!n||n===r?(0,l.jsx)(`button`,{type:`button`,className:`doc-ref-target`,onClick:()=>i(e),children:o}):a?(0,l.jsxs)(`button`,{type:`button`,className:`doc-ref-target external`,title:`In another document — opens it at this chunk`,onClick:()=>a(n,e,t),children:[o,` ↗`]}):(0,l.jsxs)(`span`,{className:`doc-ref-target external`,title:`In another document`,children:[o,` ↗`]})}function Tt({statement:e}){let t=we(e),n=Te(e),r=De(e),i=Ee(e),{rows:a,more:o}=Oe(e);return(0,l.jsxs)(l.Fragment,{children:[t&&(0,l.jsx)(`span`,{className:`doc-stmt-status ${t}`,children:t}),n&&(0,l.jsx)(`span`,{className:`doc-stmt-method`,title:`how this relation was made`,children:n}),r&&(0,l.jsx)(`span`,{className:`doc-stmt-verdict`,title:r,children:`judged`}),i&&(0,l.jsx)(`span`,{className:`doc-stmt-valid`,children:i}),a.length>0&&(0,l.jsxs)(`ul`,{className:`doc-stmt-evidence`,children:[a.map(e=>(0,l.jsxs)(`li`,{title:e.quote,children:[`“`,ke(e.quote),`”`,e.stale&&(0,l.jsx)(`span`,{className:`doc-stmt-stale`,children:` (source changed)`})]},e.id)),o>0&&(0,l.jsxs)(`li`,{className:`doc-stmt-more`,children:[`+`,o,` more`]})]})]})}function Et({id:e,onRule:t}){let[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=async n=>{s(!0),d(null);try{await t(e,n,n?void 0:i.trim()),r(!1),a(``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{s(!1)}};return(0,l.jsxs)(`span`,{className:`doc-stmt-review`,children:[n?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:i,disabled:o,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i.trim()&&f(!1),e.key===`Escape`&&r(!1)},autoFocus:!0}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:o||!i.trim(),onClick:()=>void f(!1),children:`Reject`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!1),children:`Cancel`})]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>void f(!0),children:`Accept`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!0),children:`Reject…`})]}),u&&(0,l.jsx)(`span`,{className:`doc-stmt-err`,role:`alert`,children:u})]})}var Dt=3;function Ot({documentId:e,proposals:t,incomplete:n,scope:r,browse:i,onChanged:a,onSelectChunk:o,onOpenDocument:s}){let u=j(),[d,f]=(0,c.useState)(new Set),[p,m]=(0,c.useState)({kind:`idle`}),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useRef)(null),S=new Set(t.map(e=>e.id)),C=[...d].filter(e=>S.has(e)),w=p.kind!==`idle`&&p.kind!==`reason`,T=(e,t)=>{v(null),b(null),e===`reject`?m({kind:`reason`,action:e,all:t}):E(e,t,``)},E=async(t,n,o)=>{m({kind:`counting`,action:t,all:n});let s;try{s=await Le(u,{documentId:e,action:t,ids:n?void 0:C,reason:o.trim()||void 0,scope:r,browse:i},{confirm:(e,r)=>new Promise(i=>{x.current=i,m({kind:`confirm`,action:t,all:n,dry:e,changed:r!==`first`})}),onProgress:e=>m({kind:`ruling`,action:t,ruled:e.ruled,total:e.total})})}catch(e){s={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[],error:e}}x.current=null,m({kind:`idle`}),g(``),s.rulingIds.length>0?(f(new Set),b({text:Re(t,s),rulingIds:s.rulingIds}),a()):s.error===void 0&&!s.cancelled&&b({text:`Nothing to rule: no proposals match.`,rulingIds:[]}),s.error!==void 0&&v(s.error instanceof Error?s.error.message:String(s.error))},D=e=>{e&&p.kind===`confirm`&&m({kind:`ruling`,action:p.action}),x.current?.(e)},O=async()=>{if(!y||!u.documentRevertRuling)return;let e=y,t=await Me(e=>u.documentRevertRuling(e,r,i),e.rulingIds),n=[`${t.reverted} came back to review`];t.changed>0&&n.push(`${t.changed} changed since and left as ruled`),t.errors.length>0&&n.push(`not undone: ${t.errors.join(`; `)}`),b({...e,undone:!0,text:n.join(`; `)+`.`}),a()},k=e=>f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),A=t.length>0&&C.length===t.length,M=t.length===0&&!n;return(0,l.jsxs)(`div`,{className:`doc-conn-group doc-bulk`,children:[(0,l.jsxs)(`h5`,{children:[`Proposals from this document (`,t.length,`)`]}),(0,l.jsxs)(`div`,{className:`doc-bulk-bar`,children:[(0,l.jsxs)(`label`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select every proposal shown`,checked:A,disabled:w||t.length===0,onChange:()=>f(A?new Set:new Set(S))}),` `,`all shown`]}),(0,l.jsxs)(`button`,{type:`button`,disabled:w||C.length===0,onClick:()=>T(`accept`,!1),children:[`Accept selected (`,C.length,`)`]}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||C.length===0,onClick:()=>T(`reject`,!1),children:`Reject selected…`}),(0,l.jsx)(`button`,{type:`button`,disabled:w||M,onClick:()=>T(`accept`,!0),children:`Accept all from this document`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||M,onClick:()=>T(`reject`,!0),children:`Reject all…`})]}),p.kind===`reason`&&(0,l.jsxs)(`form`,{className:`doc-bulk-step`,onSubmit:e=>{e.preventDefault(),h.trim()&&E(p.action,p.all,h)},children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:h,onChange:e=>g(e.target.value),autoFocus:!0}),(0,l.jsx)(`button`,{type:`submit`,className:`danger`,disabled:!h.trim(),children:`Count`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>m({kind:`idle`}),children:`Cancel`})]}),p.kind===`counting`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`counting…`}),p.kind===`confirm`&&(0,l.jsx)(kt,{step:p,onAnswer:D}),p.kind===`ruling`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:p.total?`ruled ${p.ruled??0} of ${p.total}…`:`ruling…`}),_&&(0,l.jsx)(`p`,{className:`doc-stmt-err`,role:`alert`,children:_}),y&&(0,l.jsxs)(`p`,{className:`doc-bulk-result`,role:`status`,children:[y.text,y.rulingIds.length>0&&!y.undone&&u.documentRevertRuling&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>void O(),children:`Undo`})]}),t.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:t.map(t=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select ${t.from_title??t.from_id} ${t.kind} ${t.to_title??t.to_id}`,checked:d.has(t.id),disabled:w,onChange:()=>k(t.id)}),(0,l.jsx)(wt,{id:t.from_id,title:t.from_title,targetDocumentId:t.from_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:t.kind}),(0,l.jsx)(wt,{id:t.to_id,title:t.to_title,targetDocumentId:t.to_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(Tt,{statement:t})]},t.id))})]})}function kt({step:e,onAnswer:t}){let{dry:n}=e,r=e.action===`accept`?`Accept`:`Reject`,i=Ne(n.matched);return(0,l.jsxs)(`div`,{className:`doc-bulk-step doc-bulk-confirm`,children:[e.changed&&(0,l.jsx)(`p`,{className:`doc-bulk-warn`,children:`The proposals changed since the last count; counted again.`}),(0,l.jsxs)(`p`,{children:[r,` `,n.matched,` statement`,n.matched===1?``:`s`,e.all?` filed from this document`:``,i>1?`, in ${i} rulings of up to 1,000`:``,`?`,n.skipped>0&&` ${n.skipped} of them are not yours to rule and will be skipped.`]}),(n.sample??[]).length>0&&(0,l.jsx)(`ul`,{className:`doc-bulk-sample`,children:(n.sample??[]).slice(0,Dt).map(e=>(0,l.jsxs)(`li`,{children:[e.from_title||e.from_id,` `,(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),` `,e.to_title||e.to_id]},e.id))}),(0,l.jsxs)(`button`,{type:`button`,className:e.action===`reject`?`danger`:void 0,onClick:()=>t(!0),children:[r,` `,n.matched]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>t(!1),children:`Cancel`})]})}var At=8,jt=20;function Mt(e){return/embedder|embedding|vector|semantic|not configured/i.test(e)}function Nt({documentId:e,selectedId:t,scope:n,browse:r,onSelectChunk:i,onOpenDocument:a,refreshKey:o,review:s}){let u=j(),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(void 0),[_,v]=(0,c.useState)([]),[y,b]=(0,c.useState)([]),[x,S]=(0,c.useState)(null),[C,w]=(0,c.useState)([]),[T,E]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(!d||!t)return;let e=t,i=!1;return m(!0),Promise.allSettled([u.documentBacklinks(e,n,r),u.documentRelated(e,n,r,At),u.documentUnlinkedMentions(e,n,r,jt)]).then(([t,n,r])=>{if(!i){if(v(t.status===`fulfilled`?t.value.backlinks??[]:[]),n.status===`fulfilled`)b(n.value.related??[]),S(null);else{b([]);let e=n.reason instanceof Error?n.reason.message:String(n.reason);S(Mt(e)?`semantic search not configured`:e)}r.status===`fulfilled`?(w(r.value.unlinked_mentions??[]),E(!!r.value.truncated)):(w([]),E(!1)),g(e),m(!1)}}),()=>{i=!0}},[u,d,t,n,r,o]);let D=(t,n,r)=>(0,l.jsx)(wt,{id:t,title:n,targetDocumentId:r,documentId:e,onSelectChunk:i,onOpenDocument:a}),O=!!(d&&t&&!p&&h===t);return(0,l.jsxs)(`div`,{className:`doc-conn`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-conn-toggle`,onClick:()=>f(e=>!e),children:[d?`▼`:`▶`,` Connections`]}),d&&(0,l.jsxs)(`div`,{className:`doc-conn-body`,children:[s&&(0,l.jsx)(Ot,{documentId:e,proposals:s.proposals,incomplete:s.incomplete,scope:s.scope,browse:r,onChanged:s.onChanged,onSelectChunk:i,onOpenDocument:a}),t?O?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Backlinks`}),_.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:_.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.from_id,e.from_title,e.from_document_id),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),e.auto&&(0,l.jsx)(`span`,{className:`doc-conn-auto`,title:`Auto-linked from a [[wikilink]]`,children:`auto`}),(0,l.jsx)(Tt,{statement:e})]},`${e.from_id}-${e.kind}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Related`}),x?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:x}):y.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:y.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.chunk_id,e.title,e.document_id),(0,l.jsx)(`span`,{className:`doc-conn-score`,title:`similarity score`,children:e.score.toFixed(2)})]},`${e.chunk_id}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Unlinked mentions`}),C.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsxs)(`ul`,{className:`doc-conn-list`,children:[C.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-conn-row`,children:D(e.chunk_id,e.title,e.document_id)},`${e.chunk_id}-${t}`)),T&&(0,l.jsx)(`li`,{className:`doc-conn-more`,"aria-hidden":!0,children:`(more…)`})]})]})]}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`loading…`}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`Select a chunk.`})]})]})}var Pt=24;function Ft({edges:e,documentId:t,selectedId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a,incomplete:o}){let[s,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(!1);if(e.length===0)return null;let p=n?e.filter(e=>e.from_id===n||e.to_id===n):[],m=d?e:e.slice(0,Pt),h=Lt(m);return(0,l.jsxs)(`div`,{className:`doc-refs`,children:[o&&(0,l.jsxs)(`p`,{className:`doc-refs-incomplete`,children:[`Showing the first `,e.length,` links of this document; it has more, which are not shown here or in the graph.`]}),n&&(0,l.jsxs)(`div`,{className:`doc-refs-list-wrap`,children:[(0,l.jsx)(`h4`,{children:`References`}),p.length===0?(0,l.jsx)(`p`,{className:`doc-refs-empty`,children:`This chunk has no links.`}):(0,l.jsx)(`ul`,{className:`doc-refs-list`,children:p.map((e,o)=>(0,l.jsx)(It,{edge:e,selectedId:n,documentId:t,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a},`${e.from_id}-${e.to_id}-${e.kind}-${o}`))})]}),(0,l.jsxs)(`div`,{className:`doc-graph`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-graph-toggle`,onClick:()=>u(e=>!e),children:[s?`▼`:`▶`,` relationship graph (`,e.length,`)`]}),s&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(rt,{code:h,onNodeClick:e=>{let n=Rt(m,e);n&&(!n.documentId||n.documentId===t?r(n.id):i?.(n.documentId,n.id,n.title))}}),e.length>Pt&&(0,l.jsx)(`button`,{type:`button`,className:`doc-graph-more`,onClick:()=>f(e=>!e),children:d?`show top ${Pt}`:`show all ${e.length}`})]})]})]})}function It({edge:e,selectedId:t,documentId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a}){let o=e.from_id===t,s=o?e.to_id:e.from_id,c=o?e.to_title:e.from_title,u=o?e.to_document_id:e.from_document_id;return(0,l.jsxs)(`li`,{className:`doc-ref`,children:[(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),(0,l.jsx)(`span`,{className:`doc-ref-arrow`,"aria-hidden":!0,children:o?`→`:`←`}),(0,l.jsx)(wt,{id:s,title:c,targetDocumentId:u,documentId:n,onSelectChunk:r,onOpenDocument:i}),(0,l.jsx)(Tt,{statement:e}),a&&G(e)&&(0,l.jsx)(Et,{id:e.id,onRule:a})]})}function Lt(e){let t=[`graph LR`];for(let n of e){let e=`${zt(n.from_id)}["${Bt(n.from_title,n.from_id)}"]`,r=`${zt(n.to_id)}["${Bt(n.to_title,n.to_id)}"]`,i=(n.kind||`link`).replace(/[|"]/g,` `),a=n.status===`proposed`?`-.->`:`-->`;t.push(` ${e} ${a}|${i}| ${r}`)}return t.join(`
|
|
2
|
+
`)}function Rt(e,t){for(let n of e){if(zt(n.from_id)===t)return{id:n.from_id,documentId:n.from_document_id,title:n.from_title};if(zt(n.to_id)===t)return{id:n.to_id,documentId:n.to_document_id,title:n.to_title}}}function zt(e){return`n`+e.replace(/[^a-zA-Z0-9]/g,``)}function Bt(e,t){let n=(e??``).replace(/["[\]{}|<>]/g,` `).replace(/\s+/g,` `).trim()||t.slice(0,6);return n.length>30?n.slice(0,29)+`…`:n}var Vt=6;function Ht(e,t,n,r){let i=Math.max(r,t-n-Vt);return Math.round(Math.max(r,Math.min(e,i)))}function Ut({children:e,defaultBottomHeight:t=240,minTopHeight:n=96,minBottomHeight:r=48,storageKey:i,className:a}){let[o,s]=(0,c.useState)(()=>{if(i)try{let e=parseInt(localStorage.getItem(i)??``,10);if(Number.isFinite(e)&&e>=r)return e}catch{}return t}),u=(0,c.useRef)(null),[d,f]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(i&&!d)try{localStorage.setItem(i,String(o))}catch{}},[i,o,d]);let p=(0,c.useCallback)(e=>{e.preventDefault(),f(!0),e.target.setPointerCapture(e.pointerId)},[]),m=(0,c.useCallback)(e=>{if(!d||!u.current)return;let t=u.current.getBoundingClientRect();s(Ht(t.bottom-e.clientY,t.height,n,r))},[d,n,r]),h=(0,c.useCallback)(e=>{f(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:u,className:`stack-splitter ${a??``} ${d?`dragging`:``}`,style:{gridTemplateRows:`minmax(${n}px, 1fr) ${Vt}px min(${o}px, calc(100% - ${n+Vt}px))`},children:[(0,l.jsx)(`div`,{className:`stack-splitter-pane stack-splitter-top`,children:e[0]}),(0,l.jsx)(`div`,{className:`stack-splitter-handle`,role:`separator`,"aria-orientation":`horizontal`,"aria-valuenow":o,title:`Drag to share the space between the text and its links`,onPointerDown:p,onPointerMove:m,onPointerUp:h,onPointerCancel:h}),(0,l.jsx)(`div`,{className:`stack-splitter-pane stack-splitter-bottom`,children:e[1]})]})}function Wt({documentId:e,scope:t,detail:n}){return(0,l.jsxs)(`div`,{className:`doc-unavailable`,role:`alert`,children:[(0,l.jsx)(`p`,{className:`doc-unavailable-lead`,children:`This document can’t be opened.`}),(0,l.jsxs)(`p`,{children:[`It may have been deleted, live in a scope other than `,(0,l.jsx)(`code`,{children:t}),`, or not be yours to read.`]}),(0,l.jsxs)(`p`,{className:`doc-unavailable-detail`,children:[(0,l.jsx)(`code`,{children:e}),n&&(0,l.jsxs)(l.Fragment,{children:[` — `,n]})]})]})}function Gt(e){let t=typeof e==`number`?e/1e6:Date.parse(String(e));return!Number.isFinite(t)||t<=0?String(e??``):new Date(t).toLocaleString()}function Kt({chunkId:e,chunkTitle:t,scope:n,browse:r,onClose:i}){let a=j(),[o,s]=(0,c.useState)([]),[u,d]=(0,c.useState)(!0),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(`none`),[g,_]=(0,c.useState)(null),[v,y]=(0,c.useState)(``),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(``);(0,c.useEffect)(()=>{let t=!1;return d(!0),p(null),a.documentHistory(e,n,r).then(e=>{if(t)return;let n=e.revisions??[];if(s(n),n.length>=2){let e=n.map(e=>e.revision);C(Math.min(...e)),T(Math.max(...e))}}).catch(e=>!t&&p(e instanceof Error?e.message:String(e))).finally(()=>!t&&d(!1)),()=>{t=!0}},[a,e,n,r]);let O=async t=>{p(null),x(!0),_(t),h(`version`);try{let i=await a.documentGetVersion(e,t,n,r);y(i.body??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}},k=async()=>{if(S!==null&&w!==null){p(null),x(!0),h(`diff`);try{let t=await a.documentDiff(e,S,w,n,r);D(t.diff??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}}};return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:i,children:(0,l.jsxs)(`div`,{className:`modal history-modal`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`History`,t?` — ${t}`:``]}),(0,l.jsx)(`div`,{className:`modal-buttons modal-buttons-top`,children:(0,l.jsx)(`button`,{type:`button`,onClick:i,children:`close`})})]}),f&&(0,l.jsx)(`div`,{className:`modal-err`,children:f}),u?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):o.length===0?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`No history recorded for this chunk.`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`div`,{className:`doc-hist-revs`,children:o.map(e=>(0,l.jsxs)(`button`,{type:`button`,className:`doc-hist-rev`+(m===`version`&&g===e.revision?` active`:``),onClick:()=>void O(e.revision),children:[(0,l.jsxs)(`span`,{className:`doc-hist-rev-num`,children:[`rev `,e.revision]}),(0,l.jsx)(`span`,{className:`doc-hist-rev-time`,children:Gt(e.created_at)}),(0,l.jsx)(`span`,{className:`doc-hist-rev-actor`,children:e.actor||`unknown`})]},e.revision))}),o.length>=2&&(0,l.jsxs)(`div`,{className:`doc-hist-diffbar`,children:[(0,l.jsx)(`span`,{children:`Compare`}),(0,l.jsx)(`select`,{value:S??``,onChange:e=>C(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff from revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`span`,{"aria-hidden":!0,children:`→`}),(0,l.jsx)(`select`,{value:w??``,onChange:e=>T(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff to revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void k(),disabled:b||S===null||w===null,children:`diff`})]}),(0,l.jsx)(`div`,{className:`doc-hist-output`,children:b?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):m===`diff`?(0,l.jsx)(qt,{text:E}):m===`version`?(0,l.jsx)(`pre`,{className:`md-pre doc-hist-version`,children:(0,l.jsx)(`code`,{children:v||`(empty)`})}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Select a revision to view it, or compare two.`})})]})]})})}function qt({text:e}){if(!e.trim())return(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(no differences)`});let t=e.split(`
|
|
3
3
|
`);return(0,l.jsx)(`pre`,{className:`md-pre doc-hist-diff`,children:t.map((e,t)=>{let n=e.startsWith(`+`)&&!e.startsWith(`+++`)?`diff-add`:e.startsWith(`-`)&&!e.startsWith(`---`)?`diff-del`:e.startsWith(`@@`)?`diff-hunk`:``;return(0,l.jsxs)(`span`,{className:n,children:[e,`
|
|
4
|
-
`]},t)})})}function
|
|
5
|
-
`)?(0,l.jsx)(`pre`,{className:`md-pre`,children:(0,l.jsx)(`code`,{className:e,children:t})}):(0,l.jsx)(`code`,{children:t})}};function
|
|
4
|
+
`]},t)})})}function Jt({source:e}){return(0,l.jsx)(`div`,{className:`md`,children:(0,l.jsx)(d.default,{remarkPlugins:[f.default],components:Yt,children:e})})}var Yt={a({href:e,children:t}){let n=e??``,r=/^https?:\/\//i.test(n);return(0,l.jsx)(`a`,{href:n,target:r?`_blank`:void 0,rel:r?`noopener noreferrer`:void 0,children:t})},pre({children:e}){return(0,l.jsx)(l.Fragment,{children:e})},code({className:e,children:t}){let n=/language-(\w+)/.exec(e??``)?.[1],r=String(t??``);return n===`mermaid`?(0,l.jsx)(rt,{code:r.replace(/\n$/,``)}):n||r.includes(`
|
|
5
|
+
`)?(0,l.jsx)(`pre`,{className:`md-pre`,children:(0,l.jsx)(`code`,{className:e,children:t})}):(0,l.jsx)(`code`,{children:t})}};function Xt(e){let t=e.fields??{};return typeof t.alt==`string`&&t.alt.trim()!==``?t.alt:e.title||`image`}function Zt({documentId:e,scope:t,titleHint:n,browse:r,principal:i,renderAssistant:a,initialChunkId:o,onOpenDocument:s,onTitle:u,onChunkSelect:d,focusChunk:f}){let p=j(),m=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),[h,_]=(0,c.useState)([]),[v,y]=(0,c.useState)(void 0),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(`chunks`),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(null),[O,k]=(0,c.useState)(null),A=(0,c.useRef)(null),[M,N]=(0,c.useState)(null),[ee,te]=(0,c.useState)(null),[P,F]=(0,c.useState)(!1),[ne,re]=(0,c.useState)(!1),[ie,I]=(0,c.useState)(null),[L,R]=(0,c.useState)(!1),[z,ae]=(0,c.useState)(void 0),[oe,se]=(0,c.useState)(null),[ce,le]=(0,c.useState)(0),[B,ue]=(0,c.useState)(!1),[V,de]=(0,c.useState)(null),[fe,me]=(0,c.useState)(!1),[he,H]=(0,c.useState)([]),[_e,U]=(0,c.useState)(!1),[be,Se]=(0,c.useState)(0),[Ce,we]=(0,c.useState)(0),[Te,G]=(0,c.useState)(void 0),K=(0,c.useCallback)(()=>le(e=>e+1),[]),Ee=(0,c.useRef)(o);Ee.current=o;let De=(0,c.useRef)(u);De.current=u;let Oe=(0,c.useMemo)(()=>Ye(h),[h]),ke=(0,c.useMemo)(()=>h.find(e=>!e.parent_id)?.title||n||`document`,[h,n]),q=(0,c.useMemo)(()=>!!b&&!b.parent_id,[b]),J=(0,c.useMemo)(()=>xe(h,b?.id),[h,b]),Y=(0,c.useMemo)(()=>V?.root_chunk_id??h.find(e=>!e.parent_id)?.id,[V,h]),Ae=(0,c.useRef)(d);Ae.current=d,(0,c.useEffect)(()=>{v&&Ae.current?.(v===Y?void 0:v)},[v,Y]);let je=(0,c.useMemo)(()=>[...new Set(h.map(e=>e.status).filter(e=>!!e))],[h]),Me=!!V?.color_enabled,Ne=(0,c.useMemo)(()=>{let e=new Set;for(let t of he)e.add(t.from_id),e.add(t.to_id);return e},[he]),X=(0,c.useMemo)(()=>Me?Q(V?.type,V?.status,Be(V?.color_scheme)):void 0,[Me,V?.type,V?.status,V?.color_scheme]),Le=(0,c.useMemo)(()=>$(X),[X]);(0,c.useEffect)(()=>{let n=!1;return R(!0),I(null),se(null),p.documentQueryChunks(e,t,m).then(r=>{if(n)return;let i=r.chunks??[];_(i),ae(`${t}:${e}`),y(e=>e??pe(i,Ee.current))}).catch(e=>{n||(_([]),se(e instanceof Error?e.message:String(e)))}).finally(()=>!n&&R(!1)),()=>{n=!0}},[p,e,t,ce,m]);let Re=!L&&(oe!==null||z===`${t}:${e}`&&h.length===0),Z=(0,c.useMemo)(()=>h.find(t=>!t.parent_id&&t.document_id===e)?.title,[h,e]);(0,c.useEffect)(()=>{Z&&De.current?.(e,Z)},[e,Z]),(0,c.useEffect)(()=>{let n=!1;return p.documentGet(e,t,m).then(e=>!n&&de(e)).catch(()=>!n&&de(null)),()=>{n=!0}},[p,e,t,ce,m]),(0,c.useEffect)(()=>{let n=!1;return W(p,e,t,m).then(e=>{n||(H(e.edges),U(e.incomplete))}).catch(()=>{n||(H([]),U(!1))}),()=>{n=!0}},[p,e,t,ce,m,be]),(0,c.useEffect)(()=>{if(!Y||!p.documentAcceptClassification){G(void 0);return}let n=!1;return p.documentGetChunk(Y,t,m).then(t=>!n&&G(t.document_id===e?t.fields:void 0)).catch(()=>!n&&G(void 0)),()=>{n=!0}},[p,e,Y,t,ce,m]);let ze=(0,c.useMemo)(()=>{if(p.documentAcceptStatement&&p.documentRejectStatement)return async(e,n,r)=>{n?await p.documentAcceptStatement(e,t,m,r):await p.documentRejectStatement(e,r??``,t,m),Se(e=>e+1)}},[p,t,m]),Ve=(0,c.useMemo)(()=>Pe(p,t),[p,t]),He=(0,c.useMemo)(()=>Fe(he,e),[he,e]),Ue=(0,c.useCallback)(()=>Se(e=>e+1),[]),We=(0,c.useMemo)(()=>Ie(Ve,He,_e,Ue),[Ve,He,_e,Ue]),Ge=f?.seq,Ke=(0,c.useRef)(f);Ke.current=f;let qe=(0,c.useRef)(Y);qe.current=Y;let Xe=(0,c.useRef)(h);Xe.current=h,(0,c.useEffect)(()=>{if(Ge===void 0)return;let e=Ke.current?.chunkId,t=Xe.current.length>0?pe(Xe.current,e):e??qe.current;t&&y(t)},[Ge]),(0,c.useEffect)(()=>{y(void 0),x(null),T(null),C(`chunks`),de(null),H([]),U(!1),we(0),G(void 0)},[e,t]),(0,c.useEffect)(()=>{if(!v){x(null);return}let e=!1;return p.documentGetChunk(v,t,m).then(t=>!e&&x(t)).catch(t=>!e&&I(t instanceof Error?t.message:String(t))),()=>{e=!0}},[p,v,t,ce,m]),(0,c.useEffect)(()=>{let e=b?.type===`image`||!!b?.asset;if(!b||!e||!p.documentAssetObjectUrl){D(null),k(null);return}let n=!1,r=null;return k(null),p.documentAssetObjectUrl(b.id,t,m).then(e=>{n?URL.revokeObjectURL(e):(r=e,D(e))}).catch(e=>!n&&k(e instanceof Error?e.message:String(e))),()=>{n=!0,r&&URL.revokeObjectURL(r)}},[p,b,t,m]),(0,c.useEffect)(()=>{if(S!==`markdown`||!v){T(null);return}let e=Ze(Oe,v);if(!e)return;let n=!1,r=[],i=(e,t)=>{r.push({node:e,depth:t}),e.children.forEach(e=>i(e,t+1))};return i(e,0),Promise.all(r.map(e=>p.documentGetChunk(e.node.row.id,t,m))).then(e=>{if(n)return;let t=r.map((t,n)=>{let r=Math.min(t.depth+1,6),i=e[n],a=`#`.repeat(r)+` `+t.node.row.title;if(i.type===`mermaid`&&i.body)return a+`
|
|
6
6
|
|
|
7
7
|
\`\`\`mermaid
|
|
8
8
|
`+i.body+"\n```\n";if(i.type===`image`||i.asset){let e=i.body?` — `+i.body:``;return a+`
|
|
@@ -12,6 +12,6 @@ _🖼 image chunk_`+e+`
|
|
|
12
12
|
|
|
13
13
|
`+i.body:``)+`
|
|
14
14
|
`}).join(`
|
|
15
|
-
`);T(t)}).catch(e=>!n&&I(e instanceof Error?e.message:String(e))),()=>{n=!0}},[p,S,v,
|
|
16
|
-
A[Start] --> B[End]`},t,m);q(),y(r.id),N(r)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,X,q]),lt=(0,c.useCallback)(async()=>{if(!p.documentCreateChunk)return;let n=v&&!J?v:void 0,r=v||X;if(r){I(null);try{let i=await p.documentCreateChunk(e,n?``:r,{title:`Text`,body:``},t,m,n);q(),y(i.id),N(i)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,J,X,q]),ut=(0,c.useCallback)(async()=>{if(p.documentCreateChunk&&v){I(null);try{let n=await p.documentCreateChunk(e,v,{title:`Text`,body:``},t,m);q(),y(n.id),N(n)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,q]),dt=(0,c.useMemo)(()=>{if(!b||J)return{canUp:!1,canDown:!1};let e=b.parent_id??``,t=h.filter(t=>(t.parent_id??``)===e).sort((e,t)=>e.position-t.position||e.id.localeCompare(t.id)),n=t.findIndex(e=>e.id===b.id);return{canUp:n>0,canDown:n>=0&&n<t.length-1}},[h,b,J]),ft=(0,c.useCallback)(async e=>{if(p.documentReorderChunk&&v){I(null);try{await p.documentReorderChunk(v,e,t,m),q()}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,v,t,m,q]),pt=(0,c.useCallback)(async()=>{if(!p.documentDeleteChunk||!b)return;I(null);let e=b.parent_id;try{await p.documentDeleteChunk(b.id,t,m),re(!1),y(e||X),q()}catch(e){I(e instanceof Error?e.message:String(e)),re(!1)}},[p,b,t,m,X,q]);return(0,c.useEffect)(()=>{if(!ot)return;let e=e=>{if(M||ue)return;let t=document.activeElement,n=t?.tagName;if(n===`INPUT`||n===`TEXTAREA`||t?.isContentEditable)return;let r=_e(e.clipboardData?.items);r&&(e.preventDefault(),st(r))};return window.addEventListener(`paste`,e),()=>window.removeEventListener(`paste`,e)},[ot,M,ue,st]),(0,l.jsxs)(`div`,{className:`doc-viewer`,children:[(0,l.jsx)(`input`,{ref:A,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&st(t)}}),(0,l.jsxs)(`div`,{className:`doc-toolbar`,style:Ie,children:[(0,l.jsx)(`strong`,{className:`doc-title`,title:Oe,children:Oe}),(0,l.jsx)(qe,{value:e,label:`doc`}),(0,l.jsxs)(`div`,{className:`doc-toolbar-actions`,children:[ot&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void lt(),title:`Add a text chunk AFTER the selected chunk, at the same level`,children:`+ text`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ut(),disabled:!v,title:v?`Add a chunk NESTED UNDER the selected chunk (in the ontology, a child is a subclass)`:`Select a chunk first — this nests a new chunk under it`,children:`+ child`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>A.current?.click(),title:`Add an image chunk (upload — or paste a screenshot into the view)`,children:`+ image`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ct(),title:`Add a Mermaid diagram chunk`,children:`+ diagram`})]}),(0,l.jsx)(`button`,{type:`button`,className:je?`active`:``,onClick:()=>fe(!0),disabled:!X,title:`Colors — tint chunk tiles + the Path tree by type/status`,children:`colors`}),p.documentClassify&&(0,l.jsx)(`button`,{type:`button`,className:xe>0?`active`:``,onClick:()=>Se(e=>e>0?0:1),title:`Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)`,children:`classify`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void tt(),title:`Download the whole document as Markdown (.md)`,children:`↓ .md`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void at(),title:`Download the whole document as a node/edge canvas graph (.canvas)`,children:`↓ .canvas`}),a&&(0,l.jsx)(`button`,{type:`button`,className:V?`active`:``,onClick:()=>H(e=>!e),title:`Document Assistant — instruct an agent to restructure/import/link chunks`,children:`assistant`}),(0,l.jsx)(`button`,{type:`button`,onClick:q,title:`Reload`,children:`↻`})]})]}),ie&&(0,l.jsx)(`div`,{className:`paths-err`,children:ie}),!Le&&(0,l.jsx)(vt,{documentId:e,scope:t,browse:m,rootFields:Ce,requestKey:xe,onClose:()=>Se(0),onChanged:q},`${t}:${e}`),Le?(0,l.jsx)(Ut,{documentId:e,scope:t,detail:oe??void 0}):(0,l.jsxs)(me,{className:`doc-split`,defaultLeftWidth:320,minLeftWidth:160,minRightWidth:320,storageKey:`loomcycle.explorer.split.doc`,children:[(0,l.jsx)(`div`,{className:`doc-chunktree`,children:L&&h.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):(0,l.jsx)(Ze,{tree:De,selectedId:v,onSelect:$e,colorEnabled:je,scheme:U?.color_scheme,documentColor:Z,linkedIds:Me})}),(0,l.jsx)(`div`,{className:`doc-content`,children:b?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-content-head`,children:[Y.length>0&&(0,l.jsxs)(`nav`,{className:`chunk-ancestry`,"aria-label":`Chunks above this one`,children:[(0,l.jsx)(`button`,{type:`button`,className:`chunk-ancestry-up`,onClick:()=>y(Y[Y.length-1].id),title:`Up to ${Y[Y.length-1].title||`(untitled)`}`,children:`↰ Up`}),(0,l.jsxs)(`ol`,{className:`doc-trail-list`,children:[Y.map(e=>(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>y(e.id),title:e.title||`(untitled)`,children:e.title||`(untitled)`})},e.id)),(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`location`,title:b.title||`(untitled)`,children:b.title||`(untitled)`})})]})]}),(0,l.jsx)(`h3`,{children:b.title||`(untitled)`}),(0,l.jsxs)(`div`,{className:`doc-content-meta`,children:[b.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:b.type}),b.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:b.status}),(0,l.jsxs)(`span`,{className:`chunk-rev`,children:[`rev `,b.revision]}),b.tags?.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e)),(0,l.jsx)(qe,{value:b.id,label:`chunk`})]}),(0,l.jsxs)(`div`,{className:`doc-content-controls`,children:[(0,l.jsxs)(`div`,{className:`doc-mode-toggle`,children:[(0,l.jsx)(`button`,{type:`button`,className:S===`chunks`?`active`:``,onClick:()=>C(`chunks`),title:`This chunk's own content`,children:`chunk`}),(0,l.jsx)(`button`,{type:`button`,className:S===`markdown`?`active`:``,onClick:()=>C(`markdown`),title:J?`Whole document as Markdown`:`This chunk + its sub-chunks as Markdown`,children:`markdown`})]}),(0,l.jsx)(`button`,{type:`button`,className:`chunk-edit`,onClick:()=>N(b),children:`edit`}),p.documentEntityTypes&&g(b)&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>te(b),title:`Change this subject's type to another type in force`,children:`change type`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>F(!0),title:`View this chunk's edit history + diffs`,children:`history`}),!J&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ft(`up`),disabled:!dt.canUp,title:`Move this chunk up within its level`,children:`↑`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ft(`down`),disabled:!dt.canDown,title:`Move this chunk down within its level`,children:`↓`})]}),!J&&(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>re(!0),title:`Delete this chunk and its sub-chunks`,children:`delete`})]})]}),(0,l.jsxs)(Ht,{storageKey:`loomcycle.explorer.doc-links-height`,className:`doc-content-split`,children:[(0,l.jsx)(`div`,{className:`doc-content-body`,children:b.type===`mermaid`?b.body?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(nt,{code:b.body}),S===`markdown`&&(0,l.jsx)(`pre`,{className:`md-pre doc-mermaid-source`,children:(0,l.jsx)(`code`,{children:b.body})})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty diagram)`}):b.type===`image`||b.asset?O?(0,l.jsxs)(`p`,{className:`doc-empty-body`,children:[`Image failed to load: `,O]}):E?(0,l.jsxs)(`figure`,{className:`doc-image`,children:[(0,l.jsx)(`img`,{src:E,alt:Yt(b)}),b.body&&(0,l.jsx)(`figcaption`,{children:b.body})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Loading image…`}):S===`markdown`?w===null?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Assembling Markdown…`}):(0,l.jsx)(qt,{source:w}):b.body?(0,l.jsx)(qt,{source:b.body}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty chunk)`})}),(0,l.jsxs)(`div`,{className:`doc-links-pane`,children:[(0,l.jsx)(Pt,{edges:pe,incomplete:he,documentId:e,selectedId:v,onSelectChunk:y,onOpenDocument:s?et:void 0,onRuleStatement:Re}),(0,l.jsx)(Mt,{documentId:e,selectedId:v,scope:t,browse:m,onSelectChunk:y,onOpenDocument:s?et:void 0,refreshKey:ve,review:We})]})]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a chunk on the left.`})})})]}),V&&a&&(0,l.jsx)(`div`,{className:`doc-assistant`,children:a({documentId:e,scope:t,subject:i?.subject,onChanged:q})}),M&&(0,l.jsx)(rt,{chunk:M,scope:t,browse:m,onClose:()=>N(null),onSaved:q}),ee&&(0,l.jsx)(it,{chunk:ee,scope:t,browse:m,onClose:()=>te(null),onSaved:q}),P&&b&&(0,l.jsx)(Gt,{chunkId:b.id,chunkTitle:b.title,scope:t,browse:m,onClose:()=>F(!1)}),ue&&X&&(0,l.jsx)(xt,{documentId:e,rootChunkId:X,docType:U?.type,docStatus:U?.status,chunkStatuses:Ae,scope:t,browse:m,onClose:()=>fe(!1),onSaved:q}),ne&&b&&(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:()=>re(!1),children:(0,l.jsxs)(`div`,{className:`modal chunk-delete-confirm`,onClick:e=>e.stopPropagation(),children:[(0,l.jsx)(`h3`,{children:`Delete chunk`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`Delete “`,b.title||`(untitled)`,`” and all of its sub-chunks? This cannot be undone.`]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>re(!1),children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>void pt(),children:`delete`})]})]})})]})}function Zt(e,t=``){let n=e.get(t);if(!n)return[];let r=n.entries.map(n=>{let r=n.kind===`directory`&&n.full_path.startsWith(`${t}/`);return{name:n.name,fullPath:n.full_path,kind:n.kind,resourceRef:n.resource_ref,listing:r?e.get(n.full_path):void 0,children:r?Zt(e,n.full_path):[]}});return r.sort((e,t)=>{let n=e.kind===`directory`;return n===(t.kind===`directory`)?e.name.localeCompare(t.name):n?-1:1}),r}var Qt={directory:`📁`,document:`📄`,volume_mount:`💾`,memory_entry:`🧠`};function $t(e){let{tree:t,root:n}=e;return!n||!n.loaded&&n.loading?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):n.loaded&&t.length===0&&!n.nextCursor?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`This tree is empty. Create a folder or document to begin.`})}):(0,l.jsxs)(`ul`,{className:`tree path-tree`,children:[t.map(t=>(0,l.jsx)(nn,{node:t,...e},t.fullPath)),(0,l.jsx)(en,{dir:``,listing:n,...e})]})}function en({dir:e,listing:t,onLoadMore:n,onRetry:r}){let i=[];return!t||t.loading&&t.entries.length===0?i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`loading…`})},`status`)):t.error?i.push((0,l.jsxs)(`li`,{className:`node path-status`,children:[e!==``&&(0,l.jsxs)(`span`,{className:`path-err`,children:[`failed to load: `,t.error]}),` `,(0,l.jsx)(`button`,{type:`button`,className:`path-more`,onClick:()=>r(e),children:`retry`})]},`status`)):t.loaded&&t.entries.length===0&&e!==``&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`empty`})},`status`)),t?.nextCursor&&!t.error&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`button`,{type:`button`,className:`path-more`,disabled:t.loading,onClick:()=>n(e),children:t.loading?`loading…`:`Load more (${t.entries.length} shown)`})},`more`)),(0,l.jsx)(l.Fragment,{children:i})}function tn(e,t){if(e.kind!==`document`||!t)return;let n=e.resourceRef;return n?.document_id?t.get(n.document_id):void 0}function nn(e){let{node:t,expanded:n,onToggle:r,selectedPath:i,onSelect:a,summaries:o}=e,s=t.kind===`directory`,c=s&&n.has(t.fullPath),u=i===t.fullPath,d=tn(t,o),f=d&&d.color_enabled?Ue(Be(d.type,d.status,ze(d.color_scheme))):void 0;return(0,l.jsxs)(`li`,{className:`node path-node kind-${t.kind} ${u?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row path-row`,style:f,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":c?`collapse`:`expand`,"aria-expanded":s?c:void 0,disabled:!s,onClick:e=>{e.stopPropagation(),s&&r(t.fullPath)},children:s?c?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`path-link`,onClick:()=>a(t),title:t.fullPath,children:[(0,l.jsx)(`span`,{className:`path-kind-icon`,"aria-hidden":!0,children:Qt[t.kind]??`•`}),(0,l.jsx)(`span`,{className:`path-name`,children:t.name}),d?.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:d.type}),d?.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:d.status})]})]}),c&&(0,l.jsxs)(`ul`,{className:`children path-children`,children:[t.children.map(t=>(0,l.jsx)(nn,{...e,node:t},t.fullPath)),(0,l.jsx)(en,{...e,dir:t.fullPath,listing:t.listing})]})]})}var rn=/^[A-Za-z0-9._-]+$/;function an(e,t){return`${e}/${t}`}function on(e,t){for(let n of e){if(n.fullPath===t)return n;let e=on(n.children,t);if(e)return e}}function sn(e){let{theme:t,defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d}=e,f=ae(e);return(0,l.jsx)(oe,{theme:t,dataLayer:f,children:(0,l.jsx)(cn,{defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d})})}function cn({defaultScope:e,path:t,onPathChange:n,browse:r,principal:i,renderAssistant:a,renderNavigator:o,navigator:s,onError:u}){let d=j(),[f,p]=(0,c.useState)(e??`user`),[g,_]=(0,c.useState)(void 0),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(()=>new Set),E=t===void 0?g:t,D=(0,c.useRef)(n);(0,c.useEffect)(()=>{D.current=n},[n]);let O=(0,c.useRef)(u);(0,c.useEffect)(()=>{O.current=u},[u]);let[k,A]=(0,c.useState)([]),M=(0,c.useRef)(0),N=(0,c.useRef)(void 0),P=(0,c.useCallback)(e=>{N.current=e,D.current?.(e),_(e)},[]),F=(0,c.useCallback)(e=>{M.current++,A(e=>e.length>0?[]:e),P(e)},[P]);(0,c.useEffect)(()=>{t!==void 0&&t!==N.current&&(M.current++,A(e=>e.length>0?[]:e))},[t]);let I=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),L=(0,c.useMemo)(()=>new ne(d,f,I),[d,f,I]),R=(0,c.useSyncExternalStore)(L.subscribe,L.getSnapshot),z=(0,c.useCallback)(e=>{O.current?.(e)},[]),[ae,oe]=(0,c.useState)(()=>o?m(globalThis.localStorage):`tree`),V=!!o&&ae===`stars`,U=(0,c.useCallback)(e=>{oe(e),h(globalThis.localStorage,e),e===`tree`&&de(!1)},[]),[ue,de]=(0,c.useState)(!1),[W,he]=(0,c.useState)(0);(0,c.useEffect)(()=>{o&&s&&U(s)},[s]);let[G,ge]=(0,c.useState)(),[_e,ve]=(0,c.useState)(),K=(0,c.useCallback)((e,t)=>(he(e=>e+1),L.invalidate(e,t)),[L]),[ye,be]=(0,c.useState)(()=>new Map),xe=(0,c.useRef)(new Set),Se=(0,c.useRef)(0),Ce=(0,c.useCallback)(()=>{Se.current++,xe.current=new Set,be(new Map)},[]),we=(0,c.useRef)(!0);(0,c.useEffect)(()=>{we.current?we.current=!1:(F(void 0),y(null),T(new Set),Ce()),L.loadDir(``).catch(z)},[L,F,Ce,z]),(0,c.useEffect)(()=>{for(let e of w)R.has(e)||L.loadDir(e).catch(z)},[L,w,R,z]);let q=(0,c.useRef)(null);(0,c.useEffect)(()=>{let e=q.current!==null&&q.current!==L;if(q.current=L,!E||e)return;let t=te(E).filter(e=>e!==``);T(e=>{if(t.every(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.add(e)),n}),L.reveal(E).catch(z)},[L,E,z]),(0,c.useEffect)(()=>{let e=[];for(let t of R.values())for(let n of ie(t.entries))xe.current.has(n)||(xe.current.add(n),e.push(n));let t=Se.current;for(let n=0;n<e.length;n+=500)d.documentsSummary({documentIds:e.slice(n,n+500)},f,I).then(e=>{Se.current===t&&be(t=>{let n=new Map(t);for(let t of e.documents??[])n.set(t.document_id,t);return n})}).catch(()=>{})},[d,R,f,I]);let Te=(0,c.useMemo)(()=>Zt(R),[R]),Ee=(0,c.useCallback)(async()=>{y(null),Ce(),he(e=>e+1),await L.refresh(w).catch(z),E&&await L.reveal(E).catch(z)},[L,w,E,Ce,z]),De=(0,c.useCallback)(e=>{T(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Oe=(0,c.useCallback)(e=>L.loadMore(e).catch(z),[L,z]),J=(0,c.useCallback)(e=>{(L.getSnapshot().get(e)?.loaded?L.loadMore(e):L.loadDir(e)).catch(z)},[L,z]),Y=(0,c.useMemo)(()=>E?on(Te,E):void 0,[Te,E]),X=R.get(``)?.error,ke=Y?.kind===`directory`?Y.fullPath:void 0,[Ae,je]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!ke||!d.pathIsStored)return;let e=!1;return d.pathIsStored(ke,f,I).then(t=>{e||je({path:ke,explicit:t})},()=>{}),()=>{e=!0}},[d,ke,f,I]);let Me=Y?Y.kind===`directory`?Ae?.path===Y.fullPath?Ae.explicit?`yes`:`implicit (no entry)`:void 0:`yes`:void 0,Z=(0,c.useMemo)(()=>Y?Y.kind===`directory`?Y.fullPath:ee(Y.fullPath):``,[Y]),Ne=Z||`/`,Pe=(0,c.useCallback)(()=>{x({title:`New folder in ${Ne}`,fields:[{key:`name`,label:`Folder name`,placeholder:`e.g. launches`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!rn.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=an(Z,t);await d.pathMkdir(n,f,I),await K(n).catch(z),F(n)}})},[d,L,Z,Ne,f,I,z,F]),Fe=(0,c.useCallback)(()=>{x({title:`New document in ${Ne}`,fields:[{key:`name`,label:`Path name`,placeholder:`e.g. launch-plan`},{key:`title`,label:`Title`,placeholder:`e.g. Launch Plan`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!rn.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=e.title.trim()||t,r=an(Z,t);await d.documentCreate(n,r,f,I),await K(r).catch(z),F(r)}})},[d,L,Z,Ne,f,I,z,F]),Ie=(0,c.useCallback)(()=>{Y&&x({title:`Rename / move ${Y.fullPath}`,fields:[{key:`to`,label:`New path`,value:Y.fullPath}],submitLabel:`Move`,onSubmit:async e=>{let t=e.to.trim();if(!t.startsWith(`/`))throw Error(`path must start with /`);await d.pathMv(Y.fullPath,t,f,I),await Promise.all([K(Y.fullPath,{dropSubtree:!0}),K(t)]).catch(z),F(t)}})},[d,L,Y,f,I,z,F]),Le=(0,c.useCallback)(()=>{if(!Y)return;if(Y.kind===`document`){let e=Y.resourceRef?.document_id;x({title:`Delete document ${Y.fullPath}`,message:`This deletes the document, all its chunks, and its path entry. This cannot be undone.`,fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{if(!e)throw Error(`this document dirent has no document_id`);await d.documentDelete(e,f,I),await K(Y.fullPath).catch(z),F(void 0)}});return}let e=Y;y(null),(async()=>{let t;try{t=await re(d,e.fullPath,f,I)}catch(t){y(`could not list ${e.fullPath} for delete: ${t instanceof Error?t.message:String(t)}`);return}let n=ie(t);x({title:`Delete branch ${e.fullPath}`,message:t.length===0?`This removes the (empty) folder.`:`This removes the folder and everything under it`+(n.length>0?` — including ${n.length} document(s), whose chunks are deleted.`:`.`),fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{for(let e of n)await d.documentDelete(e,f,I);await d.pathRm(e.fullPath,f,!0,I),await K(e.fullPath,{dropSubtree:!0}).catch(z),F(void 0)}})})()},[d,L,Y,f,I,z,F]),Q=Y&&(Y.kind===`directory`||Y.kind===`document`),Re=!!d.documentsTransfer&&!!Q,ze=(0,c.useCallback)(()=>{if(Y){if(Y.kind===`document`){let e=Y.resourceRef?.document_id;if(!e){y(`this document entry has no document_id`);return}C({documentId:e,fromPath:Y.fullPath})}else C({underPath:Y.fullPath,fromPath:Y.fullPath})}},[Y]),Be=(0,c.useCallback)(e=>{e.op===`move`?(K(e.from,{dropSubtree:!0}).catch(z),A([]),F(void 0)):e.toScope===f&&K(e.to).catch(z)},[K,z,f,F]),$=(0,c.useMemo)(()=>{if(k.length>0)return k[k.length-1];if(Y?.kind===`document`)return{documentId:Y.resourceRef?.document_id??``,path:Y.fullPath,title:Y.name}},[k,Y]),Ve=(0,c.useCallback)((e,t)=>{let n=++M.current,r=le(L.getSnapshot(),e.documentId);A(se(k,{...t,path:$?.path},{...e,path:r})),P(r),!r&&d.documentPath&&d.documentPath(e.documentId,f,I).then(t=>{t&&M.current===n&&(A(n=>ce(n,e.documentId,{path:t})),P(t))},()=>{})},[d,L,k,$?.path,f,I,P]),He=(0,c.useCallback)(e=>{let t=B(k,e);t!==k&&(M.current++,A(t),P(t[t.length-1].path))},[k,P]),Ue=(0,c.useCallback)((e,t)=>A(n=>ce(n,e,{title:t})),[]),We=(0,c.useCallback)(e=>{ve(t=>({documentId:e.documentId,chunkId:e.chunkId,seq:(t?.seq??0)+1})),$?.documentId!==e.documentId&&(e.path?F(e.path):(M.current++,A([{documentId:e.documentId,chunkId:e.chunkId}]),P(void 0)))},[$?.documentId,F,P]),Ge=(0,c.useMemo)(()=>({scope:f,browse:I,selection:{documentId:$?.documentId,chunkId:G&&G.documentId===$?.documentId?G.chunkId:void 0,path:$?.path},onSelect:We,reloadToken:W,maximized:ue,onToggleMaximize:()=>de(e=>!e),subject:i?.subject}),[f,I,$?.documentId,$?.path,G,We,W,ue,i?.subject]),Ke=_e&&$&&_e.documentId===$.documentId?_e:void 0,qe=!!$?.path&&Y?.kind===`document`&&Y.fullPath===$.path;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(me,{className:V?`paths-view paths-view--stars`:`paths-view`,defaultLeftWidth:V?720:420,minLeftWidth:280,minRightWidth:300,storageKey:V?`loomcycle.explorer.split.stars`:`loomcycle.explorer.split.paths`,hideRight:V&&ue,children:[(0,l.jsxs)(`div`,{className:`left`,children:[(0,l.jsxs)(`div`,{className:`paths-toolbar`,children:[(0,l.jsxs)(`label`,{className:`paths-scope`,children:[(0,l.jsx)(`span`,{children:`scope`}),(0,l.jsxs)(`select`,{value:f,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),o&&(0,l.jsxs)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Navigator`,children:[(0,l.jsx)(`button`,{type:`button`,"aria-pressed":!V,className:V?void 0:`active`,onClick:()=>U(`tree`),title:`Browse the Path tree`,children:`tree`}),(0,l.jsx)(`button`,{type:`button`,"aria-pressed":V,className:V?`active`:void 0,onClick:()=>U(`stars`),title:`Browse the scope as a 3D star map`,children:`stars`})]}),(0,l.jsxs)(`div`,{className:`paths-toolbar-actions`,children:[!V&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:Pe,title:`New folder in ${Ne}`,children:`+ folder`}),(0,l.jsx)(`button`,{type:`button`,onClick:Fe,title:`New document in ${Ne}`,children:`+ document`})]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void Ee(),title:`Reload the tree`,children:`↻`})]})]}),!V&&(0,l.jsxs)(`p`,{className:`paths-context`,children:[`new items → `,(0,l.jsx)(`code`,{children:Ne}),I?.scopeId&&(0,l.jsxs)(l.Fragment,{children:[` · `,`subject `,(0,l.jsx)(`code`,{children:I.scopeId})]}),I?.tenant&&(0,l.jsxs)(l.Fragment,{children:[` · `,`tenant `,(0,l.jsx)(`code`,{children:I.tenant})]})]}),(v||X)&&(0,l.jsx)(`div`,{className:`paths-err`,children:v||X}),V&&o?(0,l.jsx)(`div`,{className:`paths-navigator`,children:o(Ge)}):(0,l.jsx)($t,{tree:Te,root:R.get(``),expanded:w,onToggle:De,onLoadMore:Oe,onRetry:J,selectedPath:E,onSelect:e=>F(e.fullPath),summaries:ye})]}),(0,l.jsx)(`div`,{className:`right`,children:$?(0,l.jsxs)(`div`,{className:`paths-doc`,children:[(0,l.jsx)(fe,{trail:k,onJump:He}),(0,l.jsxs)(`div`,{className:`paths-doc-head`,children:[$.path?(0,l.jsx)(`code`,{className:`paths-doc-path`,children:$.path}):(0,l.jsxs)(`span`,{className:`paths-doc-path paths-doc-unfiled`,title:`Opened by id — no entry for this document was found in the Path tree`,children:[H($),` `,(0,l.jsx)(`em`,{children:`· opened by id, not in the tree`})]}),qe&&(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Ie,children:`rename / move`}),Re&&(0,l.jsx)(`button`,{type:`button`,onClick:ze,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Le,children:`delete`})]})]}),(0,l.jsx)(Xt,{documentId:$.documentId,scope:f,titleHint:$.title,browse:I,principal:i,renderAssistant:a,initialChunkId:$.chunkId??Ke?.chunkId,onOpenDocument:Ve,onTitle:Ue,onChunkSelect:e=>ge({documentId:$.documentId,chunkId:e}),focusChunk:Ke},k.length)]}):Y?(0,l.jsxs)(`div`,{className:`paths-detail`,children:[(0,l.jsxs)(`h2`,{children:[(0,l.jsx)(`span`,{className:`paths-detail-kind`,children:Y.kind}),(0,l.jsx)(`code`,{children:Y.fullPath})]}),(0,l.jsxs)(`dl`,{className:`paths-detail-meta`,children:[(0,l.jsx)(`dt`,{children:`scope`}),(0,l.jsx)(`dd`,{children:f}),Me&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`stored`}),(0,l.jsx)(`dd`,{children:Me})]})]}),Q?(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Ie,children:`rename / move`}),Re&&(0,l.jsx)(`button`,{type:`button`,onClick:ze,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Le,children:`delete`})]}):(0,l.jsxs)(`p`,{className:`paths-readonly`,children:[`Read-only — `,Y.kind,` entries are managed by their own tool.`]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a path on the left, or create a folder / document.`})})})]}),b&&(0,l.jsx)(ln,{state:b,onClose:()=>x(null)}),S&&(0,l.jsx)(pe,{data:d,scope:f,browse:I,documentId:S.documentId,underPath:S.underPath,fromPath:S.fromPath,onClose:()=>C(null),onDone:Be})]})}function ln({state:e,onClose:t}){let[n,r]=(0,c.useState)(()=>Object.fromEntries(e.fields.map(e=>[e.key,e.value??``]))),[i,a]=(0,c.useState)(!1),[o,s]=(0,c.useState)(null);return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:t,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async r=>{r.preventDefault(),a(!0),s(null);try{await e.onSubmit(n),t()}catch(e){s(e instanceof Error?e.message:String(e)),a(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:e.title}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:t,disabled:i,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:e.danger?`danger`:`primary`,disabled:i,children:i?`working…`:e.submitLabel})]})]}),e.message&&(0,l.jsx)(`p`,{className:`modal-context`,children:e.message}),e.fields.map((e,t)=>(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:e.label}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:n[e.key],placeholder:e.placeholder,autoFocus:t===0,onChange:t=>r(n=>({...n,[e.key]:t.target.value}))})]},e.key)),o&&(0,l.jsx)(`div`,{className:`modal-err`,children:o})]})})}function un(e){let{documentId:t,scope:n,browse:r,theme:i}=e,a=ae(e);return(0,l.jsx)(oe,{theme:i,dataLayer:a,children:(0,l.jsx)(dn,{...e},`${n}:${t}:${r?.scopeId??``}:${r?.tenant??``}`)})}function dn({documentId:e,chunkId:t,scope:n,titleHint:r,browse:i,principal:a,renderAssistant:o,onOpenDocument:s}){let[u,d]=(0,c.useState)([]),f=u[u.length-1],[p,m]=(0,c.useState)(),h=(0,c.useRef)(t);(0,c.useEffect)(()=>{t!==h.current&&(h.current=t,u.length>0?(m(void 0),d([])):m(e=>({chunkId:t,seq:(e?.seq??0)+1})))},[t]);let g=(0,c.useCallback)((e,t)=>{s?s(e,t):d(n=>se(n,t,e))},[s]),_=(0,c.useCallback)(e=>d(t=>B(t,e)),[]),v=(0,c.useCallback)((e,t)=>d(n=>ce(n,e,{title:t})),[]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(fe,{trail:u,onJump:_}),(0,l.jsx)(Xt,{documentId:f?.documentId??e,scope:n,titleHint:f?f.title:r,browse:i,principal:a,renderAssistant:o,initialChunkId:f?f.chunkId:t,focusChunk:f?void 0:p,onOpenDocument:g,onTitle:v},u.length)]})}exports.DEFAULT_SCHEME=Q,exports.DocumentViewer=un,exports.EDGE_PAGE_CAP=ve,exports.PathExplorer=sn,exports.QUEUE_CHANGED_RETRIES=Y,exports.RULING_CHUNK=J,exports.RequestError=R,exports.assetFetchFromConnection=L,exports.chunkColor=$,exports.chunkCount=Me,exports.chunkInheritsDocColor=Ve,exports.chunkRowStyle=Ge,exports.createLoomcycleClient=I,exports.dataLayerFromClient=D,exports.docColor=Be,exports.effectiveScheme=ze,exports.hexToTint=He,exports.isQueueChanged=ke,exports.jsonPostFromConnection=z,exports.loadDocumentEdges=K,exports.runRuling=Ae,exports.tintStyle=Ue,exports.transferInput=y,exports.undoRulings=je,exports.washStyle=We;
|
|
15
|
+
`);T(t)}).catch(e=>!n&&I(e instanceof Error?e.message:String(e))),()=>{n=!0}},[p,S,v,Oe,t,ce,m]);let $e=(0,c.useCallback)(e=>y(e.row.id),[]),et=(0,c.useCallback)((t,n,r)=>s?.({documentId:t,chunkId:n,title:r},{documentId:e,chunkId:v,title:ke}),[s,e,v,ke]),tt=(0,c.useCallback)(async()=>{try{let n=await p.documentExportMd(e,t,!0,m),r=new Blob([n.markdown],{type:`text/markdown`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=(n.title||`document`).replace(/[^\w.-]+/g,`_`)+`.md`,a.click(),URL.revokeObjectURL(i)}catch(e){I(e instanceof Error?e.message:String(e))}},[p,e,t,m]),nt=(0,c.useCallback)(async()=>{try{let n=await p.documentExportCanvas(e,t,m),r=new Blob([JSON.stringify(n.canvas,null,2)],{type:`application/json`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=(ke||`document`).replace(/[^\w.-]+/g,`_`)+`.canvas`,a.click(),URL.revokeObjectURL(i)}catch(e){I(e instanceof Error?e.message:String(e))}},[p,e,t,m,ke]),ot=!!p.documentCreateChunk&&!!Y,st=(0,c.useCallback)(async n=>{if(!p.documentCreateChunk||!p.documentSetAsset)return;let r=v||Y;if(r){I(null);try{let{mediaType:i,data:a}=await ve(n),o=await p.documentCreateChunk(e,r,{title:n.name||`image`,type:`image`},t,m);await p.documentSetAsset(o.id,i,a,n.name,t,m),K(),y(o.id)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Y,K]),ct=(0,c.useCallback)(async()=>{if(!p.documentCreateChunk)return;let n=v||Y;if(n){I(null);try{let r=await p.documentCreateChunk(e,n,{title:`Diagram`,type:`mermaid`,body:`graph TD
|
|
16
|
+
A[Start] --> B[End]`},t,m);K(),y(r.id),N(r)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,Y,K]),lt=(0,c.useCallback)(async()=>{if(!p.documentCreateChunk)return;let n=v&&!q?v:void 0,r=v||Y;if(r){I(null);try{let i=await p.documentCreateChunk(e,n?``:r,{title:`Text`,body:``},t,m,n);K(),y(i.id),N(i)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,q,Y,K]),ut=(0,c.useCallback)(async()=>{if(p.documentCreateChunk&&v){I(null);try{let n=await p.documentCreateChunk(e,v,{title:`Text`,body:``},t,m);K(),y(n.id),N(n)}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,e,t,m,v,K]),dt=(0,c.useMemo)(()=>{if(!b||q)return{canUp:!1,canDown:!1};let e=b.parent_id??``,t=h.filter(t=>(t.parent_id??``)===e).sort((e,t)=>e.position-t.position||e.id.localeCompare(t.id)),n=t.findIndex(e=>e.id===b.id);return{canUp:n>0,canDown:n>=0&&n<t.length-1}},[h,b,q]),ft=(0,c.useCallback)(async e=>{if(p.documentReorderChunk&&v){I(null);try{await p.documentReorderChunk(v,e,t,m),K()}catch(e){I(e instanceof Error?e.message:String(e))}}},[p,v,t,m,K]),pt=(0,c.useCallback)(async()=>{if(!p.documentDeleteChunk||!b)return;I(null);let e=b.parent_id;try{await p.documentDeleteChunk(b.id,t,m),re(!1),y(e||Y),K()}catch(e){I(e instanceof Error?e.message:String(e)),re(!1)}},[p,b,t,m,Y,K]);return(0,c.useEffect)(()=>{if(!ot)return;let e=e=>{if(M||fe)return;let t=document.activeElement,n=t?.tagName;if(n===`INPUT`||n===`TEXTAREA`||t?.isContentEditable)return;let r=ye(e.clipboardData?.items);r&&(e.preventDefault(),st(r))};return window.addEventListener(`paste`,e),()=>window.removeEventListener(`paste`,e)},[ot,M,fe,st]),(0,l.jsxs)(`div`,{className:`doc-viewer`,children:[(0,l.jsx)(`input`,{ref:A,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&st(t)}}),(0,l.jsxs)(`div`,{className:`doc-toolbar`,style:Le,children:[(0,l.jsx)(`strong`,{className:`doc-title`,title:ke,children:ke}),(0,l.jsx)(Je,{value:e,label:`doc`}),(0,l.jsxs)(`div`,{className:`doc-toolbar-actions`,children:[ot&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void lt(),title:`Add a text chunk AFTER the selected chunk, at the same level`,children:`+ text`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ut(),disabled:!v,title:v?`Add a chunk NESTED UNDER the selected chunk (in the ontology, a child is a subclass)`:`Select a chunk first — this nests a new chunk under it`,children:`+ child`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>A.current?.click(),title:`Add an image chunk (upload — or paste a screenshot into the view)`,children:`+ image`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ct(),title:`Add a Mermaid diagram chunk`,children:`+ diagram`})]}),(0,l.jsx)(`button`,{type:`button`,className:Me?`active`:``,onClick:()=>me(!0),disabled:!Y,title:`Colors — tint chunk tiles + the Path tree by type/status`,children:`colors`}),p.documentClassify&&(0,l.jsx)(`button`,{type:`button`,className:Ce>0?`active`:``,onClick:()=>we(e=>e>0?0:1),title:`Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)`,children:`classify`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void tt(),title:`Download the whole document as Markdown (.md)`,children:`↓ .md`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void nt(),title:`Download the whole document as a node/edge canvas graph (.canvas)`,children:`↓ .canvas`}),a&&(0,l.jsx)(`button`,{type:`button`,className:B?`active`:``,onClick:()=>ue(e=>!e),title:`Document Assistant — instruct an agent to restructure/import/link chunks`,children:`assistant`}),(0,l.jsx)(`button`,{type:`button`,onClick:K,title:`Reload`,children:`↻`})]})]}),ie&&(0,l.jsx)(`div`,{className:`paths-err`,children:ie}),!Re&&(0,l.jsx)(yt,{documentId:e,scope:t,browse:m,rootFields:Te,requestKey:Ce,onClose:()=>we(0),onChanged:K},`${t}:${e}`),Re?(0,l.jsx)(Wt,{documentId:e,scope:t,detail:oe??void 0}):(0,l.jsxs)(ge,{className:`doc-split`,defaultLeftWidth:320,minLeftWidth:160,minRightWidth:320,storageKey:`loomcycle.explorer.split.doc`,children:[(0,l.jsx)(`div`,{className:`doc-chunktree`,children:L&&h.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):(0,l.jsx)(Qe,{tree:Oe,selectedId:v,onSelect:$e,colorEnabled:Me,scheme:V?.color_scheme,documentColor:X,linkedIds:Ne})}),(0,l.jsx)(`div`,{className:`doc-content`,children:b?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-content-head`,children:[J.length>0&&(0,l.jsxs)(`nav`,{className:`chunk-ancestry`,"aria-label":`Chunks above this one`,children:[(0,l.jsx)(`button`,{type:`button`,className:`chunk-ancestry-up`,onClick:()=>y(J[J.length-1].id),title:`Up to ${J[J.length-1].title||`(untitled)`}`,children:`↰ Up`}),(0,l.jsxs)(`ol`,{className:`doc-trail-list`,children:[J.map(e=>(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>y(e.id),title:e.title||`(untitled)`,children:e.title||`(untitled)`})},e.id)),(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`location`,title:b.title||`(untitled)`,children:b.title||`(untitled)`})})]})]}),(0,l.jsx)(`h3`,{children:b.title||`(untitled)`}),(0,l.jsxs)(`div`,{className:`doc-content-meta`,children:[b.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:b.type}),b.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:b.status}),(0,l.jsxs)(`span`,{className:`chunk-rev`,children:[`rev `,b.revision]}),b.tags?.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e)),(0,l.jsx)(Je,{value:b.id,label:`chunk`})]}),(0,l.jsxs)(`div`,{className:`doc-content-controls`,children:[(0,l.jsxs)(`div`,{className:`doc-mode-toggle`,children:[(0,l.jsx)(`button`,{type:`button`,className:S===`chunks`?`active`:``,onClick:()=>C(`chunks`),title:`This chunk's own content`,children:`chunk`}),(0,l.jsx)(`button`,{type:`button`,className:S===`markdown`?`active`:``,onClick:()=>C(`markdown`),title:q?`Whole document as Markdown`:`This chunk + its sub-chunks as Markdown`,children:`markdown`})]}),(0,l.jsx)(`button`,{type:`button`,className:`chunk-edit`,onClick:()=>N(b),children:`edit`}),p.documentEntityTypes&&g(b)&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>te(b),title:`Change this subject's type to another type in force`,children:`change type`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>F(!0),title:`View this chunk's edit history + diffs`,children:`history`}),!q&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ft(`up`),disabled:!dt.canUp,title:`Move this chunk up within its level`,children:`↑`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void ft(`down`),disabled:!dt.canDown,title:`Move this chunk down within its level`,children:`↓`})]}),!q&&(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>re(!0),title:`Delete this chunk and its sub-chunks`,children:`delete`})]})]}),(0,l.jsxs)(Ut,{storageKey:`loomcycle.explorer.doc-links-height`,className:`doc-content-split`,children:[(0,l.jsx)(`div`,{className:`doc-content-body`,children:b.type===`mermaid`?b.body?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(rt,{code:b.body}),S===`markdown`&&(0,l.jsx)(`pre`,{className:`md-pre doc-mermaid-source`,children:(0,l.jsx)(`code`,{children:b.body})})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty diagram)`}):b.type===`image`||b.asset?O?(0,l.jsxs)(`p`,{className:`doc-empty-body`,children:[`Image failed to load: `,O]}):E?(0,l.jsxs)(`figure`,{className:`doc-image`,children:[(0,l.jsx)(`img`,{src:E,alt:Xt(b)}),b.body&&(0,l.jsx)(`figcaption`,{children:b.body})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Loading image…`}):S===`markdown`?w===null?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Assembling Markdown…`}):(0,l.jsx)(Jt,{source:w}):b.body?(0,l.jsx)(Jt,{source:b.body}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty chunk)`})}),(0,l.jsxs)(`div`,{className:`doc-links-pane`,children:[(0,l.jsx)(Ft,{edges:he,incomplete:_e,documentId:e,selectedId:v,onSelectChunk:y,onOpenDocument:s?et:void 0,onRuleStatement:ze}),(0,l.jsx)(Nt,{documentId:e,selectedId:v,scope:t,browse:m,onSelectChunk:y,onOpenDocument:s?et:void 0,refreshKey:be,review:We})]})]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a chunk on the left.`})})})]}),B&&a&&(0,l.jsx)(`div`,{className:`doc-assistant`,children:a({documentId:e,scope:t,subject:i?.subject,onChanged:K})}),M&&(0,l.jsx)(it,{chunk:M,scope:t,browse:m,onClose:()=>N(null),onSaved:K}),ee&&(0,l.jsx)(at,{chunk:ee,scope:t,browse:m,onClose:()=>te(null),onSaved:K}),P&&b&&(0,l.jsx)(Kt,{chunkId:b.id,chunkTitle:b.title,scope:t,browse:m,onClose:()=>F(!1)}),fe&&Y&&(0,l.jsx)(St,{documentId:e,rootChunkId:Y,docType:V?.type,docStatus:V?.status,chunkStatuses:je,scope:t,browse:m,onClose:()=>me(!1),onSaved:K}),ne&&b&&(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:()=>re(!1),children:(0,l.jsxs)(`div`,{className:`modal chunk-delete-confirm`,onClick:e=>e.stopPropagation(),children:[(0,l.jsx)(`h3`,{children:`Delete chunk`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`Delete “`,b.title||`(untitled)`,`” and all of its sub-chunks? This cannot be undone.`]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>re(!1),children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>void pt(),children:`delete`})]})]})})]})}function Qt(e,t=``){let n=e.get(t);if(!n)return[];let r=n.entries.map(n=>{let r=n.kind===`directory`&&n.full_path.startsWith(`${t}/`);return{name:n.name,fullPath:n.full_path,kind:n.kind,resourceRef:n.resource_ref,listing:r?e.get(n.full_path):void 0,children:r?Qt(e,n.full_path):[]}});return r.sort((e,t)=>{let n=e.kind===`directory`;return n===(t.kind===`directory`)?e.name.localeCompare(t.name):n?-1:1}),r}var $t={directory:`📁`,document:`📄`,volume_mount:`💾`,memory_entry:`🧠`};function en(e){let{tree:t,root:n}=e;return!n||!n.loaded&&n.loading?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):n.loaded&&t.length===0&&!n.nextCursor?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`This tree is empty. Create a folder or document to begin.`})}):(0,l.jsxs)(`ul`,{className:`tree path-tree`,children:[t.map(t=>(0,l.jsx)(rn,{node:t,...e},t.fullPath)),(0,l.jsx)(tn,{dir:``,listing:n,...e})]})}function tn({dir:e,listing:t,onLoadMore:n,onRetry:r}){let i=[];return!t||t.loading&&t.entries.length===0?i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`loading…`})},`status`)):t.error?i.push((0,l.jsxs)(`li`,{className:`node path-status`,children:[e!==``&&(0,l.jsxs)(`span`,{className:`path-err`,children:[`failed to load: `,t.error]}),` `,(0,l.jsx)(`button`,{type:`button`,className:`path-more`,onClick:()=>r(e),children:`retry`})]},`status`)):t.loaded&&t.entries.length===0&&e!==``&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`empty`})},`status`)),t?.nextCursor&&!t.error&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`button`,{type:`button`,className:`path-more`,disabled:t.loading,onClick:()=>n(e),children:t.loading?`loading…`:`Load more (${t.entries.length} shown)`})},`more`)),(0,l.jsx)(l.Fragment,{children:i})}function nn(e,t){if(e.kind!==`document`||!t)return;let n=e.resourceRef;return n?.document_id?t.get(n.document_id):void 0}function rn(e){let{node:t,expanded:n,onToggle:r,selectedPath:i,onSelect:a,summaries:o}=e,s=t.kind===`directory`,c=s&&n.has(t.fullPath),u=i===t.fullPath,d=nn(t,o),f=d&&d.color_enabled?$(Q(d.type,d.status,Be(d.color_scheme))):void 0;return(0,l.jsxs)(`li`,{className:`node path-node kind-${t.kind} ${u?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row path-row`,style:f,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":c?`collapse`:`expand`,"aria-expanded":s?c:void 0,disabled:!s,onClick:e=>{e.stopPropagation(),s&&r(t.fullPath)},children:s?c?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`path-link`,onClick:()=>a(t),title:t.fullPath,children:[(0,l.jsx)(`span`,{className:`path-kind-icon`,"aria-hidden":!0,children:$t[t.kind]??`•`}),(0,l.jsx)(`span`,{className:`path-name`,children:t.name}),d?.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:d.type}),d?.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:d.status})]})]}),c&&(0,l.jsxs)(`ul`,{className:`children path-children`,children:[t.children.map(t=>(0,l.jsx)(rn,{...e,node:t},t.fullPath)),(0,l.jsx)(tn,{...e,dir:t.fullPath,listing:t.listing})]})]})}var an=/^[A-Za-z0-9._-]+$/;function on(e,t){return`${e}/${t}`}function sn(e,t){for(let n of e){if(n.fullPath===t)return n;let e=sn(n.children,t);if(e)return e}}function cn(e){let{theme:t,defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d}=e,f=ae(e);return(0,l.jsx)(oe,{theme:t,dataLayer:f,children:(0,l.jsx)(ln,{defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d})})}function ln({defaultScope:e,path:t,onPathChange:n,browse:r,principal:i,renderAssistant:a,renderNavigator:o,navigator:s,onError:u}){let d=j(),[f,p]=(0,c.useState)(e??`user`),[g,_]=(0,c.useState)(void 0),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(()=>new Set),E=t===void 0?g:t,D=(0,c.useRef)(n);(0,c.useEffect)(()=>{D.current=n},[n]);let O=(0,c.useRef)(u);(0,c.useEffect)(()=>{O.current=u},[u]);let[k,A]=(0,c.useState)([]),M=(0,c.useRef)(0),N=(0,c.useRef)(void 0),P=(0,c.useCallback)(e=>{N.current=e,D.current?.(e),_(e)},[]),F=(0,c.useCallback)(e=>{M.current++,A(e=>e.length>0?[]:e),P(e)},[P]);(0,c.useEffect)(()=>{t!==void 0&&t!==N.current&&(M.current++,A(e=>e.length>0?[]:e))},[t]);let I=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),L=(0,c.useMemo)(()=>new ne(d,f,I),[d,f,I]),R=(0,c.useSyncExternalStore)(L.subscribe,L.getSnapshot),z=(0,c.useCallback)(e=>{O.current?.(e)},[]),[ae,oe]=(0,c.useState)(()=>o?m(globalThis.localStorage):`tree`),B=!!o&&ae===`stars`,V=(0,c.useCallback)(e=>{oe(e),h(globalThis.localStorage,e),e===`tree`&&pe(!1)},[]),[fe,pe]=(0,c.useState)(!1),[H,_e]=(0,c.useState)(0);(0,c.useEffect)(()=>{o&&s&&V(s)},[s]);let[U,ve]=(0,c.useState)(),[ye,be]=(0,c.useState)(),W=(0,c.useCallback)((e,t)=>(_e(e=>e+1),L.invalidate(e,t)),[L]),[xe,Se]=(0,c.useState)(()=>new Map),Ce=(0,c.useRef)(new Set),we=(0,c.useRef)(0),Te=(0,c.useCallback)(()=>{we.current++,Ce.current=new Set,Se(new Map)},[]),G=(0,c.useRef)(!0);(0,c.useEffect)(()=>{G.current?G.current=!1:(F(void 0),y(null),T(new Set),Te()),L.loadDir(``).catch(z)},[L,F,Te,z]),(0,c.useEffect)(()=>{for(let e of w)R.has(e)||L.loadDir(e).catch(z)},[L,w,R,z]);let K=(0,c.useRef)(null);(0,c.useEffect)(()=>{let e=K.current!==null&&K.current!==L;if(K.current=L,!E||e)return;let t=te(E).filter(e=>e!==``);T(e=>{if(t.every(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.add(e)),n}),L.reveal(E).catch(z)},[L,E,z]),(0,c.useEffect)(()=>{let e=[];for(let t of R.values())for(let n of ie(t.entries))Ce.current.has(n)||(Ce.current.add(n),e.push(n));let t=we.current;for(let n=0;n<e.length;n+=500)d.documentsSummary({documentIds:e.slice(n,n+500)},f,I).then(e=>{we.current===t&&Se(t=>{let n=new Map(t);for(let t of e.documents??[])n.set(t.document_id,t);return n})}).catch(()=>{})},[d,R,f,I]);let Ee=(0,c.useMemo)(()=>Qt(R),[R]),De=(0,c.useCallback)(async()=>{y(null),Te(),_e(e=>e+1),await L.refresh(w).catch(z),E&&await L.reveal(E).catch(z)},[L,w,E,Te,z]),Oe=(0,c.useCallback)(e=>{T(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ke=(0,c.useCallback)(e=>L.loadMore(e).catch(z),[L,z]),q=(0,c.useCallback)(e=>{(L.getSnapshot().get(e)?.loaded?L.loadMore(e):L.loadDir(e)).catch(z)},[L,z]),J=(0,c.useMemo)(()=>E?sn(Ee,E):void 0,[Ee,E]),Y=R.get(``)?.error,Ae=J?.kind===`directory`?J.fullPath:void 0,[je,Me]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!Ae||!d.pathIsStored)return;let e=!1;return d.pathIsStored(Ae,f,I).then(t=>{e||Me({path:Ae,explicit:t})},()=>{}),()=>{e=!0}},[d,Ae,f,I]);let Ne=J?J.kind===`directory`?je?.path===J.fullPath?je.explicit?`yes`:`implicit (no entry)`:void 0:`yes`:void 0,X=(0,c.useMemo)(()=>J?J.kind===`directory`?J.fullPath:ee(J.fullPath):``,[J]),Pe=X||`/`,Fe=(0,c.useCallback)(()=>{x({title:`New folder in ${Pe}`,fields:[{key:`name`,label:`Folder name`,placeholder:`e.g. launches`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!an.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=on(X,t);await d.pathMkdir(n,f,I),await W(n).catch(z),F(n)}})},[d,L,X,Pe,f,I,z,F]),Ie=(0,c.useCallback)(()=>{x({title:`New document in ${Pe}`,fields:[{key:`name`,label:`Path name`,placeholder:`e.g. launch-plan`},{key:`title`,label:`Title`,placeholder:`e.g. Launch Plan`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!an.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=e.title.trim()||t,r=on(X,t);await d.documentCreate(n,r,f,I),await W(r).catch(z),F(r)}})},[d,L,X,Pe,f,I,z,F]),Le=(0,c.useCallback)(()=>{J&&x({title:`Rename / move ${J.fullPath}`,fields:[{key:`to`,label:`New path`,value:J.fullPath}],submitLabel:`Move`,onSubmit:async e=>{let t=e.to.trim();if(!t.startsWith(`/`))throw Error(`path must start with /`);await d.pathMv(J.fullPath,t,f,I),await Promise.all([W(J.fullPath,{dropSubtree:!0}),W(t)]).catch(z),F(t)}})},[d,L,J,f,I,z,F]),Re=(0,c.useCallback)(()=>{if(!J)return;if(J.kind===`document`){let e=J.resourceRef?.document_id;x({title:`Delete document ${J.fullPath}`,message:`This deletes the document, all its chunks, and its path entry. This cannot be undone.`,fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{if(!e)throw Error(`this document dirent has no document_id`);await d.documentDelete(e,f,I),await W(J.fullPath).catch(z),F(void 0)}});return}let e=J;y(null),(async()=>{let t;try{t=await re(d,e.fullPath,f,I)}catch(t){y(`could not list ${e.fullPath} for delete: ${t instanceof Error?t.message:String(t)}`);return}let n=ie(t);x({title:`Delete branch ${e.fullPath}`,message:t.length===0?`This removes the (empty) folder.`:`This removes the folder and everything under it`+(n.length>0?` — including ${n.length} document(s), whose chunks are deleted.`:`.`),fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{for(let e of n)await d.documentDelete(e,f,I);await d.pathRm(e.fullPath,f,!0,I),await W(e.fullPath,{dropSubtree:!0}).catch(z),F(void 0)}})})()},[d,L,J,f,I,z,F]),Z=J&&(J.kind===`directory`||J.kind===`document`),ze=!!d.documentsTransfer&&!!Z,Be=(0,c.useCallback)(()=>{if(J){if(J.kind===`document`){let e=J.resourceRef?.document_id;if(!e){y(`this document entry has no document_id`);return}C({documentId:e,fromPath:J.fullPath})}else C({underPath:J.fullPath,fromPath:J.fullPath})}},[J]),Ve=(0,c.useCallback)(e=>{e.op===`move`?(W(e.from,{dropSubtree:!0}).catch(z),A([]),F(void 0)):e.toScope===f&&W(e.to).catch(z)},[W,z,f,F]),Q=(0,c.useMemo)(()=>{if(k.length>0)return k[k.length-1];if(J?.kind===`document`)return{documentId:J.resourceRef?.document_id??``,path:J.fullPath,title:J.name}},[k,J]),He=(0,c.useCallback)((e,t)=>{let n=++M.current,r=de(L.getSnapshot(),e.documentId);A(se(k,{...t,path:Q?.path},{...e,path:r})),P(r),!r&&d.documentPath&&d.documentPath(e.documentId,f,I).then(t=>{t&&M.current===n&&(A(n=>le(n,e.documentId,{path:t})),P(t))},()=>{})},[d,L,k,Q?.path,f,I,P]),Ue=(0,c.useCallback)(e=>{let t=ce(k,e);t!==k&&(M.current++,A(t),P(t[t.length-1].path))},[k,P]),We=(0,c.useCallback)((e,t)=>A(n=>le(n,e,{title:t})),[]),$=(0,c.useCallback)(e=>{be(t=>({documentId:e.documentId,chunkId:e.chunkId,seq:(t?.seq??0)+1})),Q?.documentId!==e.documentId&&(e.path?F(e.path):(M.current++,A([{documentId:e.documentId,chunkId:e.chunkId}]),P(void 0)))},[Q?.documentId,F,P]),Ge=(0,c.useMemo)(()=>({scope:f,browse:I,selection:{documentId:Q?.documentId,chunkId:U&&U.documentId===Q?.documentId?U.chunkId:void 0,path:Q?.path},onSelect:$,reloadToken:H,maximized:fe,onToggleMaximize:()=>pe(e=>!e),subject:i?.subject}),[f,I,Q?.documentId,Q?.path,U,$,H,fe,i?.subject]),Ke=ye&&Q&&ye.documentId===Q.documentId?ye:void 0,qe=!!Q?.path&&J?.kind===`document`&&J.fullPath===Q.path;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(ge,{className:B?`paths-view paths-view--stars`:`paths-view`,defaultLeftWidth:B?720:420,minLeftWidth:280,minRightWidth:300,storageKey:B?`loomcycle.explorer.split.stars`:`loomcycle.explorer.split.paths`,hideRight:B&&fe,children:[(0,l.jsxs)(`div`,{className:`left`,children:[(0,l.jsxs)(`div`,{className:`paths-toolbar`,children:[(0,l.jsxs)(`label`,{className:`paths-scope`,children:[(0,l.jsx)(`span`,{children:`scope`}),(0,l.jsxs)(`select`,{value:f,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),o&&(0,l.jsxs)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Navigator`,children:[(0,l.jsx)(`button`,{type:`button`,"aria-pressed":!B,className:B?void 0:`active`,onClick:()=>V(`tree`),title:`Browse the Path tree`,children:`tree`}),(0,l.jsx)(`button`,{type:`button`,"aria-pressed":B,className:B?`active`:void 0,onClick:()=>V(`stars`),title:`Browse the scope as a 3D star map`,children:`stars`})]}),(0,l.jsxs)(`div`,{className:`paths-toolbar-actions`,children:[!B&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:Fe,title:`New folder in ${Pe}`,children:`+ folder`}),(0,l.jsx)(`button`,{type:`button`,onClick:Ie,title:`New document in ${Pe}`,children:`+ document`})]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void De(),title:`Reload the tree`,children:`↻`})]})]}),!B&&(0,l.jsxs)(`p`,{className:`paths-context`,children:[`new items → `,(0,l.jsx)(`code`,{children:Pe}),I?.scopeId&&(0,l.jsxs)(l.Fragment,{children:[` · `,`subject `,(0,l.jsx)(`code`,{children:I.scopeId})]}),I?.tenant&&(0,l.jsxs)(l.Fragment,{children:[` · `,`tenant `,(0,l.jsx)(`code`,{children:I.tenant})]})]}),(v||Y)&&(0,l.jsx)(`div`,{className:`paths-err`,children:v||Y}),B&&o?(0,l.jsx)(`div`,{className:`paths-navigator`,children:o(Ge)}):(0,l.jsx)(en,{tree:Ee,root:R.get(``),expanded:w,onToggle:Oe,onLoadMore:ke,onRetry:q,selectedPath:E,onSelect:e=>F(e.fullPath),summaries:xe})]}),(0,l.jsx)(`div`,{className:`right`,children:Q?(0,l.jsxs)(`div`,{className:`paths-doc`,children:[(0,l.jsx)(me,{trail:k,onJump:Ue}),(0,l.jsxs)(`div`,{className:`paths-doc-head`,children:[Q.path?(0,l.jsx)(`code`,{className:`paths-doc-path`,children:Q.path}):(0,l.jsxs)(`span`,{className:`paths-doc-path paths-doc-unfiled`,title:`Opened by id — no entry for this document was found in the Path tree`,children:[ue(Q),` `,(0,l.jsx)(`em`,{children:`· opened by id, not in the tree`})]}),qe&&(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Le,children:`rename / move`}),ze&&(0,l.jsx)(`button`,{type:`button`,onClick:Be,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Re,children:`delete`})]})]}),(0,l.jsx)(Zt,{documentId:Q.documentId,scope:f,titleHint:Q.title,browse:I,principal:i,renderAssistant:a,initialChunkId:Q.chunkId??Ke?.chunkId,onOpenDocument:He,onTitle:We,onChunkSelect:e=>ve({documentId:Q.documentId,chunkId:e}),focusChunk:Ke},k.length)]}):J?(0,l.jsxs)(`div`,{className:`paths-detail`,children:[(0,l.jsxs)(`h2`,{children:[(0,l.jsx)(`span`,{className:`paths-detail-kind`,children:J.kind}),(0,l.jsx)(`code`,{children:J.fullPath})]}),(0,l.jsxs)(`dl`,{className:`paths-detail-meta`,children:[(0,l.jsx)(`dt`,{children:`scope`}),(0,l.jsx)(`dd`,{children:f}),Ne&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`stored`}),(0,l.jsx)(`dd`,{children:Ne})]})]}),Z?(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Le,children:`rename / move`}),ze&&(0,l.jsx)(`button`,{type:`button`,onClick:Be,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Re,children:`delete`})]}):(0,l.jsxs)(`p`,{className:`paths-readonly`,children:[`Read-only — `,J.kind,` entries are managed by their own tool.`]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a path on the left, or create a folder / document.`})})})]}),b&&(0,l.jsx)(un,{state:b,onClose:()=>x(null)}),S&&(0,l.jsx)(he,{data:d,scope:f,browse:I,documentId:S.documentId,underPath:S.underPath,fromPath:S.fromPath,onClose:()=>C(null),onDone:Ve})]})}function un({state:e,onClose:t}){let[n,r]=(0,c.useState)(()=>Object.fromEntries(e.fields.map(e=>[e.key,e.value??``]))),[i,a]=(0,c.useState)(!1),[o,s]=(0,c.useState)(null);return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:t,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async r=>{r.preventDefault(),a(!0),s(null);try{await e.onSubmit(n),t()}catch(e){s(e instanceof Error?e.message:String(e)),a(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:e.title}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:t,disabled:i,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:e.danger?`danger`:`primary`,disabled:i,children:i?`working…`:e.submitLabel})]})]}),e.message&&(0,l.jsx)(`p`,{className:`modal-context`,children:e.message}),e.fields.map((e,t)=>(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:e.label}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:n[e.key],placeholder:e.placeholder,autoFocus:t===0,onChange:t=>r(n=>({...n,[e.key]:t.target.value}))})]},e.key)),o&&(0,l.jsx)(`div`,{className:`modal-err`,children:o})]})})}function dn(e){let{documentId:t,scope:n,browse:r,theme:i}=e,a=ae(e);return(0,l.jsx)(oe,{theme:i,dataLayer:a,children:(0,l.jsx)(fn,{...e},`${n}:${t}:${r?.scopeId??``}:${r?.tenant??``}`)})}function fn({documentId:e,chunkId:t,scope:n,titleHint:r,browse:i,principal:a,renderAssistant:o,onOpenDocument:s}){let[u,d]=(0,c.useState)([]),f=u[u.length-1],[p,m]=(0,c.useState)(),h=(0,c.useRef)(t);(0,c.useEffect)(()=>{t!==h.current&&(h.current=t,u.length>0?(m(void 0),d([])):m(e=>({chunkId:t,seq:(e?.seq??0)+1})))},[t]);let g=(0,c.useCallback)((e,t)=>{s?s(e,t):d(n=>se(n,t,e))},[s]),_=(0,c.useCallback)(e=>d(t=>ce(t,e)),[]),v=(0,c.useCallback)((e,t)=>d(n=>le(n,e,{title:t})),[]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(me,{trail:u,onJump:_}),(0,l.jsx)(Zt,{documentId:f?.documentId??e,scope:n,titleHint:f?f.title:r,browse:i,principal:a,renderAssistant:o,initialChunkId:f?f.chunkId:t,focusChunk:f?void 0:p,onOpenDocument:g,onTitle:v},u.length)]})}exports.DEFAULT_SCHEME=Z,exports.DocumentViewer=dn,exports.EDGE_PAGE_CAP=be,exports.PathExplorer=cn,exports.QUEUE_CHANGED_RETRIES=J,exports.RULING_CHUNK=q,exports.RequestError=R,exports.assetFetchFromConnection=L,exports.chunkColor=He,exports.chunkCount=Ne,exports.chunkInheritsDocColor=Ue,exports.chunkRowStyle=Ke,exports.createLoomcycleClient=I,exports.dataLayerFromClient=D,exports.docColor=Q,exports.effectiveScheme=Be,exports.hexToTint=We,exports.isQueueChanged=Ae,exports.jsonPostFromConnection=z,exports.loadDocumentEdges=W,exports.runRuling=je,exports.tintStyle=$,exports.transferInput=y,exports.undoRulings=Me,exports.washStyle=Ge;
|
|
17
17
|
//# sourceMappingURL=index.cjs.map
|