1 line
48 KiB
JavaScript
1 line
48 KiB
JavaScript
(()=>{if(document.documentElement.dataset.appTheme)return;const e="plotline.theme",t=document.querySelectorAll("[data-theme-choice]"),n=n=>{const a="dark"===n?"dark":"light";document.documentElement.dataset.theme=a,document.documentElement.dataset.bsTheme=a,(t=>{try{localStorage.setItem(e,t)}catch{}})(a),t.forEach(e=>{const t=e.dataset.themeChoice===a;e.classList.toggle("active",t),e.setAttribute("aria-pressed",String(t))})};t.forEach(e=>{e.addEventListener("click",()=>n(e.dataset.themeChoice))}),n((()=>{try{return localStorage.getItem(e)}catch{return null}})()||"light")})(),(()=>{const e=document.querySelector("[data-trial-banner]");if(!e)return;const t=`plotline.trialBanner.dismissed.${e.dataset.trialBannerKey||"current"}`;try{if("true"===localStorage.getItem(t))return void(e.hidden=!0)}catch{}e.querySelector("[data-trial-banner-dismiss]")?.addEventListener("click",()=>{e.hidden=!0;try{localStorage.setItem(t,"true")}catch{}})})(),(()=>{const e="plotdirector:story-position-changed",t=(e,t)=>{const n=e?.position||e?.Position||e||{},a=(...e)=>{for(const t of e){const e=Number.parseInt(t||"",10);if(Number.isInteger(e)&&e>0)return e}return null};return{source:t||e?.source||e?.Source||"Navigation",projectId:a(n.projectId,n.ProjectId,e?.projectId,e?.ProjectId),bookId:a(n.bookId,n.BookId,e?.bookId,e?.BookId),chapterId:a(n.chapterId,n.ChapterId,e?.chapterId,e?.ChapterId),sceneId:a(n.sceneId,n.SceneId,e?.sceneId,e?.SceneId),canonicalUrl:e?.canonicalUrl||e?.CanonicalUrl||e?.sceneUrl||e?.SceneUrl||""}};window.PlotDirectorStoryPosition={eventName:e,normalise:t,publishChanged:(n,a)=>{const o=t(n,a);return o.projectId?(document.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:o})),o):o}}})(),(()=>{const e=document.getElementById("plotlineConfirmModal"),t=e&&window.bootstrap?new bootstrap.Modal(e):null,n=e?.querySelector("#plotlineConfirmModalTitle"),a=e?.querySelector("#plotlineConfirmModalMessage"),o=e?.querySelector("[data-confirm-submit]"),r=e?.querySelector("[data-delete-confirm-field]"),i=e?.querySelector("[data-delete-confirm-input]");let s=null,l=null;e?.addEventListener("hidden.bs.modal",()=>{s=null,l=null,i&&(i.value=""),r?.classList.add("d-none"),o?.removeAttribute("disabled")}),i?.addEventListener("input",()=>{"true"===s?.dataset.requireDeleteText&&o&&(o.disabled="DELETE"!==i.value.trim())}),o?.addEventListener("click",()=>{if(s){if("true"===s.dataset.requireDeleteText){const e=s.querySelector("[data-delete-confirm-target], [name='confirmationText']");e&&(e.value=i?.value.trim()||"")}s.dataset.confirmed="true",t?.hide(),s.requestSubmit&&l?s.requestSubmit(l):s.requestSubmit?s.requestSubmit():s.submit()}}),document.addEventListener("submit",c=>{const d=c.target;if(!(d instanceof HTMLFormElement)||"true"===d.dataset.confirmed||"true"===d.dataset.confirmSkip||"true"===d.dataset.noDeleteConfirm)return;const p=d.dataset.confirmMessage,u=c.submitter instanceof HTMLElement?c.submitter:d.querySelector("button[type='submit']"),m=u?.textContent||"",h=d.getAttribute("action")||"",g=/restore/i.test(m)||/\/restore\b/i.test(h),f=/delete forever/i.test(m)||/\/deleteforever\b/i.test(h),v=!g&&!f&&(/archive/i.test(m)||/\/archive\b/i.test(h)),y=!f&&/(delete|remove)/i.test(m);if(!(p||v||g||y||f))return;const w=p||(v?"Archive this item?\n\nThis will hide it from active lists and timelines, but the data will be kept and can be restored later.":g?"Restore this item?\n\nThis will return it to active lists and timelines where applicable.":f?"Permanently delete this item?\n\nThis cannot be undone. Any linked planning data may also be removed or become unavailable. Only continue if you are certain.":"Remove this item?\n\nThis removes the link or supporting record. Major story items are archived instead of permanently deleted.");if(!(t&&e&&n&&a&&o))return;c.preventDefault();const b=(e=>{const t=e.split(/\n\s*\n/);return{title:t.shift()?.trim()||"Confirm action",body:t.join("\n\n").trim()}})(w);s=d,l=u,n.textContent=d.dataset.confirmTitle||b.title,a.textContent=d.dataset.confirmBody||b.body,o.textContent=d.dataset.confirmButtonText||m.trim()||"Confirm",o.className=`btn ${d.dataset.confirmButtonClass||(g?"btn-primary":"btn-danger")}`;const L="true"===d.dataset.requireDeleteText||f;r?.classList.toggle("d-none",!L),L&&o&&(o.disabled=!0,i?.focus()),t.show(),L&&window.setTimeout(()=>i?.focus(),200)})})(),(()=>{if(!window.bootstrap)return;const e=new Map;let t=null;const n=new WeakSet,a=e=>e.querySelector("[data-help-tooltip]")||e,o=e=>bootstrap.Tooltip.getInstance(a(e))?.hide(),r=(e=null)=>{t&&t!==e&&bootstrap.Popover.getInstance(t)?.hide()},i=()=>document.querySelectorAll("[data-help-icon]").forEach(e=>o(e)),s=(s=document)=>{(e=>{if(!e)return[];const t=[];return e.matches?.("[data-help-icon]")&&t.push(e),e.querySelectorAll?.("[data-help-icon]").forEach(e=>t.push(e)),t})(s).forEach(s=>{if(n.has(s))return;n.add(s);const l=a(s),c=l.dataset.helpMicro||"Help article not found.",d=s.dataset.helpTitle||"Help unavailable",p=s.dataset.helpSummary||"Help content has not yet been written for this feature.";bootstrap.Tooltip.getOrCreateInstance(l,{title:c,trigger:"hover focus",placement:"top",container:"body"});const u=bootstrap.Popover.getOrCreateInstance(s,{title:d,trigger:"click",placement:"auto",container:"body",html:!0,customClass:"plotline-help-popover",content(){const e=document.createElement("div"),t=document.createElement("p");t.className="mb-2",t.textContent=p;const n=document.createElement("a");return n.href=s.dataset.helpUrl||"#",n.textContent="More...",n.className="plotline-help-more",n.addEventListener("click",e=>{e.preventDefault(),r(),i(),s.dispatchEvent(new CustomEvent("plotline:help-more",{bubbles:!0,detail:{key:s.dataset.helpKey||""}}))}),e.append(t,n),e}});e.set(s,u),s.addEventListener("click",e=>{window.PlotLineHelpDrawer?.isActive?.()&&(e.preventDefault(),e.stopPropagation(),r(),o(s),window.PlotLineHelpPopovers?.hideAll(),window.PlotLineHelpDrawer.open(s.dataset.helpKey||""))}),s.addEventListener("show.bs.popover",e=>{window.PlotLineHelpDrawer?.isActive?.()?e.preventDefault():(r(s),o(s))}),s.addEventListener("shown.bs.popover",()=>{t=s,o(s)}),s.addEventListener("hidden.bs.popover",()=>{t===s&&(t=null)})})};document.addEventListener("click",e=>{const n=e.target instanceof Element?e.target:null;if(!n||!t)return;if(n.closest("[data-help-icon]"))return;const a=document.querySelector(`#${t.getAttribute("aria-describedby")}`);a?.contains(n)||r()}),document.addEventListener("keydown",e=>{"Escape"===e.key&&r()}),window.PlotLineHelpPopovers={hideAll(){e.forEach(e=>e.hide()),i(),t=null}},window.PlotLineHelpIcons={init:s},s()})(),(()=>{const e=document.querySelector("[data-help-layout]"),t=document.querySelector("[data-help-drawer]"),n=document.querySelector("[data-help-content]"),a=document.querySelector("[data-help-splitter]"),o=document.querySelector("[data-help-close]"),r=document.querySelector("[data-help-collapse]"),i=document.querySelector("[data-help-expand]"),s=document.querySelector("[data-help-pin]"),l=document.querySelector("[data-help-drawer-heading]");if(!e||!t||!n)return;const c="plotline.helpDrawer.width",d="plotline.helpDrawer.pinned",p="plotline.helpDrawer.key",u="plotline.helpDrawer.collapsed",m=e=>{try{return"true"===localStorage.getItem(e)}catch{return!1}},h=(e,t)=>{try{localStorage.setItem(e,t)}catch{}},g=t=>{const n=`${((e,t,n)=>Math.min(n,Math.max(t,e)))(Number.parseFloat(t)||25,20,50)}%`;e.style.setProperty("--help-drawer-width",n),h(c,n)},f=e=>{h(d,String(e)),s?.setAttribute("aria-pressed",String(e)),s&&(s.textContent=e?"Unpin":"Pin")},v=t=>{e.classList.toggle("help-collapsed",t),h(u,String(t)),r&&(r.textContent=t?"Expand":"Collapse")},y=async(t,a={})=>{const o=t||"";e.classList.add("help-open"),a.keepCollapsed||v(!1),h(p,o),l&&(l.textContent=o||"Help"),n.innerHTML='<p class="muted">Loading help...</p>';try{const e=await fetch(`/HelpDrawer/Article?key=${encodeURIComponent(o)}`,{headers:{"X-Requested-With":"XMLHttpRequest"}});n.innerHTML=e.ok?await e.text():'<p class="muted">Help for this feature has not yet been written.</p>';const t=n.querySelector(".help-drawer-article h2")?.textContent?.trim();l&&t&&(l.textContent=t)}catch{n.innerHTML='<p class="muted">Help for this feature has not yet been written.</p>'}};window.PlotLineHelpDrawer={isActive:()=>e.classList.contains("help-open"),open:e=>y(e)},g(localStorage.getItem(c)||"25%"),f(m(d)),v(m(u)),document.addEventListener("plotline:help-more",e=>{const t=e.detail?.key||e.target?.dataset?.helpKey||"";window.PlotLineHelpPopovers?.hideAll(),y(t)}),document.addEventListener("click",e=>{const t=e.target instanceof Element?e.target.closest("[data-help-open]"):null;t&&(e.preventDefault(),window.PlotLineHelpPopovers?.hideAll(),y(t.dataset.helpOpen||""))}),o?.addEventListener("click",()=>{e.classList.remove("help-open","help-collapsed"),f(!1)}),r?.addEventListener("click",()=>v(!e.classList.contains("help-collapsed"))),i?.addEventListener("click",()=>v(!1)),i?.addEventListener("keydown",e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),v(!1))}),s?.addEventListener("click",()=>f(!m(d))),a?.addEventListener("pointerdown",t=>{if(!e.classList.contains("help-open")||e.classList.contains("help-collapsed"))return;t.preventDefault(),document.body.classList.add("help-resizing"),a.setPointerCapture?.(t.pointerId);const n=t=>{const n=e.getBoundingClientRect(),a=(n.right-t.clientX)/n.width*100;g(a)},o=()=>{document.body.classList.remove("help-resizing"),document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o)};document.addEventListener("pointermove",n),document.addEventListener("pointerup",o)});const w=(()=>{try{return localStorage.getItem(p)||""}catch{return""}})();m(d)&&w&&y(w,{keepCollapsed:!0})})(),(()=>{const e=document.querySelectorAll("[data-metric-shape-chart]");if(!e.length)return;const t=["#2f6f63","#b35f3b","#6750a4","#c58b2b","#7d3f52","#33759b","#9c4d8f","#a33d3d","#6f8f3d","#d08a2f","#444b57"],n=new Set(["Overall Intensity","Tension","Emotional Weight","Action"]),a=[],o=e=>{const t=e.querySelector(".metric-chart-frame");if(!t)return;let n=Number(t.dataset.metricNaturalWidth||0);if(n&&"true"===t.dataset.metricCanvasConstrained||(t.style.width="",n=t.getBoundingClientRect().width,n&&(t.dataset.metricNaturalWidth=String(n))),!n)return;const a=Math.max(window.devicePixelRatio||1,1),o=Math.floor(3e4/a);n>o?(t.style.width=`${o}px`,t.dataset.metricCanvasConstrained="true"):(t.style.width="",t.dataset.metricCanvasConstrained="false")},r=()=>{window.requestAnimationFrame(()=>{a.forEach(({chart:e,root:t,timelineLayout:n})=>{n?n.schedule(!0):(o(t),e.resize())})})};window.PlotLineMetricCharts={resizeAll:r},window.addEventListener("plotline:timeline-layout-changed",r);const i={id:"plotlineChapterGuides",afterDraw(e){const t=e.config.options.plugins.plotlineScenes||[],{ctx:n,chartArea:a,scales:o}=e;if(!t.length||!o.x)return;n.save(),n.strokeStyle="rgba(47, 111, 99, 0.16)",n.fillStyle="rgba(82, 75, 65, 0.58)",n.lineWidth=1,n.font="700 10px system-ui, -apple-system, Segoe UI, sans-serif";const r=[];t.forEach((e,n)=>{n&&e.chapterLabel===t[n-1].chapterLabel&&e.bookTitle===t[n-1].bookTitle||r.push({scene:e,index:n})});const i=r.filter(e=>!e.scene.isPlaceholder),s=i.length>40?5:i.length>24?4:i.length>14?2:1;i.forEach((t,r)=>{const{scene:l,index:c}=t,d=o.x.getPixelForValue(e.data.datasets[0].data[c].x);if(!Number.isFinite(d)||d<a.left||d>a.right)return;n.beginPath(),n.moveTo(d,a.top),n.lineTo(d,a.bottom),n.stroke();const p=Number.parseInt(String(l.chapterLabel).replace(/[^0-9]/g,""),10);(0===r||r===i.length-1||1===s||Number.isFinite(p)&&p%s===0)&&n.fillText(l.chapterLabel,Math.min(d+4,a.right-70),a.bottom+22)}),n.restore()}};if(window.Chart){Chart.register(i);class e extends Chart.LinearScale{static id="timelinePosition";getPixelForValue(e){return Number(e)-(this.chart.$timelineViewportLeft||0)}getValueForPixel(e){return e+(this.chart.$timelineViewportLeft||0)}}Chart.register(e)}e.forEach(e=>{const r=e.querySelector("script[type='application/json']"),i=e.querySelector("canvas"),s=e.querySelector("[data-metric-toggles]"),l=e.querySelector("[data-chart-fallback]"),c=e.querySelector("[data-timeline-metric-edit-toolbar]"),d=e.querySelector("[data-edit-metric-status]"),p=e.hasAttribute("data-timeline-metric-editor")&&c&&d;if(!r||!i)return;let u;try{u=JSON.parse(r.textContent||"{}")}catch{return void l?.classList.remove("d-none")}if(!window.Chart||!u.scenes?.length||!u.metrics?.length)return void l?.classList.remove("d-none");const m=e.closest(".timeline-shell"),h=m?.querySelector(".timeline-series-row"),g=e.querySelector(".metric-chart-frame"),f=new Map(Array.from(h?.querySelectorAll(".timeline-scene-card[data-scene-id]")||[],e=>[Number(e.dataset.sceneId),e])),v=m&&h&&f.size?document.createElement("div"):null;let y=null,w=!1;v&&(v.className="metric-timeline-viewport",i.before(v),v.append(i));const b=new Set(u.defaultMetrics?.length?u.defaultMetrics:n),L=u.scenes.length,S=L>80?10:L>40?5:L>24?4:L>14?2:1,E=u.metrics.map((e,n)=>{const a=new Map(e.points.map(e=>[e.sceneId,e.value])),o=t[n%t.length];return{label:e.metricName,metricTypeId:e.metricTypeId,minValue:Number.isFinite(e.minValue)?e.minValue:1,maxValue:Number.isFinite(e.maxValue)?e.maxValue:10,data:u.scenes.map((e,t)=>{const n=a.get(e.sceneId);return null==n?{x:t+.5,y:null,sceneId:e.sceneId}:{x:t+.5,y:n,sceneId:e.sceneId}}),borderColor:o,backgroundColor:o,pointBackgroundColor:o,pointBorderColor:"#fff",pointBorderWidth:1.5,pointRadius:3,pointHoverRadius:5,borderWidth:2,tension:.35,spanGaps:!0,hidden:!b.has(e.metricName)}});let x=null,I=!1;o(e);const q=e=>{d&&(d.textContent=e)},C=()=>E.map((e,t)=>t).filter(e=>A?.isDatasetVisible(e)),k=()=>{const e=C();return 1===e.length?e[0]:-1},M=()=>{if(!p)return;const e=k();E.forEach((t,n)=>{t.pointRadius=n===e?5:3,t.pointHoverRadius=n===e?7:5,t.borderWidth=n===e?3:2});const t=C(),n=e>=0;i.classList.toggle("metric-curve-editing",n),d.classList.toggle("d-none",0===t.length),0===t.length?q(""):q(n?"Drag points up or down to edit this metric.":"Select a single metric to edit its curve."),A?.update()};s.innerHTML="",E.forEach((e,t)=>{const n=`metric-toggle-${Math.random().toString(36).slice(2)}-${t}`,a=document.createElement("label");a.className="metric-toggle-pill",a.style.setProperty("--metric-colour",e.borderColor),a.innerHTML=`<input type="checkbox" id="${n}" ${e.hidden?"":"checked"}><span>${e.label}</span>`,s.appendChild(a),a.querySelector("input").addEventListener("change",e=>{A.setDatasetVisibility(t,e.target.checked),M(),A.update()})});const A=new Chart(i,{type:"line",data:{datasets:E},options:{responsive:!0,animation:!v&&void 0,maintainAspectRatio:!1,interaction:{mode:"nearest",intersect:!1},scales:{y:{min:1,max:10,ticks:{stepSize:1},grid:{color:"rgba(82, 75, 65, 0.10)"}},x:{type:"linear",min:0,max:L,bounds:"ticks",ticks:{maxRotation:0,autoSkip:!1,maxTicksLimit:16,callback(e){const t=E[0].data.findIndex(t=>t.x===Number(e));if(t<0||t>=L)return"";const n=u.scenes[t];return 0!==t&&t!==L-1&&t%S!==0||n?.isPlaceholder?"":n?.axisLabel||""}},afterBuildTicks(e){e.ticks=E[0].data.filter(t=>Number.isFinite(t.x)&&(!w||t.x>=e.min&&t.x<=e.max)).map(e=>({value:e.x}))},grid:{display:!1}}},plugins:{legend:{display:!1},plotlineScenes:u.scenes,tooltip:{callbacks:{title(e){const t=e[0].dataIndex,n=u.scenes[t];return n.isPlaceholder?n.sceneTitle||"No scene":`${n.chapterLabel}, Scene ${n.sceneNumber}: ${n.sceneTitle}`},label:e=>`${e.dataset.label}: ${e.formattedValue}`,afterBody(e){const t=e[0].dataIndex,n=u.scenes[t],a=[];return n.characterPresence?a.push(n.characterPresence):void 0!==n.characterAppears&&a.push(n.characterAppears?"Character appears":"Character does not appear"),n.bookTitle&&a.push(n.bookTitle),a}}}}}});if(p&&(M(),i.addEventListener("pointerdown",e=>{x=(e=>{if(!p)return null;const t=k();if(t<0)return null;const n=A.getElementsAtEventForMode(e,"nearest",{intersect:!0},!0).find(e=>e.datasetIndex===t);if(!n)return null;const a=A.data.datasets[n.datasetIndex],o=a?.data?.[n.index];return o?.sceneId&&null!=o.y?{datasetIndex:n.datasetIndex,pointIndex:n.index,previousValue:o.y}:null})(e),x&&(e.preventDefault(),i.setPointerCapture?.(e.pointerId),I=!0)}),i.addEventListener("pointermove",e=>{if(!x)return;const t=A.data.datasets[x.datasetIndex],n=t?.data?.[x.pointIndex];t&&n&&(n.y=((e,t)=>{const n=A.scales.y.getValueForPixel(e.offsetY),a=Math.round(n);return Math.max(t.minValue,Math.min(t.maxValue,a))})(e,t),A.update("none"))}),i.addEventListener("pointerup",async t=>{if(!x)return;const n=x;x=null,i.releasePointerCapture?.(t.pointerId),await(async t=>{const n=A.data.datasets[t.datasetIndex],a=n?.data?.[t.pointIndex];if(!n||!a?.sceneId)return;const o=c?.querySelector("input[name='__RequestVerificationToken']")?.value||"";q("Saving...");try{const t=await fetch(e.dataset.updateUrl||"/SceneMetrics/UpdateSceneMetricValue",{method:"POST",headers:{"Content-Type":"application/json",RequestVerificationToken:o},body:JSON.stringify({sceneId:Number(a.sceneId),metricId:Number(n.metricTypeId),value:Number(a.y)})}),r=await t.json().catch(()=>({}));if(!t.ok||!r.success)throw new Error(r.message||"Save failed");a.y=r.value,q("Saved"),A.update()}catch{a.y=t.previousValue,q("Save failed"),A.update()}})(n),window.setTimeout(()=>{I=!1},0)}),i.addEventListener("pointercancel",e=>{if(!x)return;const t=A.data.datasets[x.datasetIndex],n=t?.data?.[x.pointIndex];n&&(n.y=x.previousValue),x=null,i.releasePointerCapture?.(e.pointerId),I=!1,A.update()})),i.addEventListener("click",e=>{if(I)return void e.preventDefault();const t=A.getElementsAtEventForMode(e,"nearest",{intersect:!0},!0);if(!t.length)return;const n=t[0].index,a=u.scenes[n];a?.timelineUrl&&(window.PlotLineTimelineScroll?.save(),window.location.href=a.timelineUrl)}),v){let t=0,n=!1;const a=()=>{if(t=0,e.getBoundingClientRect().width){if(n){n=!1;const t=h.getBoundingClientRect();if(t.width){const n=g.getBoundingClientRect().left,a=new Map;let o=t.right-n;f.forEach((e,t)=>{const r=e.getBoundingClientRect();r.width&&(a.set(t,r.left+r.width/2-n),o=Math.max(o,r.right-n))}),a.size&&(e.style.setProperty("--metric-layout-width",`${o}px`),g.style.width=`${o}px`,g.classList.add("metric-timeline-measured"),E.forEach(e=>e.data.forEach(e=>{e.x=a.get(e.sceneId)??NaN})),w=!0,A.options.scales.x.type="timelinePosition")}}w?(v.style.width=`${Math.min(m.clientWidth,g.clientWidth,Math.floor(3e4/Math.max(window.devicePixelRatio||1,1)))}px`,A.$timelineViewportLeft=i.getBoundingClientRect().left-g.getBoundingClientRect().left,A.options.scales.x.min=A.$timelineViewportLeft,A.options.scales.x.max=A.$timelineViewportLeft+v.clientWidth):o(e),A.resize(),A.update("none")}},r=(e=!1)=>{n||=e,t||(t=window.requestAnimationFrame(a))};y={schedule:r},m.addEventListener("scroll",()=>r(),{passive:!0}),window.addEventListener("resize",()=>r(!0));const s=window.ResizeObserver?new ResizeObserver(()=>r(!0)):null;s?.observe(m),s?.observe(h),s?.observe(e),h.querySelectorAll(".timeline-book, .timeline-book-title, .timeline-chapter, .timeline-scenes, .timeline-scene-card").forEach(e=>s?.observe(e)),r(!0)}else{const t=window.ResizeObserver?new ResizeObserver(()=>{o(e),A.resize()}):null;t?.observe(e),t?.observe(g||e)}a.push({chart:A,root:e,timelineLayout:y})})})(),(()=>{const e=document.querySelector("[data-timeline-root]"),t=document.querySelector("[data-timeline-controls]");if(!e||!t)return;const n="plotline.timeline.visibility",a={"scene-cards":!0,"plot-lines":!0,assets:!0,characters:!0,locations:!0,warnings:!0,metrics:!0},o=t=>{Object.entries(t).forEach(([t,n])=>{e.classList.toggle(`hide-${t}`,!n),document.querySelectorAll(`[data-timeline-section='${t}']`).forEach(e=>{e.classList.toggle("timeline-section-hidden",!n)})}),document.querySelectorAll("[data-location-marker]").forEach(e=>{e.classList.toggle("timeline-section-hidden",!t.locations)}),document.querySelectorAll("[data-warning-marker]").forEach(e=>{e.classList.toggle("timeline-section-hidden",!t.warnings)}),document.querySelector("[data-visibility-json]")?.setAttribute("value",JSON.stringify(t))},r=(()=>{try{return{...a,...JSON.parse(localStorage.getItem(n)||"{}")}}catch{return{...a}}})();t.querySelectorAll("[data-timeline-toggle]").forEach(e=>{const t=e.dataset.timelineToggle;e.checked=r[t]??!0,e.addEventListener("change",()=>{r[t]=e.checked,localStorage.setItem(n,JSON.stringify(r)),o(r)})}),t.querySelector("[data-timeline-preset-form]")?.addEventListener("submit",()=>{document.querySelector("[data-visibility-json]")?.setAttribute("value",JSON.stringify(r))}),o(r)})(),(()=>{const e=document.querySelector("[data-timeline-root]");if(!e)return;const t=e.querySelector(".timeline-workspace")||e,n=document.querySelector("[data-timeline-density]"),a=document.querySelector("[data-timeline-zoom]"),o=document.querySelector("[data-timeline-search]"),r=e.querySelector("[data-timeline-minimap]"),i=document.querySelectorAll("[data-timeline-jump], [data-timeline-warning-jump], [data-timeline-entity-jump]"),s=[...e.querySelectorAll(".timeline-scene-card[data-scene-id]")],l="plotline.timeline.collapsed",c="plotline.timeline.density",d="plotline.timeline.zoom",p="plotline.timeline.pending-scroll",u="plotdirector.timelineNavigationDiscovered",m="plotline.timeline.inspectorWidth",h=[".timeline-shell",".plot-lane-board",".asset-lane-board",".character-lane-board",".metric-graph-stack","[data-timeline-minimap]"].join(","),g=["compact","comfortable","expanded"],f=["book","chapter","scene-detail","scene-overview"],v=e.querySelector("[data-inspector-drawer]"),y=e.querySelector("[data-inspector-resizer]"),w=e.querySelector("[data-inspector-close]"),b=null!==localStorage.getItem(l),L=(e=>{try{return new Set(JSON.parse(localStorage.getItem(e)||"[]"))}catch{return new Set}})(l),S=()=>[...e.querySelectorAll(h)],E=t=>{if(!v)return;const{minimum:n,maximum:a,defaultWidth:o}=(()=>{const t=e.getBoundingClientRect().width||window.innerWidth,n=Math.min(420,Math.max(320,t-360)),a=Math.max(n,Math.min(.65*t,t-420));return{minimum:n,maximum:a,defaultWidth:Math.max(n,Math.min(a,.4*t))}})(),r=Math.max(n,Math.min(a,Number(t)||o));e.style.setProperty("--timeline-inspector-width",`${Math.round(r)}px`)};v&&(E(localStorage.getItem(m)),window.addEventListener("resize",()=>E(localStorage.getItem(m)))),(()=>{const o=e.querySelector("[data-timeline-navigation-card]");if(!o)return;const r=o.querySelector("[data-timeline-navigation-dismiss]"),i=o.querySelector("[data-timeline-navigation-demo]"),s=()=>e.querySelector(".timeline-shell"),l=e=>Boolean(e&&e.scrollWidth>e.clientWidth+8),c=e=>Math.max(0,e.scrollWidth-e.clientWidth),d=()=>[t,...S()].filter((e,t,n)=>e&&n.indexOf(e)===t);let p=!1,m=!1,h=!1,g=null;const f=new WeakMap,v=e=>f.set(e,e.scrollLeft),y=(e=!1)=>{if(window.clearTimeout(g),!e||window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches||o.hidden)return o.classList.remove("is-dismissing"),void(o.hidden=!0);o.classList.add("is-dismissing"),g=window.setTimeout(()=>{o.hidden=!0,o.classList.remove("is-dismissing")},1300)},w=e=>{const t=l(e),n=c(e);e.classList.toggle("timeline-horizontal-overflow",t),e.classList.toggle("has-scroll-left",t&&e.scrollLeft>8),e.classList.toggle("has-scroll-right",t&&e.scrollLeft<n-8)},b=()=>{l(s())&&!(()=>{try{return"true"===localStorage.getItem(u)}catch{return!1}})()&&!p?(window.clearTimeout(g),o.hidden=!1,o.classList.remove("is-dismissing")):o.classList.contains("is-dismissing")||y(!1),d().forEach(w)},L=()=>{p=!0,y(!0);try{localStorage.setItem(u,"true")}catch{}};d().forEach(e=>{v(e),e.addEventListener("wheel",t=>{if(!t.defaultPrevented&&t.shiftKey&&Math.abs(t.deltaY)>Math.abs(t.deltaX)&&l(e)){const n=e.scrollLeft;t.preventDefault(),e.scrollLeft+=t.deltaY,window.requestAnimationFrame(()=>{w(e),!m&&Math.abs(e.scrollLeft-n)>4&&L(),v(e)})}},{passive:!1}),e.addEventListener("scroll",()=>(e=>{if(w(e),!h||m)return void v(e);const t=f.get(e)??e.scrollLeft;Math.abs(e.scrollLeft-t)>4&&l(e)?L():v(e)})(e),{passive:!0})}),r?.addEventListener("click",L),i?.addEventListener("click",()=>{const e=s();if(!l(e))return void b();const t=e.scrollLeft,n=c(e)-t;let a=Math.min(220,n),o=1;a<24&&t>0&&(a=Math.min(220,t),o=-1),a<4||(m=!0,e.scrollTo({left:t+a*o,behavior:"smooth"}),window.setTimeout(()=>{e.scrollTo({left:t,behavior:"smooth"})},420),window.setTimeout(()=>{m=!1,d().forEach(e=>{v(e),w(e)}),b()},950))}),window.setTimeout(()=>{h=!0,d().forEach(v)},800),window.requestAnimationFrame(b),window.addEventListener("resize",b),window.addEventListener("plotline:timeline-layout-changed",b),n?.addEventListener("change",()=>window.requestAnimationFrame(b)),a?.addEventListener("change",()=>window.requestAnimationFrame(b))})(),y?.addEventListener("pointerdown",t=>{t.preventDefault(),document.body.classList.add("timeline-inspector-resizing"),y.setPointerCapture(t.pointerId);const n=t=>{const n=e.getBoundingClientRect().right-t.clientX;E(n)},a=()=>{document.body.classList.remove("timeline-inspector-resizing");const e=Math.round(v?.getBoundingClientRect().width||0);e>0&&localStorage.setItem(m,String(e)),window.dispatchEvent(new Event("plotline:timeline-layout-changed")),y.removeEventListener("pointermove",n),y.removeEventListener("pointerup",a),y.removeEventListener("pointercancel",a)};y.addEventListener("pointermove",n),y.addEventListener("pointerup",a),y.addEventListener("pointercancel",a)}),w?.addEventListener("click",e=>{e.preventDefault();const t=new URL(window.location.href),n=t.searchParams.get("FocusType")||t.searchParams.get("focusType");t.searchParams.delete("SelectedSceneID"),t.searchParams.delete("selectedSceneId"),t.searchParams.delete("selectedsceneid"),n&&"scene"!==n.toLowerCase()||(t.searchParams.delete("FocusType"),t.searchParams.delete("focusType"),t.searchParams.delete("FocusID"),t.searchParams.delete("focusId")),x(),window.location.href=t.toString()});const x=()=>{try{sessionStorage.setItem(p,JSON.stringify({path:window.location.pathname,top:window.scrollY,left:window.scrollX,workspaceLeft:t.scrollLeft,workspaceTop:t.scrollTop,containers:S().map((e,t)=>({index:t,left:e.scrollLeft,top:e.scrollTop}))}))}catch{}};window.PlotLineTimelineScroll={save:x};const I=(t,n,a)=>{a.forEach(n=>e.classList.remove(`${t}-${n}`)),e.classList.add(`${t}-${n}`)},q=e=>{const t=g.includes(e)?e:"comfortable";I("density",t,g),n&&(n.value=t),localStorage.setItem(c,t),window.dispatchEvent(new Event("plotline:timeline-layout-changed"))},C=e=>{const t=f.includes(e)?e:"chapter";I("zoom",t,f),a&&(a.value=t),localStorage.setItem(d,t),window.dispatchEvent(new Event("plotline:timeline-layout-changed"))},k=(t,n=!0)=>{const a=(t=>e.querySelector(`[data-scene-id='${CSS.escape(String(t))}']`))(t);a&&(a.classList.add("keyboard-focus"),a.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}),n&&a.focus({preventScroll:!0}),window.setTimeout(()=>a.classList.remove("keyboard-focus"),1800))},M=()=>{e.querySelectorAll("[data-plot-line-svg-board]").forEach(e=>{const t=e.querySelector("[data-plot-line-svg]");if(!t)return;let n=e.querySelector("[data-plot-line-health-svg]");n||(n=document.createElementNS("http://www.w3.org/2000/svg","svg"),n.setAttribute("class","plot-lane-svg-overlay plot-lane-svg-health-overlay"),n.setAttribute("data-plot-line-health-svg",""),n.setAttribute("aria-hidden","true"),t.after(n)),t.replaceChildren(),n.replaceChildren();const a=e.getBoundingClientRect(),o=Math.max(e.scrollWidth,a.width),r=Math.max(e.scrollHeight,a.height);[t,n].forEach(e=>{e.setAttribute("viewBox",`0 0 ${o} ${r}`),e.setAttribute("width",String(o)),e.setAttribute("height",String(r))});const i=(e,t={})=>{const n=document.createElementNS("http://www.w3.org/2000/svg",e);return Object.entries(t).forEach(([e,t])=>n.setAttribute(e,String(t))),n},s=[...new Set([...e.querySelectorAll("[data-plot-line-slot]")].map(e=>{const t=e.getBoundingClientRect();return Math.round(t.left-a.left+t.width/2)}))].sort((e,t)=>e-t),l=Math.max(s.length-1,0),c=new Map;e.querySelectorAll("[data-plot-line-row]").forEach(e=>{e.dataset.plotLineId&&c.set(e.dataset.plotLineId,e)});const d=[...c.values()].map(e=>({row:e,plotLineId:e.dataset.plotLineId,colour:e.dataset.plotColour||"#2f6f63",points:[...e.querySelectorAll("[data-plot-event-node]")].map(e=>((e,t)=>{const n=t.closest("[data-plot-line-slot]");if(!n)return null;const o=n.getBoundingClientRect(),r=t.getBoundingClientRect();return{x:r.left-a.left+r.width/2,y:r.top-a.top+r.height/2,sceneX:o.left-a.left+o.width/2,radius:Math.max(r.width,r.height)/2,sceneIndex:0,type:(t.dataset.plotEventType||"Progress").toLowerCase(),targetPlotLineId:t.dataset.targetPlotLineId||"",targetPlotLineIds:(t.dataset.targetPlotLineIds||"").split(",").map(e=>e.trim()).filter(Boolean)}})(0,e)).filter(Boolean).map(e=>({...e,sceneIndex:Math.max(0,s.findIndex(t=>t===Math.round(e.sceneX)))})).sort((e,t)=>e.x-t.x),incomingStartXs:[]})),p=new Map(d.map(e=>[e.plotLineId,e])),u=(e,n,o,r)=>{if(!n)return void(window.console?.warn&&window.console.warn(`Plot line ${r} connector skipped because target plot line data is missing.`));e.x;const s=(e=>{const t=e.getBoundingClientRect();return t.top-a.top+t.height/2})(n),l=Math.max(28,Math.min(46,.28*Math.abs(s-e.y))),c=Math.max(8,e.radius||12),d=e.x+c,p=d+l,u=d+l/2;t.append(i("path",{class:`plot-line-svg-connector plot-line-svg-connector-${r}`,d:`M ${d} ${e.y} C ${u} ${e.y}, ${u} ${s}, ${p} ${s}`,stroke:o}))};d.forEach(e=>{e.points.forEach(e=>{"branch"===e.type&&e.targetPlotLineId&&p.get(e.targetPlotLineId)?.incomingStartXs.push(e.x),"split"===e.type&&e.targetPlotLineIds.forEach(t=>{p.get(t)?.incomingStartXs.push(e.x)})})}),d.forEach(e=>{e.health=(e=>{const t=e.some(e=>"resolve"===e.type),n=e.some(e=>"abandon"===e.type),a=e.find(e=>"resolve"===e.type),o=e.find(e=>"abandon"===e.type),r=e.some(e=>"merge"===e.type&&e.targetPlotLineId),i=e.some(e=>"split"===e.type&&e.targetPlotLineIds.length>=2),s=Boolean(a)&&e.some(e=>"branch"===e.type&&e.targetPlotLineId&&e.sceneIndex>=a.sceneIndex),c=e.reduce((e,t)=>Math.max(e,t.sceneIndex),0),d=!t&&!n&&l-c>=10,p=t&&!r&&!i&&!s;let u="active";return n?u="abandoned":t?u=p?"questionable":"resolved":d&&(u="neglected"),{state:u,isNeglected:d,isDangling:!t&&!n&&!r&&!i&&l>=c,isQuestionable:p,isAbandoned:n,resolvePoint:a,abandonPoint:o}})(e.points),e.state=e.health.state}),d.forEach(e=>{const{colour:n,points:a,incomingStartXs:o,state:r}=e;if(a.length>0){const s=a.find(e=>"start"===e.type),l=o.length?Math.min(...o):null,c=a.find(e=>"split"===e.type||"merge"===e.type),d=a[0],p=a[a.length-1],u=((null===l||s&&s.x<l)&&d.x,c?c.x:p.x);e.lineEndPoint={x:u,y:d.y};const m=[...a].sort((e,t)=>e.x-t.x),h=c?m.indexOf(c):-1,g=h>=0?m.slice(0,h+1):m;null!==l&&l<g[0].x&&g.unshift({...g[0],x:l,sceneIndex:Math.max(0,g[0].sceneIndex-1)});const f=10;g.forEach((e,a)=>{const o=g[a+1];if(!o||o.x<=e.x)return;const s=Math.abs(o.sceneIndex-e.sceneIndex)>=f;t.append(i("path",{class:`plot-line-svg-path plot-line-svg-segment ${s?"plot-line-svg-segment-dormant":""} plotline-state-${r}`,d:`M ${e.x} ${e.y} L ${o.x} ${o.y}`,stroke:n}))})}}),d.forEach(({points:e,colour:t})=>{e.forEach(e=>{"branch"!==e.type&&"merge"!==e.type||u(e,c.get(e.targetPlotLineId),t,e.type),"split"===e.type&&e.targetPlotLineIds.length>=2?e.targetPlotLineIds.forEach(n=>{u(e,c.get(n),t,e.type)}):"split"===e.type&&e.targetPlotLineIds.length>0&&window.console?.warn&&window.console.warn("Plot line split connector skipped because fewer than two targets are available.")})}),d.forEach(e=>{const t=e.lineEndPoint||e.points[e.points.length-1],a=[];e.health?.isNeglected&&t&&a.push({point:t,kind:"neglected",label:"Dormant Thread",reason:"No activity for 10+ scenes.",action:"Add a Progress, Reveal or Resolve event."}),e.health?.isDangling&&t&&a.push({point:t,kind:"dangling",label:"Unresolved Thread",reason:"Thread contains no Resolve or Abandon event by the end of the current timeline.",action:"Review ending scenes and add Resolve or Abandon where appropriate."}),e.health?.isQuestionable&&e.health.resolvePoint&&a.push({point:e.health.resolvePoint,kind:"questionable",label:"Missing Closure",reason:"Resolved without merge, split, or branch.",action:"Verify this thread has sufficient payoff."}),e.health?.isAbandoned&&e.health.abandonPoint&&a.push({point:e.health.abandonPoint,kind:"abandoned",label:"Abandoned Thread",reason:"This plot line was abandoned.",action:"Check this is intentional."});const o=new Map;a.forEach(e=>{const t=`${Math.round(e.point.x)}:${Math.round(e.point.y)}`;o.has(t)||o.set(t,{point:e.point,warnings:[]}),o.get(t).warnings.push(e)}),o.forEach(({point:e,warnings:t})=>((e,t)=>{const a=Math.max(18,(e.radius||12)+8),o=t[0]?.kind||"warning",r=i("g",{class:`plotline-health-marker plotline-health-marker-${o}`}),s=i("title");s.textContent=(e=>e.map(e=>[`Warning: ${e.label}`,`Reason: ${e.reason}`,`Suggested Action: ${e.action}`].join("\n")).join("\n\n"))(t),r.append(s);const l=e.x+a,c=e.y-13;if("questionable"===o){r.append(i("circle",{cx:l,cy:c,r:9}));const e=i("text",{x:l,y:c+4,"text-anchor":"middle"});e.textContent=t.length>1?String(t.length):"?",r.append(e)}else if(r.append(i("circle",{cx:l,cy:c,r:10})),r.append(i("path",{d:`M ${l} ${c-6} L ${l+6} ${c+5} L ${l-6} ${c+5} Z`})),r.append(i("line",{x1:l,y1:c-2,x2:l,y2:c+2.5})),r.append(i("circle",{cx:l,cy:c+5.3,r:1.2})),t.length>1){const e=i("text",{x:l+11,y:c-6,"text-anchor":"middle",class:"plotline-health-count"});e.textContent=String(t.length),r.append(e)}n.append(r)})(e,t))})})},A=(e,t)=>{document.querySelectorAll(`[data-collapse-body='${CSS.escape(e)}']`).forEach(e=>{e.classList.toggle("timeline-section-collapsed",t)}),document.querySelectorAll(`[data-collapse-toggle='${CSS.escape(e)}']`).forEach(e=>{e.classList.toggle("is-collapsed",t),e.setAttribute("aria-expanded",String(!t))})};document.querySelectorAll("[data-collapse-toggle]").forEach(e=>{const t=e.dataset.collapseToggle;b||"collapsed"!==e.dataset.collapseDefault||L.add(t);const n=L.has(t);A(t,n),e.addEventListener("click",()=>{const e=!L.has(t);e?L.add(t):L.delete(t),A(t,e),localStorage.setItem(l,JSON.stringify([...L])),M(),window.dispatchEvent(new Event("plotline:timeline-layout-changed"))})}),n?.addEventListener("change",()=>q(n.value)),a?.addEventListener("change",()=>C(a.value)),q(localStorage.getItem(c)||"comfortable"),C(localStorage.getItem(d)||"chapter");const P=(()=>{try{return null!==sessionStorage.getItem(p)}catch{return!1}})();window.requestAnimationFrame(()=>{M(),((e="auto")=>{const t=r?.querySelector("[data-active-chapter='true']");if(!r||!t)return;const n=r.getBoundingClientRect(),a=t.getBoundingClientRect(),o=a.left+a.width/2,i=n.left+n.width/2;(a.left<n.left||a.right>n.right)&&r.scrollBy({left:o-i,behavior:e})})("auto"),P&&(()=>{let e=null;try{e=JSON.parse(sessionStorage.getItem(p)||"null"),sessionStorage.removeItem(p)}catch{try{sessionStorage.removeItem(p)}catch{}return}e&&e.path===window.location.pathname&&window.requestAnimationFrame(()=>{t.scrollLeft=Number(e.workspaceLeft)||0,t.scrollTop=Number(e.workspaceTop)||0;const n=S();(e.containers||[]).forEach(e=>{const t=n[e.index];t&&(t.scrollLeft=Number(e.left)||0,t.scrollTop=Number(e.top)||0)}),window.scrollTo(Number(e.left)||0,Number(e.top)||0)})})()}),window.addEventListener("resize",M),window.addEventListener("plotline:timeline-layout-changed",M);e.addEventListener("click",t=>{if(0!==t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;const n=t.target instanceof Element?t.target:null,a=n?.closest("a[href]");if(!a||!e.contains(a))return;[...new URL(a.href,window.location.href).searchParams.keys()].some(e=>"selectedsceneid"===e.toLowerCase())&&x()},{capture:!0});const T=()=>{const e=o?.value.trim().toLowerCase()||"";let t=null;return s.forEach(n=>{const a=!e||(n.dataset.timelineSearchText||"").toLowerCase().includes(e);n.classList.toggle("search-hit",Boolean(e&&a)),n.classList.toggle("search-dim",Boolean(e&&!a)),!t&&e&&a&&(t=n)}),t};o?.addEventListener("input",T),o?.addEventListener("keydown",e=>{if("Enter"!==e.key)return;const t=T();t&&(e.preventDefault(),k(t.dataset.sceneId))}),i.forEach(e=>{e.addEventListener("change",()=>{e.value&&k(e.value)})}),document.querySelectorAll("[data-jump-scene]").forEach(e=>{e.addEventListener("click",()=>{e.dataset.jumpScene&&k(e.dataset.jumpScene)})}),document.addEventListener("keydown",e=>{const n=document.activeElement?.tagName?.toLowerCase(),r=["input","select","textarea"].includes(n)||document.activeElement?.isContentEditable;if((e.ctrlKey||e.metaKey)&&"f"===e.key.toLowerCase()&&o)return e.preventDefault(),o.focus(),void o.select();if("Escape"===e.key){const e=new URL(window.location.href),t=e.searchParams.has("FocusType")||e.searchParams.has("FocusID");return e.searchParams.delete("FocusType"),e.searchParams.delete("FocusID"),void(t?window.location.href=e.toString():o?.value&&(o.value="",T()))}if(!r){if("ArrowLeft"===e.key||"ArrowRight"===e.key)return e.preventDefault(),void t.scrollBy({left:"ArrowLeft"===e.key?-260:260,behavior:"smooth"});if("+"===e.key||"="===e.key||"-"===e.key){const t=f.indexOf(a?.value||"chapter"),n="-"===e.key?-1:1,o=Math.min(f.length-1,Math.max(0,t+n));C(f[o])}}})})(),(()=>{const e=document.querySelector("[data-timeline-root]"),t=document.querySelector("[data-drag-drop-panel]");if(!t)return;const n=document.querySelector("[data-location-relationship-modal]"),a=n&&window.bootstrap?.Modal?window.bootstrap.Modal.getOrCreateInstance(n):null,o=new Map([...document.querySelectorAll("[data-drag-form]")].map(e=>[e.dataset.dragForm,e])),r=t.querySelector("[data-drag-panel-title]"),i=t.querySelector("[data-drag-panel-kicker]"),s=t.querySelector("[data-drag-panel-summary]"),l=document.querySelector("[data-scene-move-modal]"),c=l&&window.bootstrap?.Modal?window.bootstrap.Modal.getOrCreateInstance(l):null,d=l?.querySelector("[data-scene-move-title]"),p=l?.querySelector("[data-scene-move-summary]"),u=l?.querySelector("[data-scene-move-submit]"),m="plotline.timeline.scroll";let h=null,g=0;const f=(e,t,n)=>{const a=e?.querySelector(`[name='${CSS.escape(t)}']`);a&&(a.value=n??"")},v=e=>e?.selectedOptions?.[0]?.textContent?.trim()||"",y=e=>`“${e||"this scene"}”`,w=(e,t,n,a,o)=>t&&n&&t===n?`Move ${y(e.label)} to this new position within ${n}?`:t&&n?`Move ${y(e.label)} from ${t} to ${n}?`:`Move ${y(e.label)} ${a.toLowerCase()} ${o}?`,b=(e,n,l,m)=>{if("scene"===e)return t.classList.add("d-none"),t.querySelectorAll("[data-drag-form]").forEach(e=>e.classList.add("d-none")),o.get("scene")?.classList.remove("d-none"),d&&(d.textContent=n),p&&(p.textContent=l),u&&u.classList.toggle("d-none",n.toLowerCase().startsWith("cannot")||n.toLowerCase().startsWith("scene already")),void(c?c.show():t.classList.remove("d-none"));o.forEach((t,n)=>t.classList.toggle("d-none",n!==e)),t.classList.remove("d-none"),r.textContent=n,i.textContent=m,s.textContent=l,"location-relationship"===e&&a?a.show():t.scrollIntoView({behavior:"smooth",block:"center"})},L=()=>{a?.hide(),t.classList.add("d-none"),o.forEach(e=>e.classList.add("d-none"))},S=()=>{document.querySelectorAll(".drop-target-active, .drop-before, .drop-after, .chapter-drop-active, .drop-chapter-end").forEach(e=>e.classList.remove("drop-target-active","drop-before","drop-after","chapter-drop-active","drop-chapter-end"))};try{const t=JSON.parse(sessionStorage.getItem(m)||"null");t&&(sessionStorage.removeItem(m),requestAnimationFrame(()=>{const n=e?.querySelector(".timeline-shell");n&&(n.scrollLeft=t.left||0),window.scrollTo({top:t.top||0})}))}catch{sessionStorage.removeItem(m)}const E=e=>{try{const t=JSON.parse(e.dataTransfer.getData("application/json")||"{}");return t.type?t:h||{}}catch{return h||{}}},x=e=>{e.addEventListener("dragstart",t=>((e,t)=>{const n={type:t.dataset.dragType,id:t.dataset.dragId,label:t.dataset.dragLabel||t.textContent.trim()};e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData("application/json",JSON.stringify(n)),e.dataTransfer.setData("text/plain",`${n.type}:${n.id}`),h=n,document.body.classList.add("drag-active",`dragging-${n.type}`),t.classList.add("is-dragging")})(t,e)),e.addEventListener("dragend",()=>{e.classList.remove("is-dragging"),document.body.classList.remove("drag-active","dragging-scene","dragging-character","dragging-asset","dragging-location"),h=null,S()})};document.querySelectorAll("[data-drag-type][draggable='true']").forEach(x),t.querySelectorAll("[data-drag-cancel]").forEach(e=>e.addEventListener("click",L)),o.get("scene")?.addEventListener("submit",()=>{const t=e?.querySelector(".timeline-shell");try{sessionStorage.setItem(m,JSON.stringify({left:t?.scrollLeft||0,top:window.scrollY||0}))}catch{}}),e?.querySelectorAll(".timeline-scene-card[data-scene-id]").forEach(t=>{t.addEventListener("click",e=>{Date.now()<g&&(e.preventDefault(),e.stopPropagation())}),t.addEventListener("dragover",e=>{const n=E(e);["scene","character","asset"].includes(n.type)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="scene"===n.type?"move":"copy",t.classList.add("drop-target-active"),t.classList.toggle("drop-before","scene"===n.type&&e.offsetX<t.clientWidth/2),t.classList.toggle("drop-after","scene"===n.type&&e.offsetX>=t.clientWidth/2))}),t.addEventListener("dragleave",()=>t.classList.remove("drop-target-active","drop-before","drop-after")),t.addEventListener("drop",n=>{const a=E(n);if(!["scene","character","asset"].includes(a.type))return;n.preventDefault(),n.stopPropagation(),g=Date.now()+800,t.classList.remove("drop-target-active","drop-before","drop-after");const r=t.dataset.sceneId;if("scene"===a.type){if(a.id===r)return void b("scene","Cannot move scene","Drop a scene before or after a different scene.","Scene move");const i=o.get("scene"),s=n.offsetX<t.clientWidth/2?"Before":"After",l=e.querySelector(`.timeline-scene-card[data-scene-id='${CSS.escape(a.id)}']`),c=l?.dataset.chapterLabel||"",d=t.dataset.chapterLabel||"";return f(i,"SceneID",a.id),f(i,"AnchorSceneID",r),f(i,"TargetChapterID",""),f(i,"Position",s),void b("scene","Move Scene?",w(a,c,d,s,t.dataset.dragLabel),"Scene move")}if("character"===a.type){const e=o.get("character");return f(e,"SceneID",r),f(e,"CharacterID",a.id),void b("character","Add character to scene",`Add ${a.label} to ${t.dataset.dragLabel}.`,"Character drop")}const i=o.get("asset-event");f(i,"SceneID",r),f(i,"StoryAssetID",a.id),f(i,"EventTitle",""),b("asset-event","What happens to this asset?",`Add an event for ${a.label} in ${t.dataset.dragLabel}.`,"Asset drop")})}),e?.querySelectorAll(".timeline-scenes[data-chapter-drop-target]").forEach(t=>{const n=t.closest("[data-chapter-drop-target]"),a=t.dataset.chapterId||n?.dataset.chapterId,r=t.dataset.chapterLabel||n?.dataset.chapterLabel||"this chapter";t.addEventListener("dragover",e=>{"scene"===E(e).type&&a&&(e.target.closest(".timeline-scene-card[data-scene-id]")||(e.preventDefault(),e.dataTransfer.dropEffect="move",t.classList.add("drop-target-active","drop-chapter-end"),n?.classList.add("chapter-drop-active")))}),t.addEventListener("dragleave",e=>{t.contains(e.relatedTarget)||(t.classList.remove("drop-target-active","drop-chapter-end"),n?.classList.remove("chapter-drop-active"))}),t.addEventListener("drop",n=>{const i=E(n);if("scene"!==i.type||!a)return;if(n.target.closest(".timeline-scene-card[data-scene-id]"))return;n.preventDefault(),n.stopPropagation(),g=Date.now()+800,S();const s=e.querySelector(`.timeline-scene-card[data-scene-id='${CSS.escape(i.id)}']`);if(s?.dataset.chapterId===a&&t.lastElementChild?.dataset?.sceneId===i.id)return void b("scene","Scene already here",`${i.label} is already at the end of ${r}.`,"Scene move");const l=o.get("scene");f(l,"SceneID",i.id),f(l,"AnchorSceneID",""),f(l,"TargetChapterID",a),f(l,"Position","End"),b("scene","Move Scene?",w(i,s?.dataset.chapterLabel||"",r,"After",r),"Scene move")})});const I=o.get("asset-dependency"),q=()=>{const e=I?.dataset.sourceLabel||"Source asset",n=I?.dataset.targetLabel||"Target asset",a=v(I?.querySelector("[name='AssetDependencyTypeID']"))||"Requires",o=v(I?.querySelector("[name='SourceRequiredStateID']"))||"the required state",r=v(I?.querySelector("[name='TargetBlockedStateID']"))||"the blocked state",i=t.querySelector("[data-asset-dependency-preview]");i&&(i.textContent=`${e} ${a.toLowerCase()} ${n}. ${e} should be ${o} before ${n} can be ${r}.`)};I?.querySelectorAll("select").forEach(e=>e.addEventListener("change",q)),document.querySelectorAll("[data-asset-drop-target], .drag-chip.asset").forEach(e=>{e.addEventListener("dragover",t=>{"asset"===E(t).type&&(t.preventDefault(),t.dataTransfer.dropEffect="copy",e.classList.add("drop-target-active"))}),e.addEventListener("dragleave",()=>e.classList.remove("drop-target-active")),e.addEventListener("drop",t=>{const n=E(t),a=e.dataset.assetId||e.dataset.dragId,o=e.dataset.assetLabel||e.dataset.dragLabel||e.textContent.trim();"asset"===n.type&&a&&(t.preventDefault(),e.classList.remove("drop-target-active"),n.id!==a?(f(I,"SourceAssetID",n.id),f(I,"TargetAssetID",a),I.dataset.sourceLabel=n.label,I.dataset.targetLabel=o,q(),b("asset-dependency","Create asset dependency",`${n.label} -> ${o}`,"Asset dependency")):b("asset-dependency","Cannot create dependency","Drop one asset onto a different asset.","Asset dependency"))})});const C=document.querySelector("[data-location-reparent-form]"),k=document.querySelector("[data-location-drag-action]"),M=document.querySelector("[data-location-move-error]");let A=new Map([...document.querySelectorAll("[data-drag-type='location']")].map(e=>[e.dataset.dragId,e]));const P=()=>C&&"parent"===k?.value,T=(e,t)=>{const n=A.get(e);if(!n||!A.has(t))return"Choose locations from this page.";if(n.dataset.parentLocationId===t)return"This location already has that parent.";const a=new Set;for(let n=t;n;n=A.get(n)?.dataset.parentLocationId){if(n===e||a.has(n))return"A location cannot be its own parent or be moved beneath one of its descendants.";a.add(n)}return""},$=e=>{e.addEventListener("dragover",t=>{const n=E(t);"location"===n.type&&(t.preventDefault(),t.dataTransfer.dropEffect=P()?T(n.id,e.dataset.dragId)?"none":"move":"copy",e.classList.add("drop-target-active"))}),e.addEventListener("dragleave",()=>e.classList.remove("drop-target-active")),e.addEventListener("drop",t=>{const n=E(t),a=e.dataset.dragId,r=e.dataset.dragLabel||e.textContent.trim();if("location"!==n.type)return;if(t.preventDefault(),D)return;if(e.classList.remove("drop-target-active"),P()){const e=T(n.id,a);if(M&&(M.textContent=e),e)return;const t=A.get(n.id),o=t.dataset.parentLocationName||"top level";return f(C,"locationId",n.id),f(C,"parentLocationId",a),f(C,"expectedParentLocationId",t.dataset.parentLocationId),C.dataset.confirmed="false",C.dataset.confirmMessage=`Change location parent?\n\nMove “${n.label}” from ${o} to “${r}”? Any child locations will move with it.`,window.bootstrap?.Modal&&document.getElementById("plotlineConfirmModal")?(L(),void C.requestSubmit()):void(M&&(M.textContent="Unable to open confirmation. Reload the page or use Edit to change the parent."))}if(n.id===a)return void(M&&(M.textContent="Drop one location onto a different location."));M&&(M.textContent="");const i=document.querySelector("[data-location-relationship-error]");i&&(i.textContent="");const s=o.get("location-relationship");f(s,"FromLocationID",n.id),f(s,"ToLocationID",a),b("location-relationship","Create location relationship",`${n.label} -> ${r}`,"Location drop")})};A.forEach($);let D=!1;const N=document.querySelector("[data-location-move-status]"),R=async(e,t)=>{if(D)return;D=!0;const n={x:window.scrollX,y:window.scrollY},a=t?M:document.querySelector("[data-location-relationship-error]");a&&(a.textContent=""),N&&(N.textContent="Saving…");const o=[...e.querySelectorAll("button[type='submit']")];o.forEach(e=>e.disabled=!0);try{const n=await fetch(e.action,{method:"POST",body:new FormData(e),headers:{"X-Requested-With":"XMLHttpRequest"}});if(!n.ok||n.redirected){const e=await n.json().catch(()=>null);throw new Error(e?.error||"Unable to save. Your session may have expired; reload the page and try again.")}if(t){const e=await n.text(),t=(new DOMParser).parseFromString(e,"text/html").querySelector("[data-location-tree]"),a=document.querySelector("[data-location-tree]");if(!t||!a)throw new Error("Unable to refresh the location tree. Reload the page to check the saved parent.");a.replaceWith(t),A=new Map([...t.querySelectorAll("[data-drag-type='location']")].map(e=>[e.dataset.dragId,e])),A.forEach(e=>{x(e),$(e)})}else await n.json(),L();N&&(N.textContent=t?"Location moved to its new parent.":"Location relationship saved.")}catch(e){a&&(a.textContent=e.message||"Unable to save. Please try again."),N&&(N.textContent="")}finally{D=!1,o.forEach(e=>e.disabled=!1),e.dataset.confirmed="false",requestAnimationFrame(()=>(e=>{const t=document.documentElement.style.scrollBehavior;document.documentElement.style.scrollBehavior="auto",window.scrollTo(e.x,e.y),document.documentElement.style.scrollBehavior=t})(n))}};if(C?.addEventListener("submit",e=>{"true"===C.dataset.confirmed&&(e.preventDefault(),R(C,!0))}),a){const e=o.get("location-relationship");e?.addEventListener("submit",t=>{t.preventDefault(),R(e,!1)})}})(); |