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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
|
<!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:not([type="checkbox"]) { width: 100%; box-sizing: border-box; border: none; padding: .25rem .35rem; font: inherit; background: transparent; color: inherit; }
td input:not([type="checkbox"]):focus { outline: 2px solid #3b82f6; }
tr.dirty td { background: #ff9d0033; }
td input.corrupt { background: #ffebee; box-shadow: inset 0 0 0 2px #e53935; }
#status.has-warning { color: #c62828; font-weight: 700; }
tbody tr.is-focused td { background: #3b82f622 !important; }
tbody tr.is-focused td.rownum { color: #1d4ed8; font-weight: 700; opacity: 1; }
tbody tr.is-focused td:first-child { box-shadow: inset 3px 0 0 #2563eb; }
tbody tr.is-focused td:last-child { box-shadow: inset -3px 0 0 #2563eb; }
tbody tr.is-focused.dirty td.rownum::after {
content: " ●";
color: #f59e0b;
font-size: 0.8em;
}
tr[hidden] { display: none; }
td.rownum { padding: 0 .4rem; text-align: right; opacity: .5; }
td.checkcell { padding: 0 .35rem; text-align: center; white-space: nowrap; }
td.checkcell input[type="checkbox"] { width: auto; height: auto; margin: 0; padding: 0; }
#check-filter { padding: .3rem .4rem; }
.checked-count { font-size: .82rem; opacity: .85; }
.check-note { font-size: .72rem; opacity: .6; }
#clear-checks { padding: .3rem .6rem; }
td.mapcell { text-align: center; }
td.mapcell a { text-decoration: none; padding: 0 .4rem; cursor: pointer; }
th.c-coord, td.c-coord { width: 6ch; min-width: 6ch; max-width: 6ch; overflow: hidden; }
td.c-coord input { width: 6ch; min-width: 0; font-size: .72rem; }
th.c-flag2, td.c-flag2 { width: 2.2em; min-width: 2.2em; max-width: 2.2em; overflow: hidden; }
th.c-flag3, td.c-flag3 { width: 3.2em; min-width: 3.2em; max-width: 3.2em; overflow: hidden; }
th.c-short, td.c-short { width: 3.2em; min-width: 3.2em; max-width: 3.2em; overflow: hidden; }
th.c-shelter, td.c-shelter { width: 5.2em; min-width: 5.2em; max-width: 5.2em; overflow: hidden; }
th.c-ja6, td.c-ja6 { width: 2.2em; min-width: 2.2em; max-width: 2.2em; overflow: hidden; }
th.c-toy, td.c-toy { width: 100pt; min-width: 100pt; max-width: 100pt; box-sizing: border-box; overflow: hidden; }
td.c-toy input:not([type="checkbox"]) {
width: 100pt; min-width: 0; box-sizing: border-box;
padding-left: .1rem; padding-right: .1rem;
}
td.c-flag2 input, td.c-flag3 input, td.c-short input,
td.c-shelter input, td.c-ja6 input {
width: 100%; min-width: 0; padding-left: .1rem; padding-right: .1rem;
}
td.c-flag2 input, td.c-flag3 input, td.c-short input { text-align: center; }
</style>
</head>
<body>
<header>
<div class="head-row">
<h1>公園・施設データ編集</h1>
<input id="q" placeholder="絞り込み(名称・住所・備考など)" size="24">
<span id="count"></span>
<select id="check-filter" title="確認状態で絞り込む">
<option value="">確認: すべて</option>
<option value="done">確認済み</option>
<option value="todo">未確認</option>
</select>
<span id="checked-count" class="checked-count"></span>
<span class="check-note" title="確認チェックはこのブラウザにのみ保存され、JSONには入りません">このブラウザのみ</span>
<button id="clear-checks" title="このデータの確認チェックをすべて外す">確認をクリア</button>
<button id="save">保存</button>
<button id="export-unchecked" title="確認チェックが付いていない行をCSVで保存します(Excel / Googleスプレッドシートで開けます)">未確認CSV</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 TOY_ORDER = [
["swing", "ブランコ"],
["slide", "滑台"],
["sand", "砂場"],
["bar", "鉄棒"],
["spring", "スイング遊具"],
["complex", "複合遊具"],
["other", "その他遊具"],
];
const TOY_TOKENS = {
swing: ["ブランコ", "ぶらんこ"],
slide: ["滑台", "滑り台", "すべり台"],
sand: ["砂場"],
bar: ["鉄棒"],
spring: ["スプリング", "スイング", "ロッキンパッピー"],
complex: ["複合遊具"],
};
const DATASETS = {
parks: {
label: "市内公園",
fields: [
FIELD("公園名", "公園名"), FIELD("住所", "住所"),
FIELD("面積㎡", "面積㎡"), FIELD("種別", "種別"),
FIELD("設置者", "設置者"), FIELD("状態", "状態"),
FIELD("トイレ", "トイレ"), FIELD("水飲み場", "水飲み場"), FIELD("ベンチ・椅子", "ベンチ・椅子"),
FIELD("テーブル", "テーブル"), FIELD("シェルター等", "シェルター<br>パーゴラ<br>東屋"),
FIELD("防災用具", "防災用具"), FIELD("ボール遊び", "ボール<br>遊び"),
...TOY_ORDER.map(([toy, label]) => ({ key: `__toy_${toy}`, label, toy })),
FIELD("草地広場", "草地<br>広場"), FIELD("多目的広場", "多目的<br>広場"),
FIELD("築山", "築山"), FIELD("じゃぶじゃぶ池", "じゃぶ<br>じゃぶ<br>池"),
FIELD("時計", "時計"),
FIELD("緯度", "緯度"), FIELD("経度", "経度"), FIELD("備考", "備考"),
],
},
nearbyParks: {
label: "周辺の公園",
warning: "周辺の公園は update-nearby-parks.py で再生成すると上書きされます。編集内容は別途保存してください。",
fields: [
FIELD("name", "名称"), FIELD("city", "市"), FIELD("distance_m", "距離(m)"),
FIELD("area_m2", "面積(㎡)"), FIELD("時計", "時計"), 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"]),
};
function isInsideParentheses(text, index) {
let depth = 0;
for (let i = 0; i < index; i += 1) {
const ch = text[i];
if (ch === "(" || ch === "(") depth += 1;
else if (ch === ")" || ch === ")") depth = Math.max(0, depth - 1);
}
return depth > 0;
}
function splitToySegment(segment) {
const hits = [];
for (const [key, tokens] of Object.entries(TOY_TOKENS)) {
for (const token of tokens) {
let index = segment.indexOf(token);
while (index !== -1) {
if (!isInsideParentheses(segment, index)) hits.push({ index, key, token });
index = segment.indexOf(token, index + token.length);
}
}
}
hits.sort((a, b) => a.index - b.index || b.token.length - a.token.length);
const unique = [];
for (const hit of hits) {
if (unique.length && hit.index === unique[unique.length - 1].index) continue;
unique.push(hit);
}
if (unique.length <= 1) {
return [{ key: unique[0]?.key || "other", text: segment }];
}
const parts = [];
if (unique[0].index > 0) {
parts.push({ key: "other", text: segment.slice(0, unique[0].index).trim() });
}
unique.forEach((hit, i) => {
const end = i + 1 < unique.length ? unique[i + 1].index : segment.length;
const text = segment.slice(hit.index, end).trim();
if (text) parts.push({ key: hit.key, text });
});
return parts;
}
function splitToySegments(text) {
const segments = [];
let depth = 0;
let start = 0;
for (let i = 0; i < text.length; i += 1) {
const ch = text[i];
if (ch === "(" || ch === "(") depth += 1;
else if (ch === ")" || ch === ")") depth = Math.max(0, depth - 1);
else if (depth === 0 && (ch === "、" || ch === "," || ch === ",")) {
segments.push(text.slice(start, i));
start = i + 1;
}
}
segments.push(text.slice(start));
return segments;
}
function parseToyString(value) {
const parts = Object.fromEntries(TOY_ORDER.map(([key]) => [key, []]));
const text = String(value || "").trim();
if (!text) return parts;
for (const segment of splitToySegments(text)) {
const trimmed = segment.trim();
if (!trimmed) continue;
for (const part of splitToySegment(trimmed)) {
parts[part.key].push(part.text);
}
}
return parts;
}
function toyValuesFor(value) {
const parsed = parseToyString(value);
const out = {};
for (const [key] of TOY_ORDER) out[key] = parsed[key].join("、");
return out;
}
function combineToyParts(parts) {
return TOY_ORDER
.map(([key]) => String(parts[key] || "").trim())
.filter(Boolean)
.join("、");
}
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");
const checkFilter = document.getElementById("check-filter");
const checkedCount = document.getElementById("checked-count");
const clearChecksBtn = document.getElementById("clear-checks");
const STORAGE_KEY = "park-editor-checks-v1";
let currentId = null;
let data = null;
let rows = [];
let isFC = false;
let fields = [];
let checks = {};
function hasDirty() {
return Boolean(tbody.querySelector("tr.dirty"));
}
function loadChecks() {
try {
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
checks = parsed && typeof parsed === "object" ? parsed : {};
} catch {
checks = {};
}
}
function saveChecks() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(checks));
} catch {
// ブラウザの保存が使えない場合でも編集自体は続行できるようにする。
}
}
function rowKey(props, id) {
if (id === "nearbyParks" || id === "nearbyFacilities") {
if (props.osm_type && props.osm_id) return `${props.osm_type}/${props.osm_id}`;
return `${props.name || ""}|${props.city || ""}|${props.address || ""}`;
}
if (id === "facilities") return `${props.name || ""}|${props.address || ""}`;
return `${props["公園名"] || ""}|${props["住所"] || ""}`;
}
function isChecked(id, key) {
return Boolean(checks[id] && checks[id][key]);
}
function setChecked(id, key, value) {
if (!checks[id]) checks[id] = {};
if (value) checks[id][key] = true;
else delete checks[id][key];
saveChecks();
updateCheckedCount();
}
function updateCheckedCount() {
if (!currentId) return;
let done = 0;
rows.forEach((row) => {
const props = isFC ? row.properties || {} : row;
if (isChecked(currentId, rowKey(props, currentId))) done++;
});
checkedCount.textContent = `確認済み ${done} / ${rows.length}件`;
}
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 fixed = String(props["地図URL"] || "").trim();
if (fixed) return fixed;
const name = String(props["公園名"] || props.name || "").trim();
const city =
currentId === "parks" || currentId === "facilities"
? "小平市"
: String(props.city || "").trim();
let query = "";
if (name) {
query = city && !name.startsWith(city) ? `${city}${name}` : name;
}
if (!query) {
const address = String(props["住所"] || props.address || "").trim();
if (address) {
query = city && !address.startsWith(city) ? `${city}${address}` : address;
}
}
if (!query) {
const lat = props["緯度"] != null && props["緯度"] !== "" ? props["緯度"] : props.lat;
const lon = props["経度"] != null && props["経度"] !== "" ? props["経度"] : props.lon;
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) 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();
showCorruptKeys();
statusEl.textContent = `${DATASETS[id].label}: ${rows.length}件`;
} catch (e) {
statusEl.textContent = "読み込みに失敗: " + e.message;
}
}
function render() {
const COL_CLASS = {
緯度: "c-coord",
経度: "c-coord",
草地広場: "c-flag2",
築山: "c-flag2",
多目的広場: "c-flag3",
ボール遊び: "c-short",
シェルター等: "c-shelter",
じゃぶじゃぶ池: "c-ja6",
__toy_swing: "c-toy",
__toy_bar: "c-toy",
};
const headCols = ["#", "確認", "地図"]
.map((label) => ({ label, cls: "" }))
.concat(fields.map((f) => ({ label: f.label, cls: COL_CLASS[f.key] || "" })));
thead.innerHTML =
"<tr>" +
headCols.map((col) => `<th class="${col.cls}">${col.label}</th>`).join("") +
"</tr>";
tbody.innerHTML = "";
rows.forEach((row, r) => {
const props = isFC ? row.properties || {} : row;
const toys = toyValuesFor(props["遊具"]);
const tr = document.createElement("tr");
const rowNum = document.createElement("td");
rowNum.className = "rownum";
rowNum.textContent = String(r + 1);
tr.appendChild(rowNum);
const key = rowKey(props, currentId);
const checkTd = document.createElement("td");
checkTd.className = "checkcell";
const cb = document.createElement("input");
cb.type = "checkbox";
cb.dataset.check = "1";
cb.dataset.key = key;
cb.checked = isChecked(currentId, key);
cb.title = "確認済み(このブラウザにのみ保存)";
cb.addEventListener("change", () => {
setChecked(currentId, key, cb.checked);
tbody.querySelectorAll("input[data-check]").forEach((other) => {
if (other.dataset.key === key) other.checked = cb.checked;
});
filter();
});
checkTd.appendChild(cb);
tr.appendChild(checkTd);
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 colClass = COL_CLASS[field.key];
if (colClass) td.className = colClass;
const inp = document.createElement("input");
inp.value = field.toy ? toys[field.toy] : (props[field.key] != null ? props[field.key] : "");
inp.dataset.r = r;
inp.dataset.c = c;
inp.addEventListener("input", () => {
tr.classList.add("dirty");
inp.classList.toggle("corrupt", inp.value.includes("\uFFFD"));
statusEl.textContent = "未保存の変更があります";
});
td.appendChild(inp);
tr.appendChild(td);
});
tr.dataset.search = fields.map((f) => f.toy ? toys[f.toy] : String(props[f.key] != null ? props[f.key] : "")).join(" ") + " " + String(props["遊具"] || "");
tbody.appendChild(tr);
});
filter();
markCorrupt();
updateCheckedCount();
}
function filter() {
const s = q.value.trim().toLowerCase();
const checkMode = checkFilter ? checkFilter.value : "";
let shown = 0;
Array.prototype.forEach.call(tbody.children, (tr) => {
const cb = tr.querySelector("input[data-check]");
const checked = Boolean(cb && cb.checked);
const okCheck = !checkMode || (checkMode === "done" ? checked : !checked);
const okText = !s || tr.dataset.search.toLowerCase().indexOf(s) >= 0;
const ok = okText && okCheck;
tr.hidden = !ok;
if (ok) shown++;
});
count.textContent = shown + " / " + rows.length + " 件";
}
// 項目名(キー)の文字化けは表に出ないため、バナーで知らせる
function showCorruptKeys() {
const hits = [];
rows.forEach((row, i) => {
const props = isFC ? row.properties || {} : row;
for (const key of Object.keys(props)) {
if (!key.includes("\uFFFD")) continue;
const name = props["公園名"] || props["name"] || props["名称"] || `行${i + 1}`;
hits.push(`${name} / ${key}`);
}
});
if (!hits.length) return;
warningEl.hidden = false;
warningEl.textContent = `文字化けした項目名が ${hits.length} 件あります: ${hits.slice(0, 5).join(" / ")}${hits.length > 5 ? " …" : ""}`;
warningEl.style.background = "#ffcdd2";
warningEl.style.color = "#8e0000";
}
function markCorrupt() {
tbody.querySelectorAll("input[data-r][data-c]").forEach((inp) => {
inp.classList.toggle("corrupt", inp.value.includes("\uFFFD"));
});
}
function corruptInputs() {
return Array.from(tbody.querySelectorAll("input[data-r][data-c]")).filter((inp) =>
inp.value.includes("\uFFFD"),
);
}
function corruptLabel(inp) {
const row = rows[Number(inp.dataset.r)];
const props = isFC ? row.properties || {} : row;
const name =
props["公園名"] || props["name"] || props["名称"] || `行${Number(inp.dataset.r) + 1}`;
const label = fields[Number(inp.dataset.c)].label.replace(/<[^>]+>/g, "");
return `${name} / ${label}: ${inp.value}`;
}
const PARK_EXPORT_HEAD = ["番号", "確認", "メモ", "公園名", "住所", "Googleマップ"];
const PARK_EXPORT_KEYS = [
"町名", "種別", "面積㎡", "設置者", "状態",
"トイレ", "水飲み場", "ベンチ・椅子", "テーブル", "シェルター等",
"草地広場", "多目的広場", "築山", "じゃぶじゃぶ池",
"防災用具", "ボール遊び", "遊具", "時計", "駐車場", "その他設備", "備考",
"緯度", "経度",
];
function csvCell(value) {
const text = value == null ? "" : String(value);
return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
}
// 確認チェックが付いていない行を、Excel / Googleスプレッドシートで編集できるCSVにする。
// 確認・メモの列を先頭に置き、外出先で入力しやすくする。
function exportUncheckedCsv() {
const targets = [];
rows.forEach((row, r) => {
const props = isFC ? row.properties || {} : row;
if (isChecked(currentId, rowKey(props, currentId))) return;
targets.push({ r, row, props });
});
if (!targets.length) {
statusEl.textContent = "未確認の行はありません。";
return;
}
let headers;
let toCells;
if (currentId === "parks") {
headers = [...PARK_EXPORT_HEAD, ...PARK_EXPORT_KEYS];
toCells = ({ row, props }, no) => [
no, "", "",
props["公園名"] ?? "",
props["住所"] ?? "",
mapsUrl(row, props),
...PARK_EXPORT_KEYS.map((key) => props[key] ?? ""),
];
} else {
const cols = fields.filter((field) => !field.toy);
headers = ["番号", ...cols.map((field) => field.label.replace(/<[^>]+>/g, "")), "Googleマップ"];
toCells = ({ row, props }, no) => [
no,
...cols.map((field) => props[field.key] ?? ""),
mapsUrl(row, props),
];
}
const lines = [headers.map(csvCell).join(",")];
targets.forEach((target, index) => {
lines.push(toCells(target, index + 1).map(csvCell).join(","));
});
const csv = "\uFEFF" + lines.join("\r\n") + "\r\n";
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `未確認_${DATASETS[currentId].label}_${new Date().toISOString().slice(0, 10)}.csv`;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
statusEl.textContent = `未確認 ${targets.length} 件をCSVで保存しました(Excel / Googleスプレッドシートで開けます)。`;
}
document.getElementById("export-unchecked").onclick = exportUncheckedCsv;
function collect() {
const toyValues = new Map();
Array.prototype.forEach.call(tbody.querySelectorAll("input[data-r][data-c]"), (inp) => {
const row = rows[Number(inp.dataset.r)];
const props = isFC ? row.properties || (row.properties = {}) : row;
const field = fields[Number(inp.dataset.c)];
if (field.toy) {
let parts = toyValues.get(props);
if (!parts) {
parts = {};
toyValues.set(props, parts);
}
parts[field.toy] = inp.value;
return;
}
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;
});
toyValues.forEach((parts, props) => {
props["遊具"] = combineToyParts(parts);
});
}
document.getElementById("save").onclick = async function () {
const bad = corruptInputs();
if (bad.length) {
const list = bad.slice(0, 20).map((inp) => `・${corruptLabel(inp)}`).join("\n");
const more = bad.length > 20 ? `\n…ほか ${bad.length - 20} 件` : "";
if (!confirm(`文字化け(U+FFFD)が ${bad.length} 件あります。このまま保存しますか?\n\n${list}${more}`)) {
statusEl.textContent = `文字化けが ${bad.length} 件あります(赤い枠のセル)。保存を中止しました。`;
statusEl.classList.add("has-warning");
bad[0].scrollIntoView({ block: "center", behavior: "smooth" });
bad[0].focus();
return;
}
}
collect();
statusEl.textContent = "保存中…";
statusEl.classList.remove("has-warning");
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();
tbody.querySelectorAll("tr.dirty").forEach((tr) => tr.classList.remove("dirty"));
markCorrupt();
if (Array.isArray(result.warnings) && result.warnings.length) {
const list = result.warnings.slice(0, 10).map((w) => `・${w.where}`).join(" / ");
statusEl.textContent = `保存しました(${DATASETS[currentId].label} ${result.count}件)。文字化け ${result.warnings.length} 件: ${list}`;
statusEl.classList.add("has-warning");
} else {
statusEl.textContent = `保存しました(${DATASETS[currentId].label} ${result.count}件)。git にコミットを忘れずに。`;
statusEl.classList.remove("has-warning");
}
} else {
statusEl.textContent = "保存に失敗: " + (await res.text());
statusEl.classList.add("has-warning");
}
} catch (e) {
statusEl.textContent = "保存に失敗: " + e.message;
statusEl.classList.add("has-warning");
}
};
document.getElementById("revert").onclick = function () {
if (hasDirty() && !confirm("保存していない変更は破棄されます。よろしいですか?")) return;
load(currentId);
};
q.addEventListener("input", filter);
checkFilter.addEventListener("change", filter);
tbody.addEventListener("focusin", (event) => {
const target = event.target;
if (!(target instanceof Element)) return;
const tr = target.closest("tr");
if (!tr || !tbody.contains(tr)) return;
tbody.querySelectorAll("tr.is-focused").forEach((row) => {
row.classList.remove("is-focused");
});
tr.classList.add("is-focused");
});
clearChecksBtn.addEventListener("click", () => {
if (!currentId) return;
if (!confirm(`${DATASETS[currentId].label}の確認チェックをすべて外しますか?`)) return;
checks[currentId] = {};
saveChecks();
tbody.querySelectorAll("input[data-check]").forEach((cb) => {
cb.checked = false;
});
updateCheckedCount();
filter();
});
loadChecks();
renderTabs();
load("parks");
</script>
</body>
</html>
|