aboutsummaryrefslogtreecommitdiffhomepage
path: root/scripts/park-editor.html
blob: 868a5101809fce339284bab841398b2008db92d2 (plain)
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
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>公園・施設データ編集</title>
<style>
  :root { color-scheme: light dark; }
  body { font-family: system-ui, -apple-system, "Hiragino Kaku Gothic ProN", sans-serif; margin: 0; }
  header { position: sticky; top: 0; background: Canvas; border-bottom: 1px solid #9995; padding: .45rem .75rem; z-index: 20; }
  .head-row { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; }
  header h1 { font-size: 1rem; margin: 0 .5rem 0 0; }
  #q { padding: .3rem .5rem; }
  #count { font-size: .85rem; opacity: .7; }
  #save { padding: .35rem .9rem; font-weight: bold; }
  #status { font-size: .85rem; }
  #tabs { display: flex; gap: .3rem; flex-wrap: wrap; margin-top: .45rem; }
  #tabs button { padding: .3rem .7rem; border: 1px solid #9996; border-radius: 999px; background: transparent; color: inherit; cursor: pointer; font: inherit; font-size: .85rem; }
  #tabs button.active { background: #3b82f6; border-color: #3b82f6; color: #fff; }
  #warning { margin: 0; padding: .35rem .75rem; background: #ff9d0022; border-bottom: 1px solid #9995; font-size: .8rem; }
  .wrap { overflow: auto; height: calc(100vh - 7.4rem); }
  table { border-collapse: collapse; font-size: .8rem; }
  th, td { border: 1px solid #9994; padding: 0; }
  th { position: sticky; top: 0; background: Canvas; padding: .25rem .4rem; white-space: nowrap; z-index: 5; }
  td { padding: 0; }
  td input { width: 100%; box-sizing: border-box; border: none; padding: .25rem .35rem; font: inherit; background: transparent; color: inherit; }
  td input:focus { outline: 2px solid #3b82f6; }
  tr.dirty td { background: #ff9d0033; }
  tr[hidden] { display: none; }
  td.rownum { padding: 0 .4rem; text-align: right; opacity: .5; }
  td.mapcell { text-align: center; }
  td.mapcell a { text-decoration: none; padding: 0 .4rem; cursor: pointer; }
</style>
</head>
<body>
<header>
  <div class="head-row">
    <h1>公園・施設データ編集</h1>
    <input id="q" placeholder="絞り込み(名称・住所・備考など)" size="24">
    <span id="count"></span>
    <button id="save">保存</button>
    <button id="revert">再読込</button>
    <span id="status"></span>
  </div>
  <nav id="tabs"></nav>
</header>
<p id="warning" hidden></p>
<div class="wrap"><table id="tbl"><thead></thead><tbody></tbody></table></div>
<script>
const FIELD = (key, label) => ({ key, label });

const DATASETS = {
  parks: {
    label: "市内公園",
    fields: [
      FIELD("公園名", "公園名"), FIELD("住所", "住所"), FIELD("町名", "町名"),
      FIELD("面積㎡", "面積㎡"), FIELD("500㎡以上", "500㎡以上"), FIELD("種別", "種別"),
      FIELD("南西部指定管理", "南西部指定管理"), FIELD("設置者", "設置者"), FIELD("状態", "状態"),
      FIELD("トイレ", "トイレ"), FIELD("水飲み場", "水飲み場"), FIELD("ベンチ・椅子", "ベンチ・椅子"),
      FIELD("テーブル", "テーブル"), FIELD("パーゴラ", "パーゴラ"), FIELD("東屋", "東屋"),
      FIELD("防災用具", "防災用具"), FIELD("ボール遊び", "ボール遊び"), FIELD("遊具", "遊具"),
      FIELD("緯度", "緯度"), FIELD("経度", "経度"), FIELD("備考", "備考"),
    ],
  },
  nearbyParks: {
    label: "周辺の公園",
    warning: "周辺の公園は update-nearby-parks.py で再生成すると上書きされます。編集内容は別途保存してください。",
    fields: [
      FIELD("name", "名称"), FIELD("city", "市"), FIELD("distance_m", "距離(m)"),
      FIELD("area_m2", "面積(㎡)"), FIELD("note", "備考"),
      FIELD("osm_type", "OSM種別"), FIELD("osm_id", "OSM ID"),
      FIELD("name_source", "名称の出所"),
    ],
  },
  facilities: {
    label: "市内の公共施設",
    fields: [
      FIELD("name", "名称"), FIELD("type", "種別"), FIELD("address", "住所"),
      FIELD("hours", "開館時間"), FIELD("closed", "休館日"), FIELD("toilet", "トイレ"),
      FIELD("water", "給水"), FIELD("note", "備考"), FIELD("source", "出典URL"),
      FIELD("lat", "緯度"), FIELD("lon", "経度"), FIELD("city", "市"),
      FIELD("distance_m", "距離(m)"),
    ],
  },
  nearbyFacilities: {
    label: "周辺の公共施設",
    warning: "周辺の公共施設は update-nearby-facilities.py で再生成すると上書きされます。編集内容は別途保存してください。",
    fields: [
      FIELD("name", "名称"), FIELD("type", "種別"), FIELD("address", "住所"),
      FIELD("hours", "開館時間"), FIELD("closed", "休館日"), FIELD("toilet", "トイレ"),
      FIELD("water", "給水"), FIELD("note", "備考"), FIELD("source", "出典URL"),
      FIELD("lat", "緯度"), FIELD("lon", "経度"), FIELD("city", "市"),
      FIELD("distance_m", "距離(m)"),
    ],
  },
};

const NUMERIC = {
  parks: new Set(),
  nearbyParks: new Set(["distance_m", "area_m2"]),
  facilities: new Set(["lat", "lon", "distance_m"]),
  nearbyFacilities: new Set(["lat", "lon", "distance_m"]),
};

const tbl = document.getElementById("tbl");
const thead = tbl.querySelector("thead");
const tbody = tbl.querySelector("tbody");
const q = document.getElementById("q");
const count = document.getElementById("count");
const statusEl = document.getElementById("status");
const warningEl = document.getElementById("warning");
const tabsEl = document.getElementById("tabs");

let currentId = null;
let data = null;
let rows = [];
let isFC = false;
let fields = [];

function hasDirty() {
  return Boolean(tbody.querySelector("tr.dirty"));
}

function featureCentroid(feature) {
  const g = feature && feature.geometry;
  if (!g) return null;
  if (g.type === "Point") return [g.coordinates[1], g.coordinates[0]];
  const ring = g.type === "Polygon" ? g.coordinates[0] : g.coordinates[0] && g.coordinates[0][0];
  if (!ring || !ring.length) return null;
  let lat = 0;
  let lon = 0;
  for (const [x, y] of ring) {
    lon += x;
    lat += y;
  }
  return [lat / ring.length, lon / ring.length];
}

function mapsUrl(row, props) {
  const lat = props["緯度"] != null && props["緯度"] !== "" ? props["緯度"] : props.lat;
  const lon = props["経度"] != null && props["経度"] !== "" ? props["経度"] : props.lon;
  let query = "";
  if (lat != null && lat !== "" && lon != null && lon !== "") {
    query = `${lat},${lon}`;
  } else if (isFC) {
    const c = featureCentroid(row);
    if (c) query = `${c[0]},${c[1]}`;
  }
  if (!query && props.city && props.name) query = `${props.city}${props.name}`;
  if (!query && props["公園名"]) query = `小平市${props["公園名"]}`;
  if (!query && props.name) query = props.name;
  if (!query) query = "小平市";
  return "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(query);
}

function renderTabs() {
  tabsEl.innerHTML = "";
  Object.entries(DATASETS).forEach(([id, dataset]) => {
    const btn = document.createElement("button");
    btn.type = "button";
    btn.textContent = dataset.label;
    btn.dataset.id = id;
    btn.addEventListener("click", () => {
      if (id === currentId) return;
      if (hasDirty() && !confirm("未保存の変更は破棄されます。よろしいですか?")) return;
      load(id);
    });
    tabsEl.appendChild(btn);
  });
}

function updateTabs() {
  tabsEl.querySelectorAll("button").forEach((btn) => {
    btn.classList.toggle("active", btn.dataset.id === currentId);
  });
}

async function load(id) {
  currentId = id;
  fields = DATASETS[id].fields;
  updateTabs();
  warningEl.hidden = !DATASETS[id].warning;
  warningEl.textContent = DATASETS[id].warning || "";
  statusEl.textContent = "読み込み中…";
  try {
    const res = await fetch("/api/data/" + id, { cache: "no-store" });
    if (!res.ok) throw new Error(await res.text());
    data = await res.json();
    isFC = data.type === "FeatureCollection";
    rows = isFC ? data.features : data;
    render();
    statusEl.textContent = `${DATASETS[id].label}: ${rows.length}件`;
  } catch (e) {
    statusEl.textContent = "読み込みに失敗: " + e.message;
  }
}

function render() {
  thead.innerHTML = "<tr>" + ["#", "地図"].concat(fields.map((f) => f.label)).map((label) => "<th>" + label + "</th>").join("") + "</tr>";
  tbody.innerHTML = "";
  rows.forEach((row, r) => {
    const props = isFC ? row.properties || {} : row;
    const tr = document.createElement("tr");
    const rowNum = document.createElement("td");
    rowNum.className = "rownum";
    rowNum.textContent = String(r + 1);
    tr.appendChild(rowNum);

    const mapTd = document.createElement("td");
    mapTd.className = "mapcell";
    const mapA = document.createElement("a");
    mapA.textContent = "🗺";
    mapA.title = "Googleマップで開く";
    mapA.href = mapsUrl(row, props);
    mapA.target = "_blank";
    mapA.rel = "noopener";
    mapTd.appendChild(mapA);
    tr.appendChild(mapTd);

    fields.forEach((field, c) => {
      const td = document.createElement("td");
      const inp = document.createElement("input");
      inp.value = props[field.key] != null ? props[field.key] : "";
      inp.dataset.r = r;
      inp.dataset.c = c;
      inp.addEventListener("input", () => {
        tr.classList.add("dirty");
        statusEl.textContent = "未保存の変更があります";
      });
      td.appendChild(inp);
      tr.appendChild(td);
    });

    tr.dataset.search = fields.map((f) => String(props[f.key] != null ? props[f.key] : "")).join(" ");
    tbody.appendChild(tr);
  });
  filter();
}

function filter() {
  const s = q.value.trim().toLowerCase();
  let shown = 0;
  Array.prototype.forEach.call(tbody.children, (tr) => {
    const ok = !s || tr.dataset.search.toLowerCase().indexOf(s) >= 0;
    tr.hidden = !ok;
    if (ok) shown++;
  });
  count.textContent = shown + " / " + rows.length + " 件";
}

function collect() {
  Array.prototype.forEach.call(tbody.querySelectorAll("input"), (inp) => {
    const row = rows[Number(inp.dataset.r)];
    const props = isFC ? row.properties || (row.properties = {}) : row;
    const field = fields[Number(inp.dataset.c)];
    let value = inp.value;
    if (NUMERIC[currentId].has(field.key)) {
      const t = value.trim();
      if (t === "") {
        value = null;
      } else {
        const n = Number(t);
        value = Number.isFinite(n) ? n : null;
      }
    }
    props[field.key] = value;
  });
}

document.getElementById("save").onclick = async function () {
  collect();
  statusEl.textContent = "保存中…";
  try {
    const res = await fetch("/api/data/" + currentId, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(data),
    });
    if (res.ok) {
      const result = await res.json();
      statusEl.textContent = `保存しました(${DATASETS[currentId].label} ${result.count}件)。git にコミットを忘れずに。`;
      tbody.querySelectorAll("tr.dirty").forEach((tr) => tr.classList.remove("dirty"));
    } else {
      statusEl.textContent = "保存に失敗: " + (await res.text());
    }
  } catch (e) {
    statusEl.textContent = "保存に失敗: " + e.message;
  }
};

document.getElementById("revert").onclick = function () {
  if (hasDirty() && !confirm("保存していない変更は破棄されます。よろしいですか?")) return;
  load(currentId);
};

q.addEventListener("input", filter);
renderTabs();
load("parks");
</script>
</body>
</html>