| 1 | // Documentos abiertos en Code ↔ sus copias en el recinto («EditorPort»). |
| 2 | // |
| 3 | // El editor de la página es el de siempre (Monaco 0.52 de ide.js); este |
| 4 | // módulo solo ESCUCHA sus modelos y manda al recinto lo justo para que las |
| 5 | // extensiones trabajen: los documentos abiertos como file:///<ruta del |
| 6 | // proyecto> (sin nombre de proyecto ni ruta absoluta), la selección activa y |
| 7 | // cada cambio con su versión. La página manda siempre: |
| 8 | // |
| 9 | // · cambio en la página → doc.change {base, v, changes}; si el recinto no |
| 10 | // tiene esa base, pide doc.need y se le manda doc.reset (texto entero). |
| 11 | // · cambio de una extensión → doc.edit {base, steps}: se aplica SOLO si es el |
| 12 | // documento activo y su versión sigue siendo base, como un único paso de |
| 13 | // deshacer; se contesta doc.ack. Si no, se descarta (doc.reset + aviso). |
| 14 | // · lo que escribe el agente (setValue) → doc.reset. |
| 15 | // |
| 16 | // Ningún fichero se guarda desde aquí: guardar sigue siendo Cmd+S → code.write. |
| 17 | import * as code from '../tools/code.js'; |
| 18 | import { range as validRange } from './convert.js'; |
| 19 | |
| 20 | const MAX_DOC = 5 * 1024 * 1024; |
| 21 | |
| 22 | export class EditorPort { |
| 23 | // openTabs(): [[ruta, modelo]] de las pestañas de ide.js (las que ya |
| 24 | // estaban abiertas al arrancar el recinto también se ven, como en VS Code) |
| 25 | constructor({ monaco, editor, post, notify = () => {}, maxBytes = MAX_DOC, openTabs = () => [] }) { |
| 26 | this.monaco = monaco; |
| 27 | this.editor = editor; |
| 28 | this.post = post; |
| 29 | this.notify = notify; |
| 30 | this.maxBytes = maxBytes; |
| 31 | this.openTabs = openTabs; |
| 32 | this.byModel = new Map(); // model → { uri, path, v, subs } |
| 33 | this.byUri = new Map(); // uri → model |
| 34 | this.applying = null; |
| 35 | this.subs = []; |
| 36 | this.selTimer = null; |
| 37 | this.tooBig = new Set(); |
| 38 | } |
| 39 | |
| 40 | start() { |
| 41 | const ed = this.editor; |
| 42 | this.subs.push(ed.onDidChangeModel(() => { this.track(ed.getModel()); this.sendActive(); })); |
| 43 | this.subs.push(ed.onDidChangeCursorSelection(() => { |
| 44 | clearTimeout(this.selTimer); |
| 45 | this.selTimer = setTimeout(() => this.sendActive(), 80); |
| 46 | })); |
| 47 | // Todas las pestañas abiertas, no solo la activa: una extensión que |
| 48 | // arranca con el lenguaje de un documento (onLanguage) lo ve aunque se |
| 49 | // abriera antes que el recinto, y sin que el usuario vuelva a esa pestaña. |
| 50 | let tabs = []; |
| 51 | try { tabs = this.openTabs() || []; } catch { tabs = []; } |
| 52 | for (const [path, model] of tabs) if (model !== ed.getModel()) this.track(model, path); |
| 53 | this.track(ed.getModel()); |
| 54 | this.sendActive(); |
| 55 | } |
| 56 | |
| 57 | uriFor(path) { return this.monaco.Uri.file('/' + path.replace(/^\/+/, '')).toString(); } |
| 58 | uriOf(model) { return this.byModel.get(model)?.uri || null; } |
| 59 | pathOf(model) { return this.byModel.get(model)?.path || null; } |
| 60 | modelForUri(uri) { const m = this.byUri.get(uri); return m && !m.isDisposed() ? m : null; } |
| 61 | isMirrored(model) { return this.byModel.has(model); } |
| 62 | |
| 63 | // El modelo que acaba de entrar en el editor: su ruta es el fichero actual |
| 64 | // de Code (ide.js la fija justo antes de setModel), o la de su pestaña al |
| 65 | // arrancar. Sin ruta (el estado vacío, el chat) no se manda nada. |
| 66 | track(model, path = code.current().currentFile) { |
| 67 | if (!model || model.isDisposed() || this.byModel.has(model)) return; |
| 68 | if (typeof path !== 'string' || !path) return; |
| 69 | const uri = this.uriFor(path); |
| 70 | if (this.byUri.has(uri) && this.byUri.get(uri) !== model) this.untrack(this.byUri.get(uri)); |
| 71 | const text = model.getValue(); |
| 72 | if (text.length > this.maxBytes) { |
| 73 | if (!this.tooBig.has(uri)) { this.tooBig.add(uri); this.notify('big', path); } |
| 74 | return; |
| 75 | } |
| 76 | const st = { uri, path, v: model.getVersionId(), subs: [] }; |
| 77 | this.byModel.set(model, st); |
| 78 | this.byUri.set(uri, model); |
| 79 | this.post({ t: 'doc.open', uri, lang: model.getLanguageId(), text, v: st.v }); |
| 80 | st.subs.push(model.onDidChangeContent(e => this.changed(model, st, e))); |
| 81 | st.subs.push(model.onDidChangeLanguage(() => this.post({ t: 'doc.lang', uri, lang: model.getLanguageId() }))); |
| 82 | st.subs.push(model.onWillDispose(() => this.untrack(model))); |
| 83 | } |
| 84 | |
| 85 | untrack(model) { |
| 86 | const st = this.byModel.get(model); |
| 87 | if (!st) return; |
| 88 | for (const d of st.subs) { try { d.dispose(); } catch { /* — */ } } |
| 89 | this.byModel.delete(model); |
| 90 | if (this.byUri.get(st.uri) === model) this.byUri.delete(st.uri); |
| 91 | this.post({ t: 'doc.close', uri: st.uri }); |
| 92 | } |
| 93 | |
| 94 | changed(model, st, e) { |
| 95 | const base = st.v; |
| 96 | st.v = model.getVersionId(); |
| 97 | if (this.applying === model) return; // eco de un doc.edit: se contesta con doc.ack |
| 98 | if (e.isFlush || e.isEolChange || model.getValueLength() > this.maxBytes) { this.reset(model); return; } |
| 99 | this.post({ t: 'doc.change', uri: st.uri, base, v: st.v, changes: e.changes.map(c => ({ o: c.rangeOffset, l: c.rangeLength, t: c.text })) }); |
| 100 | } |
| 101 | |
| 102 | reset(model) { |
| 103 | const st = this.byModel.get(model); |
| 104 | if (!st) return; |
| 105 | st.v = model.getVersionId(); |
| 106 | this.post({ t: 'doc.reset', uri: st.uri, text: model.getValue(), v: st.v }); |
| 107 | } |
| 108 | |
| 109 | need(uri) { const m = this.modelForUri(uri); if (m) this.reset(m); } |
| 110 | |
| 111 | selections() { |
| 112 | return (this.editor.getSelections() || []).slice(0, 100).map(s => [s.selectionStartLineNumber, s.selectionStartColumn, s.positionLineNumber, s.positionColumn]); |
| 113 | } |
| 114 | |
| 115 | sendActive() { |
| 116 | const model = this.editor.getModel(); |
| 117 | const st = model && this.byModel.get(model); |
| 118 | this.post({ t: 'editor.active', uri: st ? st.uri : null, selections: st ? this.selections() : [], v: st ? st.v : 0 }); |
| 119 | } |
| 120 | |
| 121 | // lo que hace falta para ejecutar un comando sobre el documento activo |
| 122 | activeState() { |
| 123 | const model = this.editor.getModel(); |
| 124 | const st = model && this.byModel.get(model); |
| 125 | return st ? { uri: st.uri, selections: this.selections(), v: st.v } : {}; |
| 126 | } |
| 127 | |
| 128 | // Cambio que hizo una extensión en el recinto. |
| 129 | applyEdit({ uri, base, steps }, { onTouched = () => {} } = {}) { |
| 130 | const model = this.modelForUri(uri); |
| 131 | if (!model) return; |
| 132 | const active = this.editor.getModel() === model; |
| 133 | if (!active || model.getVersionId() !== base) { |
| 134 | this.reset(model); |
| 135 | this.notify('discarded', this.pathOf(model)); |
| 136 | return; |
| 137 | } |
| 138 | const prepared = []; |
| 139 | for (const step of steps) { |
| 140 | const edits = []; |
| 141 | for (const c of step) { |
| 142 | const r = validRange(this.monaco, model, c.range); |
| 143 | if (!r || typeof c.text !== 'string') { this.reset(model); return; } |
| 144 | edits.push({ range: r, text: c.text, forceMoveMarkers: true }); |
| 145 | } |
| 146 | prepared.push(edits); |
| 147 | } |
| 148 | const st = this.byModel.get(model); |
| 149 | this.applying = model; |
| 150 | try { |
| 151 | this.editor.pushUndoStop(); |
| 152 | for (const edits of prepared) this.editor.executeEdits('x2', edits); |
| 153 | this.editor.pushUndoStop(); |
| 154 | } finally { this.applying = null; } |
| 155 | st.v = model.getVersionId(); |
| 156 | this.post({ t: 'doc.ack', uri, v: st.v }); |
| 157 | onTouched(model); |
| 158 | } |
| 159 | |
| 160 | dispose() { |
| 161 | clearTimeout(this.selTimer); |
| 162 | for (const d of this.subs) { try { d.dispose(); } catch { /* — */ } } |
| 163 | this.subs = []; |
| 164 | for (const [model, st] of this.byModel) for (const d of st.subs) { try { d.dispose(); } catch { /* — */ } } |
| 165 | this.byModel.clear(); |
| 166 | this.byUri.clear(); |
| 167 | } |
| 168 | } |