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
|
<script>
// URLは src/data/schedule/config.ts で一元管理している(ページ移転時はそこだけ変える)
import { scheduleAbsoluteUrl } from '@/data/schedule/config';
import { parseDates, applyExclusions, toKey, keyToDate, entryDates, mainStartMonth } from '@/lib/schedule-dates';
const CATEGORY_DEFS = [
{ icon: '👶', label: '子育て' },
{ icon: '🧓', label: '高齢者・介護' },
{ icon: '🏥', label: '健康' },
{ icon: '♿', label: '福祉・相談' },
{ icon: '🎨', label: '文化・公民館' },
{ icon: '🏃', label: 'スポーツ' },
{ icon: '🌳', label: '環境・自然' },
{ icon: '📚', label: '学習・講演' },
{ icon: '🤝', label: '交流・地域' },
];
const MEETING_ICON = '🏛️';
// 市議会の予定は審議会等と同じアイコンなので、会議名で見分ける。
const COUNCIL_KEY = 'council';
const isCouncil = (e: { type: string; name: string }) =>
e.type === 'meeting' && e.name.includes('小平市議会');
// 図書館のイベントは出典に図書館のページ(info.html?id=…)のリンクが入っている。
const LIBRARY_KEY = 'library';
const isLibrary = (e: { source?: string }) =>
(e.source ?? '').includes('library.kodaira.ed.jp/viewer/info.html');
const WEEKDAYS = ['日', '月', '火', '水', '木', '金', '土'];
const escapeHtml = (s) =>
s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
function initSchedule() {
const calendarEl = document.getElementById('schedule-calendar');
const detailsEl = document.getElementById('schedule-day-details');
const filtersEl = document.getElementById('event-filters');
const meetingsTable = document.querySelector('#meetings-table table');
const eventsTable = document.querySelector('#events-table table');
if (!calendarEl || !detailsEl || !filtersEl || !meetingsTable || !eventsTable) return;
if (calendarEl.dataset.initialized === 'true') return;
calendarEl.dataset.initialized = 'true';
const entries = [];
function collect(table, type) {
table.querySelectorAll('tbody tr').forEach((row, i) => {
const cells = row.querySelectorAll('td');
if (cells.length < 3) return;
const dateText = cells[0].textContent.trim();
const name = cells[1].textContent.trim();
const timeText = cells[2].textContent.trim();
// 出典欄はリンク先URLで判定するため、HTML を保持する(textContent には href が入らない)。
const source = cells[4] ? cells[4].innerHTML : '';
const rowId = `${type}-row-${i}`;
row.id = rowId;
let category = MEETING_ICON;
let categoryLabel = '審議会等';
const cat = CATEGORY_DEFS.find((c) => name.startsWith(c.icon));
if (cat) {
category = cat.icon;
categoryLabel = cat.label;
} else if (type === 'event') {
category = '🤝';
categoryLabel = '交流・地域';
}
row.dataset.category = category;
const dates = new Set(entryDates(type, dateText, timeText));
entries.push({
type,
name,
time: timeText,
dates: [...dates],
category,
categoryLabel,
rowId,
dateText,
source,
});
});
}
collect(meetingsTable, 'meeting');
collect(eventsTable, 'event');
const byDate = new Map();
for (const entry of entries) {
for (const key of entry.dates) {
if (!byDate.has(key)) byDate.set(key, []);
byDate.get(key).push(entry);
}
}
const dateKeys = [...byDate.keys()].sort();
if (dateKeys.length === 0) {
calendarEl.innerHTML = '<p>表示できる予定がありません。</p>';
return;
}
const today = new Date();
const todayKey = toKey(today.getFullYear(), today.getMonth() + 1, today.getDate());
const todayMonth = todayKey.slice(0, 7);
// 今日の月もカレンダーで移動できるように含める。
// メインページの一覧は前月以降に絞っているので、カレンダーも前々月以前には戻らない。
const months = [...new Set([...dateKeys.map((k) => k.slice(0, 7)), todayMonth])]
.filter((month) => month >= mainStartMonth())
.sort();
// 開催日が今日より前のものは「終了」と表示する。
// 複数回の催しで未来の回が残っているものは対象外。
for (const entry of entries) {
if (entry.dateText.includes('申込開始')) continue;
if (entry.dates.length === 0) continue;
if (!entry.dates.every((d) => d < todayKey)) continue;
const row = document.getElementById(entry.rowId);
if (!row) continue;
row.classList.add('is-ended');
if (!row.querySelector('.schedule-ended-badge') && row.cells[0]) {
const badge = document.createElement('span');
badge.className = 'schedule-ended-badge';
badge.textContent = '終了';
row.cells[0].appendChild(badge);
}
}
// 終了した予定は表の下にまとめ、開催中の予定から表示する。
for (const table of [meetingsTable, eventsTable]) {
const tbody = table.tBodies[0];
if (!tbody) continue;
const rows = [...tbody.rows];
for (const row of rows) {
if (row.classList.contains('is-ended')) tbody.appendChild(row);
}
}
let selectedDate = todayKey;
let currentMonth = todayMonth;
let activeCategory = 'all';
function matchesCategory(e) {
if (activeCategory === 'all') return true;
if (activeCategory === COUNCIL_KEY) return isCouncil(e);
if (activeCategory === LIBRARY_KEY) return isLibrary(e);
// 「審議会等」は市議会を除く(市議会は別のボタンで絞り込む)。
if (activeCategory === MEETING_ICON) return e.type === 'meeting' && !isCouncil(e);
return e.category === activeCategory;
}
function visibleEntries(key) {
const list = byDate.get(key) || [];
return list.filter(matchesCategory);
}
function ensureVisibleSelection() {
if (selectedDate && visibleEntries(selectedDate).length > 0) return;
// 絞り込みで選択中の日付が空になったら、当月の最初の該当日へ移動する。
// 当月に該当日がなければ、最初の該当日へ移動する。
const inMonth = dateKeys.filter(
(k) => k.startsWith(currentMonth) && visibleEntries(k).length > 0
);
const any = dateKeys.filter((k) => visibleEntries(k).length > 0);
const fallback = inMonth[0] || any[0];
if (!fallback) return;
selectedDate = fallback;
currentMonth = fallback.slice(0, 7);
}
function renderCalendar() {
const index = months.indexOf(currentMonth);
const [year, month] = currentMonth.split('-').map(Number);
const first = new Date(year, month - 1, 1);
const startDay = first.getDay();
const daysInMonth = new Date(year, month, 0).getDate();
const cells = [];
for (let i = 0; i < startDay; i++) {
cells.push('<div class="schedule-cal-day is-blank"></div>');
}
for (let day = 1; day <= daysInMonth; day++) {
const key = toKey(year, month, day);
const list = visibleEntries(key);
const classes = ['schedule-cal-day'];
if (key === todayKey) classes.push('is-today');
if (key === selectedDate) classes.push('is-selected');
if (list.length === 0) {
cells.push(
`<div class="${classes.join(' ')}"><span class="schedule-cal-daynum">${day}</span></div>`
);
continue;
}
const categories = [...new Set(list.map((e) => e.category))];
const marks = categories
.slice(0, 3)
.map((icon) => `<span class="schedule-cal-mark">${icon}</span>`)
.join('');
const more =
categories.length > 3
? `<span class="schedule-cal-more">+${categories.length - 3}</span>`
: '';
const count =
list.length > 1 ? `<span class="schedule-cal-count">${list.length}</span>` : '';
cells.push(
`<button type="button" class="${classes.join(' ')} has-events" data-date="${key}" aria-label="${month}月${day}日、${list.length}件の予定"><span class="schedule-cal-daynum">${day}${count}</span><span class="schedule-cal-marks">${marks}${more}</span></button>`
);
}
calendarEl.innerHTML = `
<div class="schedule-cal-header">
<button type="button" class="schedule-cal-nav" data-dir="-1" aria-label="前の月" ${index <= 0 ? 'disabled' : ''}>‹</button>
<div class="schedule-cal-mid">
<div class="schedule-cal-title">${year}年${month}月</div>
${
selectedDate === todayKey
? ''
: '<button type="button" class="schedule-cal-today" aria-label="今日に戻る">今日に戻る</button>'
}
</div>
<button type="button" class="schedule-cal-nav" data-dir="1" aria-label="次の月" ${index >= months.length - 1 ? 'disabled' : ''}>›</button>
</div>
<div class="schedule-cal-grid">
${WEEKDAYS.map(
(w, i) =>
`<div class="schedule-cal-weekday${i === 0 ? ' is-sun' : i === 6 ? ' is-sat' : ''}">${w}</div>`
).join('')}
${cells.join('')}
</div>
<p class="schedule-cal-filter-note">${
activeCategory === 'all'
? '絞り込みなし(すべての予定を表示)'
: `絞り込み中:${filterLabel()}`
}</p>
`;
calendarEl.querySelectorAll('.schedule-cal-day[data-date]').forEach((btn) => {
btn.addEventListener('click', () => {
selectedDate = btn.dataset.date;
renderCalendar();
showDayDetails(selectedDate);
});
});
calendarEl.querySelectorAll('.schedule-cal-today').forEach((btn) => {
btn.addEventListener('click', () => {
selectedDate = todayKey;
currentMonth = todayMonth;
renderCalendar();
showDayDetails(selectedDate);
});
});
calendarEl.querySelectorAll('.schedule-cal-nav').forEach((btn) => {
btn.addEventListener('click', () => {
const next = months.indexOf(currentMonth) + Number(btn.dataset.dir);
if (next < 0 || next >= months.length) return;
currentMonth = months[next];
selectedDate = null;
renderCalendar();
detailsEl.innerHTML =
'<p class="schedule-day-placeholder">日付を選ぶと、その日の予定が表示されます。</p>';
});
});
}
function showDayDetails(key) {
if (!key) return;
const date = keyToDate(key);
const weekday = WEEKDAYS[date.getDay()];
const list = visibleEntries(key)
.slice()
.sort((a, b) => {
if (a.type !== b.type) return a.type === 'meeting' ? -1 : 1;
return a.name.localeCompare(b.name, 'ja');
});
const title = `${date.getMonth() + 1}月${date.getDate()}日(${weekday})の予定`;
// 会場の地図(ScheduleMap)に、その日の予定を知らせる。
const detail = {
date: key,
entries: list.map((e) => ({
name: e.name,
time: e.time,
category: e.category,
rowId: e.rowId,
})),
};
(window as any).__scheduleDay = detail;
document.dispatchEvent(new CustomEvent('schedule:day', { detail }));
if (list.length === 0) {
detailsEl.innerHTML = `<h3>${title}</h3><p>この日の予定はありません。</p>`;
return;
}
const items = list
.map((e) => {
const displayName = e.name.startsWith(e.category)
? e.name.slice(e.category.length).trim()
: e.name;
return `<li><a class="schedule-day-link" href="#${e.rowId}"><span class="schedule-day-icon">${e.category}</span>${escapeHtml(displayName)}</a><span class="schedule-day-meta">${escapeHtml(e.time)}</span></li>`;
})
.join('');
detailsEl.innerHTML = `<h3>${title}</h3><ul>${items}</ul>`;
detailsEl.querySelectorAll('a.schedule-day-link').forEach((a) => {
a.addEventListener('click', () => {
const row = document.getElementById(a.getAttribute('href').slice(1));
if (!row) return;
row.classList.add('schedule-row-highlight');
window.setTimeout(() => row.classList.remove('schedule-row-highlight'), 3000);
});
});
}
const meetingEntries = entries.filter((e) => e.type === 'meeting');
const eventEntries = entries.filter((e) => e.type === 'event');
const counts = {};
for (const e of entries) {
counts[e.category] = (counts[e.category] || 0) + 1;
}
function categoryLabel(category) {
if (category === COUNCIL_KEY) return '市議会';
if (category === LIBRARY_KEY) return '図書館';
if (category === MEETING_ICON) return '審議会等';
const def = CATEGORY_DEFS.find((c) => c.icon === category);
return def ? def.label : '交流・地域';
}
// 「🏛️ 市議会」「📖 図書館」のように、アイコン付きで現在の絞り込みを表す
function filterLabel() {
if (activeCategory === COUNCIL_KEY) return `${MEETING_ICON} 市議会`;
if (activeCategory === LIBRARY_KEY) return '📖 図書館';
if (activeCategory === MEETING_ICON) return `${MEETING_ICON} 審議会等`;
return `${activeCategory} ${categoryLabel(activeCategory)}`;
}
function ensureStatus(container, type) {
const id = `${type}-filter-status`;
let status = document.getElementById(id);
if (!status) {
status = document.createElement('div');
status.id = id;
status.className = 'schedule-table-status';
status.setAttribute('role', 'status');
status.setAttribute('aria-live', 'polite');
container.parentElement.insertBefore(status, container);
}
return status;
}
const meetingStatus = ensureStatus(meetingsTable.parentElement, 'meeting');
const eventStatus = ensureStatus(eventsTable.parentElement, 'event');
function updateTableStatus(status, type, total, visible) {
const tableLabel = type === 'meeting' ? '審議会等・市議会' : 'イベント';
const filtered = activeCategory !== 'all';
status.classList.toggle('is-filtered', filtered);
const text = filtered
? `${tableLabel}:「${filterLabel()}」で絞り込み中:${visible}件/全${total}件`
: `${tableLabel}:全${total}件を表示しています(絞り込みなし)`;
status.innerHTML = `<span class="schedule-table-status-text">${text}</span>`;
if (filtered) {
const clear = document.createElement('button');
clear.type = 'button';
clear.className = 'schedule-table-status-clear';
clear.textContent = '絞り込みを解除';
clear.addEventListener('click', () => setActiveCategory('all'));
status.appendChild(clear);
}
}
function updateEmptyMessage(container, id, count, text) {
let empty = document.getElementById(id);
if (!empty) {
empty = document.createElement('p');
empty.id = id;
empty.className = 'schedule-filter-empty';
container.appendChild(empty);
}
empty.hidden = count > 0;
empty.textContent = text;
}
function applyFilter() {
const visibleMeetings = meetingEntries.filter(matchesCategory).length;
const visibleEvents = eventEntries.filter(matchesCategory).length;
for (const e of entries) {
const row = document.getElementById(e.rowId);
if (row) {
const show = matchesCategory(e);
row.hidden = !show;
row.classList.toggle('is-filtered-out', !show);
}
}
updateTableStatus(meetingStatus, 'meeting', meetingEntries.length, visibleMeetings);
updateTableStatus(eventStatus, 'event', eventEntries.length, visibleEvents);
updateEmptyMessage(
meetingsTable.parentElement,
'meeting-filter-empty',
visibleMeetings,
'該当する審議会等はありません。'
);
updateEmptyMessage(
eventsTable.parentElement,
'event-filter-empty',
visibleEvents,
'該当するイベントはありません。'
);
}
function setActiveCategory(category) {
activeCategory = category;
filtersEl.querySelectorAll('.schedule-filter-btn').forEach((b) => {
b.setAttribute('aria-pressed', String(b.dataset.category === activeCategory));
});
applyFilter();
ensureVisibleSelection();
renderCalendar();
if (selectedDate) showDayDetails(selectedDate);
}
function buildFilters() {
const buttonDefs = [
{ category: 'all', icon: '', label: 'すべて', count: entries.length },
{
category: COUNCIL_KEY,
icon: MEETING_ICON,
label: '市議会',
count: entries.filter(isCouncil).length,
},
{
category: MEETING_ICON,
icon: MEETING_ICON,
label: '審議会等',
count: meetingEntries.length,
},
{
category: LIBRARY_KEY,
icon: '📖',
label: '図書館',
count: entries.filter(isLibrary).length,
},
...CATEGORY_DEFS.map((c) => ({
category: c.icon,
icon: c.icon,
label: c.label,
count: counts[c.icon] || 0,
})),
];
filtersEl.innerHTML = buttonDefs
.map(
(b) =>
`<button type="button" class="schedule-filter-btn" data-category="${b.category}" aria-pressed="${b.category === activeCategory}">${b.icon ? `${b.icon} ` : ''}${b.label}</button>`
)
.join('');
filtersEl.querySelectorAll('.schedule-filter-btn').forEach((btn) => {
btn.addEventListener('click', () => setActiveCategory(btn.dataset.category));
});
}
// 検索エンジン向けに、これからのイベントを構造化データ(JSON-LD)で出力する。
function emitEventStructuredData() {
const upcoming = entries
.filter((e) => e.type === 'event' && e.dates.some((d) => d >= todayKey))
.map((e) => {
const future = e.dates.filter((d) => d >= todayKey).sort();
const name = e.name.startsWith(e.category)
? e.name.slice(e.category.length).trim()
: e.name;
const parts = e.time.split('/');
const venue = (parts[1] ?? '').trim();
return {
'@type': 'Event',
name,
startDate: future[0],
eventStatus: 'https://schema.org/EventScheduled',
eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode',
location: {
'@type': 'Place',
name: venue || '小平市',
address: {
'@type': 'PostalAddress',
addressLocality: '東京都小平市',
addressCountry: 'JP',
},
},
description: e.time,
url: scheduleAbsoluteUrl(`#${e.rowId}`),
};
})
.sort((a, b) => a.startDate.localeCompare(b.startDate))
.slice(0, 40);
const existing = document.getElementById('schedule-event-ldjson');
if (existing) existing.remove();
if (upcoming.length === 0) return;
const script = document.createElement('script');
script.type = 'application/ld+json';
script.id = 'schedule-event-ldjson';
script.textContent = JSON.stringify({
'@context': 'https://schema.org',
'@type': 'ItemList',
name: '小平市のこれからのイベント',
itemListElement: upcoming.map((item, index) => ({
'@type': 'ListItem',
position: index + 1,
item,
})),
});
document.head.appendChild(script);
}
// 件数はフィルターのボタンには出さず、ページ下部にまとめて表示する。
function renderCategorySummary() {
const summaryEl = document.getElementById('schedule-category-summary');
if (!summaryEl) return;
const councilCount = entries.filter(isCouncil).length;
const fields = CATEGORY_DEFS.map((c) => `${c.label}${counts[c.icon] || 0}件`).join('、');
summaryEl.textContent =
`このページに載せているのは、審議会等(会議)${meetingEntries.length}件(うち市議会${councilCount}件)、` +
`イベント${eventEntries.length}件の合計${entries.length}件です。` +
`分野別では、${fields}です(会議とイベントの両方を含みます)。`;
}
buildFilters();
renderCategorySummary();
emitEventStructuredData();
applyFilter();
renderCalendar();
if (selectedDate) showDayDetails(selectedDate);
}
function boot() {
initSchedule();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot, { once: true });
} else {
boot();
}
document.addEventListener('astro:page-load', boot);
</script>
|