File size: 18,458 Bytes
e3bf1a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9ee24c
 
 
 
 
 
 
 
 
 
 
 
 
 
e3bf1a6
f9ee24c
 
e3bf1a6
f9ee24c
e3bf1a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
  <link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css"/>
  <style>
    :root{
      --panel-w: 260px;
      --toolbar-h: 44px;
      --border:#e5e7eb;
      --muted:#6b7280;
      --toggle-size: 32px;
      --seam-overlap: 6px;  /* how much the button overlaps the map when panel is open */
      --edge-gap: 8px;      /* gap from map edge when panel is closed (fully visible) */
    }
    html,body{margin:0;padding:0;height:100%;font:13px/1.4 system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,Noto Sans,Arial;}
    .page{height:100vh;display:flex;flex-direction:column;}
    .toolbar{height:var(--toolbar-h);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:8px;padding:0 12px;background:#fff}
    .toolbar h1{font-size:14px;margin:0;margin-right:auto;color:#111827}
    .btn{padding:6px 10px;border:1px solid var(--border);border-radius:8px;background:#fff;cursor:pointer}
    .btn.primary{background:#111827;color:#fff;border-color:#111827}

    .content{flex:1;min-height:0;display:flex;position:relative;background:#fff;overflow:visible;}
    
    /* Position the toggle based on panel state */
    .content.panel-open  .seam-toggle{
      right: var(--edge-gap);
    }
    .content.panel-closed .seam-toggle{
      /* fully visible near the right map edge */
      right: var(--edge-gap);
    }

    .mapwrap{position:relative;flex:1 1 auto;min-width:0;overflow:visible;}
    #map{position:absolute;inset:0}

    /* Seam toggle lives above map panes so it never vanishes */
    .seam-toggle{
      position:absolute; top:10px; z-index:1200;
      width:var(--toggle-size); height:var(--toggle-size);
      border-radius:50%; border:2px solid #111827; background:#fff;
      display:flex; align-items:center; justify-content:center;
      box-shadow:0 2px 6px rgba(0,0,0,.15); cursor:pointer;
      transition:right .2s ease, transform .2s ease, background .2s ease, border-color .2s ease;
    }
    .seam-toggle:hover{ background:#f3f4f6; }
    .seam-toggle svg{ width:18px; height:18px; stroke:#111827; stroke-width:2; fill:none; transition:transform .2s ease; }
    .content.panel-closed .seam-toggle svg{ transform:rotate(180deg); }

    /* Panel */
    .panel{
      position:relative;width:var(--panel-w);min-width:var(--panel-w);
      border-left:1px solid var(--border);background:#fff;
      display:flex;flex-direction:column;transition:width .2s ease,min-width .2s ease,border-color .2s ease,background .2s ease;
      overflow:visible;
    }
    .panel-inner{display:flex;flex-direction:column;height:100%;overflow:auto;min-height:0;}
    .panel header{padding:10px 12px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:8px}
    .panel header h2{font-size:13px;margin:0;color:#111827}
    .panel .section{padding:12px;border-bottom:1px solid var(--border)}
    .panel label{display:block;font-size:12px;color:var(--muted);margin-top:8px}
    .panel input,.panel select,.panel textarea{width:100%;box-sizing:border-box;margin-top:4px;padding:6px 8px;border:1px solid var(--border);border-radius:8px;background:#fff}
    .grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}

    .legend{position:absolute;bottom:12px;left:12px;background:#fff;border:1px solid var(--border);border-radius:8px;padding:8px 10px;box-shadow:0 1px 2px rgba(0,0,0,.06);font-size:12px}
    .legend .row{display:flex;align-items:center;gap:8px;margin-top:4px}
    .legend .swatch{width:14px;height:14px;border-radius:3px;border:1px solid #0001}

    .note{color:#92400e;background:#fef3c7;border:1px solid #fde68a;padding:8px;border-radius:8px;margin:8px 12px 0}
    .toast{position:fixed;right:16px;bottom:16px;background:#111827;color:#fff;padding:10px 12px;border-radius:8px;opacity:0;transform:translateY(8px);transition:all .2s ease}
    .toast.show{opacity:1;transform:translateY(0)}
    .leaflet-container{font:inherit}

    /* Collapsed panel */
    .panel.collapsed{width:0;min-width:0;border-left-color:transparent;background:transparent;}
    .panel.collapsed .panel-inner{display:none}
  </style>
</head>
<body>
  <div class="page">
    <div class="toolbar">
      <h1>Bike Paths Editor</h1>
      <button id="btnSaveServer" class="btn primary">Save</button>
      <button id="btnDownload" class="btn">Download</button>
      <div style="color:var(--muted);">Editing <code>bike_paths.geojson</code></div>
    </div>

    <div class="content panel-open" id="content">
      <div class="mapwrap">
        <div id="map"></div>

        <!-- Toggle anchored to map (not inside panel) so it never gets clipped -->
        <button id="seamToggle" class="seam-toggle" aria-label="Collapse properties" title="Toggle properties">
          <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M10 6l6 6-6 6"/></svg>
        </button>

        <div class="legend">
          <div><strong>STATO</strong></div>
          <div class="row"><span class="swatch" style="background:#1a9850"></span> excellent</div>
          <div class="row"><span class="swatch" style="background:#66bd63"></span> good</div>
          <div class="row"><span class="swatch" style="background:#f59e0b"></span> satisfactory</div>
          <div class="row"><span class="swatch" style="background:#d73027"></span> bad</div>
        </div>
      </div>

      <aside class="panel" id="propPanel" aria-expanded="true">
        <div class="panel-inner">
          <header><h2>Properties</h2></header>
          <div id="noSelection" class="section">
            <div class="note">Click a path to edit properties. Missing <code>STATO</code> defaults to <em>satisfactory</em>.</div>
          </div>

          <div id="editor" style="display:none;">
            <div class="section">
              <div class="grid">
                <div><label>ID</label><input id="fld_ID" type="number" placeholder="53"></div>
                <div><label>_fid</label><input id="fld__fid" type="text" placeholder="auto"></div>
              </div>
              <label>TRATTO</label><input id="fld_TRATTO" type="text" placeholder="VIA FRANCESCO CRISPI">
              <label>TIPOLOGIA</label>
              <select id="fld_TIPOLOGIA">
                <option value="">—</option>
                <option>BIDIREZIONALE</option>
                <option>MONODIREZIONALE AMBO I LATI</option>
                <option>MONODIREZIONALE</option>
              </select>
              <label>STATO</label>
              <select id="fld_STATO">
                <option>excellent</option><option>good</option><option selected>satisfactory</option><option>bad</option>
              </select>
              <label>ORDINANAZA</label><input id="fld_ORDINANAZA" type="text" placeholder="438 DEL 06/05/2011">
              <div class="grid">
                <div><label>ANNO_ISTIT</label><input id="fld_ANNO_ISTIT" type="number" placeholder="2000"></div>
                <div><label>IST_OD_PGT</label><input id="fld_IST_OD_PGT" type="number" placeholder="2015"></div>
              </div>
              <label>DISTANZA__</label><input id="fld_DISTANZA__" type="text" placeholder="1244.86">
              <label>OD_ZA_PGTU</label><input id="fld_OD_ZA_PGTU" type="text" placeholder="667 DEL 22/05/2015">
              <label>Attiva</label>
              <select id="fld_Attiva">
                <option value="">null</option><option>true</option><option>false</option>
              </select>
            </div>
            <div class="section">
              <label>Other properties (JSON)</label>
              <textarea id="fld_extra" rows="6" placeholder='{"custom_key":"value"}'></textarea>
              <div style="color:var(--muted);">Only keys not listed above appear here.</div>
            </div>
            <div class="section">
              <button id="btnApply" class="btn primary" style="width:100%;">Apply changes to feature</button>
            </div>
          </div>
        </div>
      </aside>
    </div>
  </div>

  <div id="toast" class="toast">Saved.</div>

  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
  <script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
  <script>
    const DEFAULT_CENTER = [38.1157, 13.3615];
    const DEFAULT_ZOOM = 12;

    const CITY_BOUNDS = L.latLngBounds(
      [37.987, 12.918],  // SW
      [38.226, 13.646]   // NE
    );

    const map = L.map('map', {
      center: DEFAULT_CENTER,
      zoom: DEFAULT_ZOOM,
      maxBounds: CITY_BOUNDS,        // clamp pan
      maxBoundsViscosity: 1.0,       // “sticky” edge; try 0.6–1.0
      minZoom: 10,                   // optional: don’t zoom too far out
      worldCopyJump: false           // avoid wrap-around jumping
    });
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    
    L.control.scale().addTo(map);

    // Bright orange for "satisfactory"
    const COLOR_BY_STATO = { excellent:'#1a9850', good:'#66bd63', satisfactory:'#f59e0b', bad:'#d73027' };
    const colorForStato = s => COLOR_BY_STATO[String(s||'satisfactory').toLowerCase().trim()] || COLOR_BY_STATO.satisfactory;
    const styleForFeature = f => ({ color: colorForStato(f?.properties?.STATO), weight:4, opacity:.9 });

    const drawnItems = new L.FeatureGroup(); map.addLayer(drawnItems);
    const drawControl = new L.Control.Draw({
      draw:{ polygon:true, polyline:true, rectangle:true, circle:false, marker:true, circlemarker:false },
      edit:{ featureGroup: drawnItems }
    });
    map.addControl(drawControl);

    let fcState = { type:'FeatureCollection', features: [] };
    const fidIndex = new Map();

    function ensureDefaults(f){
      f.properties ||= {};
      if (!('STATO' in f.properties) || !f.properties.STATO) f.properties.STATO = 'satisfactory';
      if (!('_fid' in f.properties) || !f.properties._fid)
        f.properties._fid = (crypto.randomUUID ? crypto.randomUUID() : ('fid_'+Math.random().toString(36).slice(2)));
    }
    function indexFeature(f){
      ensureDefaults(f);
      const fid = f.properties._fid;
      const i = fcState.features.findIndex(x => x?.properties?._fid === fid);
      if (i >= 0) fcState.features[i] = f; else fcState.features.push(f);
      fidIndex.set(fid, f); return f;
    }
    function upsertFromLayer(layer, {replaceGeometryOnly=false}={}){
      const gj = layer.toGeoJSON(); ensureDefaults(gj);
      const existing = fidIndex.get(gj.properties._fid);
      if (existing && replaceGeometryOnly){ existing.geometry = gj.geometry; layer.feature = existing; }
      else { const stored = indexFeature(gj); layer.feature = stored; }
    }
    function removeByLayer(layer){
      const fid = (layer.feature||{}).properties?._fid || layer.toGeoJSON().properties?._fid;
      if (!fid) return;
      fcState.features = fcState.features.filter(f => f.properties._fid !== fid);
      fidIndex.delete(fid);
    }

    function buildLayer(fc){
      fcState = { type:'FeatureCollection', features: [] };
      fidIndex.clear();
      drawnItems.clearLayers();

      const collection = (fc?.type === 'FeatureCollection' && Array.isArray(fc.features)) ? fc.features : [];
      collection.forEach((f) => {
        ensureDefaults(f);
        const stored = indexFeature(f);
        const lyr = L.geoJSON(stored, { style: styleForFeature }).getLayers()[0];
        if (lyr){ lyr.feature = stored; bindFeatureEvents(lyr); drawnItems.addLayer(lyr); }
      });
      try { const b = drawnItems.getBounds(); if (b && b.isValid()) map.fitBounds(b, { padding:[20,20] }); } catch(e){}
    }

    function bindFeatureEvents(layer){ layer.on('click', () => { currentLayer = layer; openEditorFor(layer); }); }

    map.on(L.Draw.Event.CREATED, e => { const layer = e.layer; upsertFromLayer(layer); drawnItems.addLayer(layer); bindFeatureEvents(layer); });
    map.on(L.Draw.Event.EDITED, e => { e.layers.eachLayer(l => upsertFromLayer(l, {replaceGeometryOnly:true})); flash('Updated geometry'); });
    map.on(L.Draw.Event.DELETED, e => { e.layers.eachLayer(l => removeByLayer(l)); flash('Deleted features'); });

    let currentLayer = null;
    const noSelection = document.getElementById('noSelection');
    const editor = document.getElementById('editor');
    const fld_ID = document.getElementById('fld_ID');
    const fld__fid = document.getElementById('fld__fid');
    const fld_TRATTO = document.getElementById('fld_TRATTO');
    const fld_TIPOLOGIA = document.getElementById('fld_TIPOLOGIA');
    const fld_STATO = document.getElementById('fld_STATO');
    const fld_ORDINANAZA = document.getElementById('fld_ORDINANAZA');
    const fld_ANNO_ISTIT = document.getElementById('fld_ANNO_ISTIT');
    const fld_DISTANZA__ = document.getElementById('fld_DISTANZA__');
    const fld_OD_ZA_PGTU = document.getElementById('fld_OD_ZA_PGTU');
    const fld_IST_OD_PGT = document.getElementById('fld_IST_OD_PGT');
    const fld_Attiva = document.getElementById('fld_Attiva');
    const fld_extra = document.getElementById('fld_extra');
    const btnApply = document.getElementById('btnApply');
    const btnSaveServer = document.getElementById('btnSaveServer');
    const btnDownload = document.getElementById('btnDownload');
    const toast = document.getElementById('toast');

    function openEditorFor(layer){
      const f = layer.feature || layer.toGeoJSON(); ensureDefaults(f);
      noSelection.style.display = 'none'; editor.style.display = '';
      fld_ID.value = f.properties.ID ?? '';
      fld__fid.value = f.properties._fid ?? '';
      fld_TRATTO.value = f.properties.TRATTO ?? '';
      fld_TIPOLOGIA.value = f.properties.TIPOLOGIA ?? '';
      const stato = String(f.properties.STATO ?? 'satisfactory').toLowerCase();
      fld_STATO.value = ['excellent','good','satisfactory','bad'].includes(stato) ? stato : 'satisfactory';
      fld_ORDINANAZA.value = f.properties.ORDINANAZA ?? '';
      fld_ANNO_ISTIT.value = f.properties.ANNO_ISTIT ?? '';
      fld_DISTANZA__.value = f.properties.DISTANZA__ ?? '';
      fld_OD_ZA_PGTU.value = f.properties.OD_ZA_PGTU ?? '';
      fld_IST_OD_PGT.value = f.properties.IST_OD_PGT ?? '';
      fld_Attiva.value = (f.properties.Attiva === true) ? 'true' : (f.properties.Attiva === false) ? 'false' : '';
      const known = new Set(['ID','TRATTO','TIPOLOGIA','STATO','ORDINANAZA','ANNO_ISTIT','DISTANZA__','OD_ZA_PGTU','IST_OD_PGT','Attiva','_fid']);
      const extras = {}; Object.entries(f.properties).forEach(([k,v]) => { if(!known.has(k)) extras[k]=v; });
      fld_extra.value = Object.keys(extras).length ? JSON.stringify(extras, null, 2) : '';
    }

    function applyChanges(){
      if(!currentLayer) return;
      const f = currentLayer.feature || currentLayer.toGeoJSON(); f.properties ||= {};
      const n = v => (v===''||v==null) ? null : (Number.isFinite(+v) ? +v : v);
      f.properties.ID = n(fld_ID.value);
      f.properties._fid = fld__fid.value || f.properties._fid || (crypto.randomUUID?crypto.randomUUID():('fid_'+Math.random().toString(36).slice(2)));
      f.properties.TRATTO = fld_TRATTO.value || '';
      f.properties.TIPOLOGIA = fld_TIPOLOGIA.value || '';
      f.properties.STATO = fld_STATO.value || 'satisfactory';
      f.properties.ORDINANAZA = fld_ORDINANAZA.value || '';
      f.properties.ANNO_ISTIT = n(fld_ANNO_ISTIT.value);
      f.properties.DISTANZA__ = fld_DISTANZA__.value || '';
      f.properties.OD_ZA_PGTU = fld_OD_ZA_PGTU.value || '';
      f.properties.IST_OD_PGT = n(fld_IST_OD_PGT.value);
      f.properties.Attiva = (fld_Attiva.value==='true') ? true : (fld_Attiva.value==='false') ? false : null;
      if (fld_extra.value.trim()){
        try{ const extras = JSON.parse(fld_extra.value); if (extras && typeof extras === 'object'){ for (const [k,v] of Object.entries(extras)) if (!(k in f.properties)) f.properties[k]=v; } }
        catch(e){ alert('Extras JSON invalid: '+e); }
      }
      indexFeature(f);
      currentLayer.feature = fidIndex.get(f.properties._fid);
      if (currentLayer.setStyle) currentLayer.setStyle(styleForFeature(f));
      flash('Updated feature & local GeoJSON');
    }
    btnApply.addEventListener('click', applyChanges);

    async function saveToServer(){
      try{
        const r = await fetch('/_save_geojson', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(fcState) });
        if(!r.ok) throw new Error('HTTP '+r.status);
        flash('Saved to server');
      }catch(e){ alert('Save failed: '+e.message); }
    }
    btnSaveServer.addEventListener('click', saveToServer);

    function downloadFile(){
      const blob = new Blob([JSON.stringify(fcState,null,2)], {type:'application/geo+json'});
      const url = URL.createObjectURL(blob);
      const a = Object.assign(document.createElement('a'), {href:url, download:'bike_paths.geojson'});
      document.body.appendChild(a); a.click(); setTimeout(()=>{URL.revokeObjectURL(url); a.remove();},0);
    }
    btnDownload.addEventListener('click', downloadFile);

    function flash(text){ const t=toast; t.textContent=text; t.classList.add('show'); setTimeout(()=>t.classList.remove('show'), 1400); }

    // Toggle: update classes on content & panel, ensure map resizes
    const content = document.getElementById('content');
    const propPanel = document.getElementById('propPanel');
    const seamToggle = document.getElementById('seamToggle');
    seamToggle.addEventListener('click', () => {
      const closed = content.classList.toggle('panel-closed');
      content.classList.toggle('panel-open', !closed);
      propPanel.classList.toggle('collapsed', closed);
      propPanel.setAttribute('aria-expanded', String(!closed));
      seamToggle.setAttribute('aria-label', closed ? 'Expand properties' : 'Collapse properties');
      setTimeout(() => map.invalidateSize(), 220);
    });

    // Initial load
    (async () => {
      try{
        const fc = await fetch('/_load_geojson').then(r=>r.json());
        buildLayer(fc);
      }catch(e){
        console.error('Load failed', e);
        buildLayer({type:'FeatureCollection',features:[]});
      }
    })();
  </script>
</body>
</html>