/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */
import f from"@typo3/core/document-service.js";import{StreamLanguage as g,LanguageSupport as d,syntaxTree as p}from"@codemirror/language";import{TypoScriptStreamParserFactory as y}from"@typo3/backend/code-editor/stream-parser/typoscript.js";import{TsCodeCompletion as h}from"@typo3/backend/code-editor/autocomplete/ts-code-completion.js";function C(){const e=g.define(new y().create()),t=e.data.of({autocomplete:u});return new d(e,[t])}const D=(async()=>{await f.ready();const e=parseInt(document.querySelector('input[name="effectivePid"]')?.value,10);return new h(e)})();async function u(e){if(!e.explicit)return null;const t=k(e),s=e.pos-(t.completingAfterDot?1:0),n=p(e.state).resolveInner(s,-1),r=n.name==="Document"||t.completingAfterDot?"":e.state.sliceDoc(n.from,s),o=n.name==="Document"||t.completingAfterDot?e.pos:n.from;let i={start:n.from,end:s,string:r,type:n.name};/^[\w$_]*$/.test(r)||(i={start:e.pos,end:e.pos,string:"",type:r==="."?"property":null}),t.token=i;const l=(await D).refreshCodeCompletion(t);if((n.name==="string"||n.name==="comment")&&w(r,l))return null;const m=T(r,l);return{from:o,options:m.map(a=>({label:a,type:"keyword"}))}}function k(e){const t=e.state.sliceDoc().split(e.state.lineBreak).length,s=e.state.sliceDoc(0,e.pos).split(e.state.lineBreak).length,n=e.state.sliceDoc().split(e.state.lineBreak)[s-1],o=e.state.sliceDoc(e.pos-1,e.pos)===".";return{lineTokens:S(t,e),currentLineNumber:s,currentLine:n,lineCount:t,completingAfterDot:o}}function S(e,t){const s=Array(e).fill("").map(()=>[]);let n=0,r=1;return p(t.state).cursor().iterate(o=>{const i=o.type.name||o.name;if(i==="Document")return;const c=o.from,l=o.to;n<c&&t.state.sliceDoc(n,c).split(t.state.lineBreak).forEach(a=>{a&&(s[Math.min(r-1,e-1)].push({type:null,string:a,start:n,end:n+a.length}),r++,n+=a.length)});const m=t.state.sliceDoc(o.from,o.to);r=t.state.sliceDoc(0,o.from).split(t.state.lineBreak).length,s[r-1].push({type:i,string:m,start:c,end:l}),n=l}),n<t.state.doc.length&&s[r-1].push({type:null,string:t.state.sliceDoc(n),start:n,end:t.state.doc.length}),s}function w(e,t){const s=e.length;for(let n=0;n<t.length;++n)if(e===t[n].substr(s))return!0;return!1}function T(e,t){const s=new Set,n=o=>{o.lastIndexOf(e,0)===0&&!s.has(o)&&s.add(o)};for(let o=0,i=t.length;o<i;++o)n(t[o]);const r=Array.from(s);return r.sort(),r}export{u as complete,C as typoscript};
