aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/components/ParksTable.astro
blob: e5def8254e7c53321c4cf04dd005a21aea9ced0d (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
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
---
// 小平市の公園一覧(/kodaira-data/parks/)を表示する。
// データは src/data/kodaira-parks.json(市立332件+市立以外)。
// DOM を抑えるため、設備は1セルにまとめ、アイコンは CSS の擬似要素で描く。
// 絞り込み・並べ替え・カード表示は利用者の端末で実行する。
import parksData from "@/data/kodaira-parks.json";
import osmData from "@/data/parks-geojson";

type Park = Record<string, string>;
const parks = parksData as Park[];

// OpenStreetMapにポリゴンがあり、地図から位置を表示できる公園名。
const mappedNames = new Set<string>(
  (osmData as any).features
    .map((f: any) => f.properties?.our_name)
    .filter(Boolean),
);

const EMPTY = "—";

// 種別の表示(色付きの丸+区分名。正式名は title / aria-label で補う)。
const TYPE_LABEL: Record<string, string> = {
  街区: "街区公園",
  近隣: "近隣公園",
  運動: "運動公園",
  広域: "広域公園",
  広場: "広場",
  緑地: "緑地",
  団地内公園: "団地内公園",
  児童遊園: "児童遊園",
};
const TYPE_CLASS: Record<string, string> = {
  街区: "parks-type--block",
  近隣: "parks-type--neighbor",
  運動: "parks-type--sports",
  広域: "parks-type--wide",
  広場: "parks-type--open",
  緑地: "parks-type--green",
  団地内公園: "parks-type--danchi",
  児童遊園: "parks-type--jidou",
};

// 市立以外の公園に付けるバッジ(設置者が空欄なら市立として扱う)。
function ownerLabel(owner: string): string {
  if (owner.includes("都営")) return "都営";
  if (owner === "東京都") return "都立";
  if (owner.includes("UR")) return "UR";
  if (owner.includes("民間")) return "民間";
  return owner;
}
function ownerClass(owner: string): string {
  if (owner.includes("都営")) return "parks-owner--toei";
  if (owner === "東京都") return "parks-owner--tokyo";
  if (owner === "未確認") return "parks-owner--unknown";
  return "parks-owner--other";
}

// 設備バッジ(アイコンは CSS の ::before で描く)。
type Badge = { kind: string; label: string; title: string };
function facilityBadges(p: Park): Badge[] {
  const badges: Badge[] = [];
  if (p["トイレ"]) {
    badges.push({ kind: "toilet", label: "トイレ", title: `トイレ: ${p["トイレ"]}` });
  }
  if (p["水飲み場"]) {
    badges.push({ kind: "water", label: "水飲み場", title: `水飲み場: ${p["水飲み場"]}` });
  }
  if (p["遊具"]) {
    badges.push({ kind: "toy", label: "遊具", title: `遊具: ${p["遊具"]}` });
  }
  if (p["パーゴラ"]) {
    badges.push({ kind: "pergola", label: "パーゴラ", title: `パーゴラ: ${p["パーゴラ"]}` });
  }
  if (p["東屋"]) {
    badges.push({ kind: "azumaya", label: "東屋", title: `東屋: ${p["東屋"]}` });
  }
  const ball = p["ボール遊び"];
  if (ball && ball !== "禁止") {
    const label = ball.includes("一部") ? "ボール遊び一部可" : "ボール遊び可";
    badges.push({ kind: "ball", label, title: `ボール遊び: ${ball}` });
  }
  if (p["南西部指定管理"]) {
    badges.push({ kind: "cm", label: "指定管理", title: "南西部地域の指定管理公園" });
  }
  return badges;
}

// 設備フィルタ用のトークン(data-fac)。
function facTokens(p: Park): string {
  const tokens: string[] = [];
  if (p["トイレ"]) tokens.push("toilet");
  if (p["水飲み場"]) tokens.push("water");
  if (p["遊具"]) tokens.push("toy");
  if (p["パーゴラ"]) tokens.push("pergola");
  if (p["東屋"]) tokens.push("azumaya");
  const ball = p["ボール遊び"];
  if (ball && ball !== "禁止") tokens.push("ball");
  if (p["南西部指定管理"]) tokens.push("cm");
  return tokens.join(" ");
}

// 設備セルの補足テキスト(バッジで示した項目の詳細と、その他の項目)。
// ラベル文字は使わず、アイコンで項目を示す。
const DETAIL_FIELDS: { key: string; icon: string }[] = [
  { key: "ベンチ・椅子", icon: "🪑" },
  { key: "テーブル", icon: "🍽" },
  { key: "防災用具", icon: "🧯" },
  { key: "遊具", icon: "🎠" },
  { key: "駐車場", icon: "🅿" },
  { key: "その他設備", icon: "🔧" },
  { key: "備考", icon: "" },
];
function detailText(p: Park): string {
  const parts: string[] = [];
  for (const { key, icon } of DETAIL_FIELDS) {
    const value = p[key];
    if (!value) continue;
    parts.push(icon ? `${icon} ${value}` : value);
  }
  const ball = p["ボール遊び"];
  if (ball && ball !== "禁止" && ball !== "可") parts.push(`⚽ ${ball}`);
  return parts.join(" / ");
}

// 面積(数値)
function areaNumber(value: string): number {
  const n = Number(value);
  return Number.isFinite(n) ? n : 0;
}
function areaText(value: string): string {
  const n = areaNumber(value);
  return n ? n.toLocaleString("ja-JP") : value;
}
// 面積の目安(小・中・大)。しきい値はページの注記に合わせる。
function sizeLabel(area: number): string {
  if (area < 1000) return "小";
  if (area < 10000) return "中";
  return "大";
}
function sizeTitle(area: number): string {
  if (area < 1000) return "目安: 1,000㎡未満(小さめ)";
  if (area < 10000) return "目安: 1,000〜10,000㎡(ふつう)";
  return "目安: 10,000㎡以上(広め)";
}

// 座標があればその位置を開く。ない場合は公園名で検索する(地番は地図側で正しく解決されないため)。
// 公園名だけだと別の自治体の同名公園に飛ぶので「小平市」を必ず付ける。
function mapsUrl(p: Park): string {
  const lat = p["緯度"];
  const lng = p["経度"];
  if (lat && lng) {
    return `https://www.google.com/maps/search/?api=1&query=${lat},${lng}`;
  }
  const query = encodeURIComponent(`小平市${p["公園名"]}`);
  return `https://www.google.com/maps/search/?api=1&query=${query}`;
}

// 検索対象(公園名・住所・町名・種別・設備・備考)。
function searchIndex(p: Park): string {
  return [
    p["公園名"],
    p["住所"],
    p["町名"],
    p["種別"],
    TYPE_LABEL[p["種別"]],
    p["設置者"],
    p["トイレ"],
    p["水飲み場"],
    p["ボール遊び"],
    ...DETAIL_FIELDS.map((f) => p[f.key]),
  ]
    .join(" ")
    .toLowerCase();
}

const towns = [...new Set(parks.map((p) => p["町名"]).filter(Boolean))].sort((a, b) =>
  a.localeCompare(b, "ja"),
);
const total = parks.length;
---

<div class="parks" data-parks>
  <div class="parks-controls">
    <label>
      <span>町名</span>
      <select data-parks-town>
        <option value="">すべての町名</option>
        {towns.map((town) => (
          <option value={town}>{town}</option>
        ))}
      </select>
    </label>
    <label>
      <span>キーワード</span>
      <input type="search" data-parks-search placeholder="公園名・住所・遊具など" />
    </label>
    <fieldset class="parks-facilities">
      <legend>設備・管理で絞る</legend>
      <label><input type="checkbox" data-fac-filter value="toilet" />トイレ</label>
      <label><input type="checkbox" data-fac-filter value="water" />水飲み場</label>
      <label><input type="checkbox" data-fac-filter value="toy" />遊具</label>
      <label><input type="checkbox" data-fac-filter value="pergola" />パーゴラ</label>
      <label><input type="checkbox" data-fac-filter value="azumaya" />東屋</label>
      <label><input type="checkbox" data-fac-filter value="ball" />ボール遊び</label>
      <label><input type="checkbox" data-fac-filter value="cm" />指定管理</label>
    </fieldset>
    <button type="button" class="parks-save" data-parks-save-image>画像で保存</button>
    <span class="parks-count" data-parks-count aria-live="polite">{total}件</span>
  </div>
  <p class="parks-hint">設備の情報は、市の資料などに基づきます。設備で絞ると、この情報がある公園だけが対象になります。</p>
  <p class="parks-save-status" data-parks-save-status aria-live="polite"></p>
  <p class="parks-none" data-parks-none hidden>条件に合う公園が見つかりませんでした。</p>

  <div class="parks-scroll">
    <table>
      <thead>
        <tr>
          <th scope="col" aria-sort="none">
            <button type="button" class="parks-sort" data-sort="name">
              公園名<span class="parks-sort-mark" aria-hidden="true"></span>
            </button>
          </th>
          <th scope="col">住所</th>
          <th scope="col" aria-sort="none">
            <button type="button" class="parks-sort" data-sort="area">
              面積(㎡)<span class="parks-sort-mark" aria-hidden="true"></span>
            </button>
          </th>
          <th scope="col">種別</th>
          <th scope="col">施設・備考</th>
        </tr>
      </thead>
      <tbody>
        {parks.map((park) => (
          <tr
            data-town={park["町名"]}
            data-area={park["面積㎡"]}
            data-name={park["公園名"]}
            data-fac={facTokens(park)}
            data-search={searchIndex(park)}
          >
            <td class="is-name" data-label="公園名">
              {mappedNames.has(park["公園名"]) ? (
                <button
                  type="button"
                  class="park-name-link"
                  data-focus-park={park["公園名"]}
                  title="地図でこの公園の位置を表示"
                >{park["公園名"]}</button>
              ) : (
                park["公園名"]
              )}
              {park["設置者"] && park["設置者"] !== "小平市" ? (
                <span
                  class:list={["parks-owner", ownerClass(park["設置者"])]}
                  title={`設置者: ${park["設置者"]}`}
                >{ownerLabel(park["設置者"])}</span>
              ) : null}
            </td>
            <td class="is-address" data-label="住所">
              <a
                href={mapsUrl(park)}
                target="_blank"
                rel="noopener"
                title={`Googleマップで「${park["公園名"]}」を開く`}
              >{park["住所"] || EMPTY}</a>
            </td>
            <td
              class="is-num"
              data-label="面積"
              data-size={park["面積㎡"] ? sizeLabel(areaNumber(park["面積㎡"])) : ""}
              title={park["面積㎡"] ? sizeTitle(areaNumber(park["面積㎡"])) : ""}
            >
              {park["面積㎡"] ? `${areaText(park["面積㎡"])}㎡` : EMPTY}
            </td>
            <td class="is-type" data-label="種別">
              {park["種別"] ? (
                <span
                  class:list={["parks-type", TYPE_CLASS[park["種別"]]]}
                  title={TYPE_LABEL[park["種別"]]}
                  aria-label={TYPE_LABEL[park["種別"]]}
                >
                  {park["種別"]}
                </span>
              ) : (
                EMPTY
              )}
            </td>
            <td class="is-facility" data-label="施設・備考">
              {facilityBadges(park).map((b) => (
                <span class:list={["fac-badge", `fac-${b.kind}`]} title={b.title} aria-label={b.title}></span>
              ))}
              {detailText(park) ? <span class="fac-detail">{detailText(park)}</span> : null}
              {facilityBadges(park).length === 0 && !detailText(park) ? EMPTY : null}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
</div>

<style>
  .parks-controls {
    display: flex;
    flex-wrap: wrap;
    gap: 0.6rem 1rem;
    align-items: center;
    margin: 1rem 0 0.4rem;
  }
  .parks-controls label {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    font-size: 0.9rem;
  }
  .parks-controls select,
  .parks-controls input[type="search"] {
    padding: 0.3rem 0.5rem;
    border: 1px solid var(--sl-color-hairline, #ccc);
    border-radius: 0.3rem;
    background: var(--sl-color-bg, #fff);
    color: var(--sl-color-text, inherit);
    font: inherit;
  }
  .parks-facilities {
    display: flex;
    flex-wrap: wrap;
    gap: 0.3rem 0.8rem;
    align-items: center;
    margin: 0;
    padding: 0.2rem 0.6rem;
    border: 1px solid var(--sl-color-hairline, #ccc);
    border-radius: 0.3rem;
  }
  .parks-facilities legend {
    padding: 0 0.2rem;
    font-size: 0.8em;
    color: inherit;
    opacity: 0.7;
  }
  .parks-facilities label {
    font-size: 0.85rem;
  }
  .parks-count {
    margin-left: auto;
    font-size: 0.9rem;
    opacity: 0.75;
  }
  .parks-save {
    padding: 0.35rem 0.7rem;
    border: 1px solid var(--sl-color-hairline, #ccc);
    border-radius: 0.35rem;
    background: var(--sl-color-bg, #fff);
    color: var(--sl-color-text, inherit);
    font: inherit;
    font-size: 0.85rem;
    cursor: pointer;
  }
  .parks-save:hover {
    border-color: var(--sl-color-text-accent, #4c8);
  }
  .parks-save:disabled {
    opacity: 0.6;
    cursor: wait;
  }
  .parks-save-status {
    margin: 0 0 0.6rem;
    font-size: 0.8rem;
    opacity: 0.8;
  }
  .parks-save-status:empty {
    display: none;
  }
  /* 画像保存用のオフスクリーン領域。サイトの表スタイルをそのまま使う。 */
  .parks-capture {
    position: fixed;
    left: 0;
    top: 0;
    z-index: -1;
    pointer-events: none;
    width: max-content;
    padding: 24px 28px;
    background: #fff;
    color: #1a1a1a;
    color-scheme: light;
    --sl-color-text: #1a1a1a;
    --sl-color-bg: #ffffff;
    --sl-color-hairline: #dddddd;
    --sl-color-gray-4: #888888;
    --sl-color-gray-6: #eef1f3;
    --sl-color-white: #1a1a1a;
    --sl-color-text-accent: #0b7a4b;
  }
  .parks-capture-head {
    display: flex;
    align-items: baseline;
    gap: 0.8rem;
    margin-bottom: 0.2rem;
  }
  .parks-capture-head strong {
    font-size: 1.35rem;
  }
  .parks-capture-head span {
    font-size: 0.9rem;
    opacity: 0.75;
  }
  .parks-capture-meta {
    margin-bottom: 0.7rem;
    font-size: 0.8rem;
    opacity: 0.75;
  }
  .parks-capture table {
    width: max-content;
  }
  .parks-capture thead th {
    position: static;
    background: #eef1f3;
    color: #1a1a1a;
  }
  .parks-capture tbody td {
    color: #1a1a1a;
  }
  .parks-capture-foot {
    margin-top: 0.7rem;
    font-size: 0.72rem;
    opacity: 0.65;
  }
  .parks-hint,
  .parks-none {
    margin: 0 0 0.6rem;
    font-size: 0.8rem;
    opacity: 0.75;
  }
  .parks-none {
    padding: 0.6rem;
    border: 1px dashed var(--sl-color-hairline, #ccc);
    border-radius: 0.3rem;
    opacity: 1;
  }
  .parks-scroll {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    border: 1px solid var(--sl-color-hairline, #ddd);
    border-radius: 0.3rem;
  }
  .parks table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.85rem;
  }
  .parks th,
  .parks td {
    border-bottom: 1px solid var(--sl-color-hairline, #ddd);
    border-right: 1px solid var(--sl-color-hairline, #ddd);
    padding: 0.35rem 0.55rem;
    text-align: left;
    vertical-align: top;
    white-space: nowrap;
  }
  .parks th:last-child,
  .parks td:last-child {
    border-right: none;
  }
  .parks thead th {
    position: sticky;
    top: 0;
    z-index: 1;
    background: var(--sl-color-gray-6, #f2f2f2);
    color: var(--sl-color-white, inherit);
  }
  .parks tbody tr:nth-child(even) td {
    background: color-mix(in srgb, var(--sl-color-text, #333) 5%, transparent);
  }
  .parks tr.is-hidden {
    display: none;
  }
  .parks-sort {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0;
    border: none;
    background: none;
    color: inherit;
    font: inherit;
    cursor: pointer;
  }
  .parks-sort:hover .parks-sort-mark {
    color: var(--sl-color-text-accent, #4c8);
  }
  .parks-sort-mark {
    display: inline-block;
    min-width: 1em;
    text-align: center;
  }
  .parks .is-name {
    font-weight: 600;
  }
  .parks-owner {
    display: inline-block;
    margin-left: 0.35rem;
    padding: 0.02rem 0.35rem;
    border: 1px solid currentColor;
    border-radius: 999px;
    font-size: 0.7rem;
    font-weight: 600;
    line-height: 1.5;
    vertical-align: 0.08em;
    white-space: nowrap;
  }
  .parks-owner--tokyo {
    color: #2e7d32;
  }
  .parks-owner--toei {
    color: #1565c0;
  }
  .parks-owner--other {
    color: #6d4c41;
  }
  .parks-owner--unknown {
    color: #757575;
  }
  .park-name-link {
    padding: 0;
    border: 0;
    background: none;
    color: inherit;
    font: inherit;
    font-weight: 600;
    text-align: left;
    cursor: pointer;
    text-decoration: underline;
    text-decoration-color: var(--sl-color-gray-4);
    text-underline-offset: 2px;
  }
  .park-name-link:hover {
    color: var(--sl-color-accent);
  }
  .parks tbody tr.is-highlighted td {
    background: #fff59d !important;
  }
  .parks .is-address {
    font-size: 0.8em;
    white-space: normal;
    min-width: 9rem;
  }
  .parks .is-address a {
    color: var(--sl-color-text-accent, #357);
  }
  .parks .is-address a::before {
    content: "📍";
    margin-right: 0.2em;
  }
  .parks .is-num {
    text-align: right;
    font-variant-numeric: tabular-nums;
    white-space: nowrap;
  }
  .parks .is-num::after {
    content: attr(data-size);
    display: inline-block;
    margin-left: 0.4em;
    padding: 0 0.45em;
    border-radius: 0.7em;
    font-size: 0.75em;
    line-height: 1.7;
    vertical-align: middle;
    background: color-mix(in srgb, currentColor 14%, transparent);
  }
  .parks .is-num[data-size="中"]::after {
    background: color-mix(in srgb, #2e9e4f 22%, transparent);
  }
  .parks .is-num[data-size="大"]::after {
    background: color-mix(in srgb, #2f7fe0 24%, transparent);
  }
  .parks .is-type {
    text-align: center;
  }
  .parks-type {
    display: inline-flex;
    align-items: center;
    gap: 0.3em;
    font-size: 0.9em;
  }
  .parks-type::before {
    content: "";
    width: 0.7em;
    height: 0.7em;
    border-radius: 50%;
    background: var(--type-color, #888);
    flex: none;
  }
  .parks-type--block {
    --type-color: #2e9e4f;
  }
  .parks-type--neighbor {
    --type-color: #2f7fe0;
  }
  .parks-type--sports {
    --type-color: #e8862a;
  }
  .parks-type--wide {
    --type-color: #7b1fa2;
  }
  .parks-type--open {
    --type-color: #8d6e63;
  }
  .parks-type--green {
    --type-color: #43a047;
  }
  .parks-type--danchi {
    --type-color: #546e7a;
  }
  .parks-type--jidou {
    --type-color: #d81b60;
  }
  .parks .is-facility {
    white-space: normal;
    min-width: 12rem;
    max-width: 26rem;
  }
  .parks .fac-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin: 0 0.3em 0.2em 0;
    padding: 0 0.4em;
    border-radius: 1em;
    font-size: 0.85em;
    line-height: 1.9;
    white-space: nowrap;
    background: color-mix(in srgb, currentColor 10%, transparent);
    cursor: help;
  }
  .parks .fac-toilet::before {
    content: "🚻";
  }
  .parks .fac-water::before {
    content: "🚰";
  }
  .parks .fac-toy::before {
    content: "🎠";
  }
  .parks .fac-ball::before {
    content: "⚽";
  }
  .parks .fac-cm::before {
    content: "🏛";
  }
  .parks .fac-pergola::before {
    content: "🌿";
  }
  .parks .fac-azumaya::before {
    content: "🛖";
  }
  .parks .fac-detail {
    display: block;
    margin-top: 0.25em;
    font-size: 0.8em;
    opacity: 0.85;
  }

  /* スマートフォンでも表形式を維持し、横スクロールで見られるようにする。 */
  @media (max-width: 640px) {
    .parks table {
      font-size: 0.75rem;
    }
    .parks th,
    .parks td {
      padding: 0.3rem 0.4rem;
    }
  }
</style>

<script>
  import { toPng } from "html-to-image";

  document.querySelectorAll("[data-parks]").forEach((root) => {
    const select = root.querySelector<HTMLSelectElement>("[data-parks-town]");
    const search = root.querySelector<HTMLInputElement>("[data-parks-search]");
    const count = root.querySelector("[data-parks-count]");
    const none = root.querySelector<HTMLElement>("[data-parks-none]");
    const tbody = root.querySelector("tbody");
    const checks = Array.from(root.querySelectorAll<HTMLInputElement>("[data-fac-filter]"));
    const sortButtons = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-sort]"));
    if (!tbody) return;

    root.querySelectorAll<HTMLButtonElement>("[data-focus-park]").forEach((btn) => {
      btn.addEventListener("click", () => {
        const name = btn.dataset.focusPark;
        if (!name) return;
        document.dispatchEvent(new CustomEvent("park:focus", { detail: { name } }));
      });
    });

    const allRows = () => Array.from(tbody.querySelectorAll<HTMLTableRowElement>("tr"));
    const total = allRows().length;
    const saveButton = root.querySelector<HTMLButtonElement>("[data-parks-save-image]");
    const saveStatus = root.querySelector<HTMLElement>("[data-parks-save-status]");
    const MAX_IMAGE_ROWS = 30;
    // AstroのスコープCSSを動的生成要素にも当てる(ダークテーマの色を上書きするため)。
    const scopeClass = Array.from(root.classList).find((cls) => cls.startsWith("astro-"));
    const withScope = <T extends HTMLElement>(el: T): T => {
      if (scopeClass) el.classList.add(scopeClass);
      return el;
    };

    const saveTableImage = async () => {
      if (!saveButton) return;
      const visible = allRows().filter((row) => !row.classList.contains("is-hidden"));
      if (!visible.length) {
        if (saveStatus) saveStatus.textContent = "表示中の公園がありません。";
        return;
      }
      const table = root.querySelector("table");
      if (!table) return;

      saveButton.disabled = true;
      if (saveStatus) saveStatus.textContent = "画像を作成中…";
      let wrap: HTMLDivElement | null = null;
      try {
        const limited = visible.slice(0, MAX_IMAGE_ROWS);
        const clone = table.cloneNode(true) as HTMLTableElement;
        const cloneBody = clone.querySelector("tbody");
        if (cloneBody) {
          cloneBody.innerHTML = "";
          limited.forEach((row) => cloneBody.appendChild(row.cloneNode(true)));
        }

        // ボタン・リンクは画像内では文字だけにする。
        clone.querySelectorAll("button").forEach((btn) => {
          const span = document.createElement("span");
          span.textContent = (btn.textContent || "").trim();
          btn.replaceWith(span);
        });
        clone.querySelectorAll("a").forEach((link) => {
          const span = document.createElement("span");
          span.textContent = (link.textContent || "").trim();
          link.replaceWith(span);
        });

        // 設備アイコンはCSSの擬似要素なので、画像では絵文字を直接入れる。
        const icons: Record<string, string> = {
          toilet: "🚻",
          water: "🚰",
          toy: "🎠",
          ball: "⚽",
          cm: "🏛",
          pergola: "🌿",
          azumaya: "🛖",
        };
        clone.querySelectorAll<HTMLElement>(".fac-badge").forEach((badge) => {
          for (const [kind, icon] of Object.entries(icons)) {
            if (badge.classList.contains(`fac-${kind}`)) {
              badge.textContent = icon;
              break;
            }
          }
        });

        wrap = document.createElement("div");
        wrap.className = "parks parks-capture";
        withScope(wrap);
        const head = document.createElement("div");
        head.className = "parks-capture-head";
        withScope(head);
        const title = document.createElement("strong");
        title.textContent = "小平市の公園一覧";
        withScope(title);
        const countLabel = document.createElement("span");
        countLabel.textContent = `${limited.length}件${
          visible.length > MAX_IMAGE_ROWS
            ? `(表示中${visible.length}件の先頭${MAX_IMAGE_ROWS}件)`
            : ""
        }`;
        withScope(countLabel);
        head.append(title, countLabel);

        const meta = document.createElement("div");
        meta.className = "parks-capture-meta";
        withScope(meta);
        const parts: string[] = [];
        if (select?.value) parts.push(`町名: ${select.value}`);
        if (search?.value.trim()) parts.push(`キーワード: ${search.value.trim()}`);
        const facLabels = checks
          .filter((c) => c.checked)
          .map((c) => (c.parentElement?.textContent || "").trim())
          .filter(Boolean);
        if (facLabels.length) parts.push(`設備: ${facLabels.join("・")}`);
        if (sortKey) {
          parts.push(
            `並べ替え: ${sortKey === "area" ? "面積" : "公園名"} ${
              sortDir === 1 ? "昇順" : "降順"
            }`,
          );
        }
        meta.textContent = parts.length ? parts.join(" / ") : "すべての公園";

        const foot = document.createElement("div");
        foot.className = "parks-capture-foot";
        withScope(foot);
        foot.textContent = `yasutakeyohei.com/kodaira-data/parks/ ・ ${new Date().toLocaleDateString(
          "ja-JP",
        )}時点`;

        wrap.append(head, meta, clone, foot);
        document.body.appendChild(wrap);

        const dataUrl = await toPng(wrap, {
          pixelRatio: 2,
          backgroundColor: "#ffffff",
          cacheBust: true,
        });

        const link = document.createElement("a");
        link.download = `kodaira-parks-${new Date().toISOString().slice(0, 10)}.png`;
        link.href = dataUrl;
        link.click();
        if (saveStatus)
          saveStatus.textContent =
            visible.length > MAX_IMAGE_ROWS
              ? `画像を保存しました(表示中${visible.length}件の先頭${MAX_IMAGE_ROWS}件)。`
              : "画像を保存しました。";
      } catch (error) {
        console.error(error);
        if (saveStatus) saveStatus.textContent = "画像の作成に失敗しました。";
      } finally {
        wrap?.remove();
        saveButton.disabled = false;
        window.setTimeout(() => {
          if (saveStatus) saveStatus.textContent = "";
        }, 5000);
      }
    };

    saveButton?.addEventListener("click", saveTableImage);

    let sortKey: string | null = null;
    let sortDir = 1;
    let selectedName = "";

    const applyFilter = () => {
      const town = select ? select.value : "";
      const query = search ? search.value.trim().toLowerCase() : "";
      const wanted = checks.filter((c) => c.checked).map((c) => c.value);
      let shown = 0;
      allRows().forEach((row) => {
        const facs = (row.dataset.fac || "").split(" ");
        const okTown = !town || row.dataset.town === town;
        const okText = !query || (row.dataset.search || "").includes(query);
        const okFac = wanted.every((token) => facs.includes(token));
        const okSelected = !selectedName || row.dataset.name === selectedName;
        const ok = okTown && okText && okFac && okSelected;
        row.classList.toggle("is-hidden", !ok);
        if (ok) shown += 1;
      });
      if (count) count.textContent = `${shown} / ${total}件`;
      if (none) none.hidden = shown !== 0;
      // 地図側に絞り込み結果を通知する。
      const visibleNames = allRows()
        .filter((row) => !row.classList.contains("is-hidden"))
        .map((row) => row.dataset.name || "")
        .filter(Boolean);
      const fromMap = Boolean(selectedName && search?.value === selectedName);
      document.dispatchEvent(
        new CustomEvent("park:filter", {
          detail: {
            names: visibleNames,
            active: Boolean(town || query || wanted.length || selectedName),
            fromMap,
          },
        }),
      );
    };

    const applySort = () => {
      sortButtons.forEach((btn) => {
        const th = btn.closest("th");
        const active = btn.dataset.sort === sortKey;
        if (th) {
          th.setAttribute("aria-sort", active ? (sortDir === 1 ? "ascending" : "descending") : "none");
        }
        const mark = btn.querySelector(".parks-sort-mark");
        if (mark) mark.textContent = active ? (sortDir === 1 ? "▲" : "▼") : "";
      });
      if (!sortKey) return;
      const sorted = allRows().sort((a, b) => {
        if (sortKey === "area") {
          const av = Number.parseFloat(a.dataset.area || "") || 0;
          const bv = Number.parseFloat(b.dataset.area || "") || 0;
          return (av - bv) * sortDir;
        }
        return (a.dataset.name || "").localeCompare(b.dataset.name || "", "ja") * sortDir;
      });
      sorted.forEach((row) => tbody.appendChild(row));
    };

    const clearSelected = () => {
      selectedName = "";
    };
    select?.addEventListener("change", () => {
      clearSelected();
      applyFilter();
    });
    search?.addEventListener("input", () => {
      clearSelected();
      applyFilter();
    });
    checks.forEach((c) =>
      c.addEventListener("change", () => {
        clearSelected();
        applyFilter();
      }),
    );

    // 地図のポリゴンクリックなどから、公園名で1件だけ絞り込む。
    document.addEventListener("park:filter-name", (e: Event) => {
      const detail = (e as CustomEvent).detail || {};
      const name = detail.name;
      if (!name) return;
      selectedName = name;
      if (search) search.value = name;
      if (select) select.value = "";
      checks.forEach((c) => {
        c.checked = false;
      });
      applyFilter();
      const row = allRows().find((r) => r.dataset.name === name);
      if (row) {
        row.classList.add("is-highlighted");
        window.setTimeout(() => row.classList.remove("is-highlighted"), 2000);
        if (detail.scroll) {
          row.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }
    });
    sortButtons.forEach((btn) => {
      btn.addEventListener("click", () => {
        const key = btn.dataset.sort;
        if (sortKey === key) {
          sortDir = -sortDir;
        } else {
          sortKey = key ?? null;
          sortDir = 1;
        }
        applySort();
      });
    });
    applyFilter();
  });
</script>