Skip to content

Commit 1fe5cac

Browse files
sametbasbugclaude
andcommitted
Put announcements one tap away on a phone
Announcements were injected into the home route only. On a phone that left them behind the bottom bar's More sheet: two taps and a page load. The rail entry that covers this on desktop is hidden at that width, and the new right column panel falls below the entire feed. The header now carries an announcement icon at <=780px, and it opens a bottom sheet in place. Above that width it stays hidden -- the rail entry and the home panel already do this job, and three surfaces for one thing on one screen is the duplication this redesign has been removing. The icon is a link to /duyurular that script upgrades into a sheet opener, so it works before and without JavaScript. It is a <dialog>: focus trap, Escape, and an inert background come from the browser, and writing those by hand is three chances to write them wrong. Content comes from a new public /duyurular/ozet fragment rather than the page shell. The header is on every page and most pages -- /about, /topics, /iletisim -- never touch the worker at all; injecting into the shell would have made the badge present on some pages and absent on others. The endpoint returns HTML, not JSON, so the announcement card keeps one renderer; a client drawing its own card would be a second one. Severity and ids ride on data attributes. The loudest severity wins, so one critical notice is not calmed down by three informational ones next to it, and both icons ship in the markup with CSS choosing between them -- the alternative was a second copy of the icon paths in the client. Read state is localStorage, by id rather than by count: a withdrawn announcement lowers the count and a stored "3 read" would mark a new one as already seen. Costs, measured: 1826 bytes of shell HTML per page (931 trigger, 895 dialog) and 250 bytes of gzipped CSS. Dead .announcement-strip rules paid 1491 raw bytes of that back -- the strip's renderer went in the previous commit and its styles stayed behind. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent c662cfe commit 1fe5cac

8 files changed

Lines changed: 407 additions & 68 deletions

File tree

‎scripts/orbit-browser-tests.mjs‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,44 @@ if (errors.length === 0) {
631631
check(!(await page.locator('.header-mobile-search').isVisible()), `${label}: mobil arama düğmesi masaüstünde görünür kaldı.`);
632632
}
633633

634+
/* Duyuru ikonu ve alt sayfası.
635+
*
636+
* İkon yalnız dar ekranda: masaüstünde sol raydaki "Duyurular" ve ana
637+
* sayfanın sağ kolonundaki panel aynı işi yapıyor.
638+
*
639+
* İçeriğin kendisi burada YOK ve olmaması doğru: duyurular D1'de
640+
* yaşıyor, bu testler statik derlemeye bakıyor ve `/duyurular/ozet`
641+
* isteği burada 404 dönüyor. Ölçtüğümüz şey iskelet — ikonun doğru
642+
* genişlikte durduğu, sayfanın açılıp kapandığı ve istek başarısız
643+
* olduğunda bağlantının bağlantı olarak kaldığı. */
644+
const announceTrigger = page.locator('[data-announcement-trigger]');
645+
check(await announceTrigger.count() === 1, `${label}: duyuru ikonu DOM'da yok.`);
646+
check(
647+
await announceTrigger.isVisible() === (viewport.width <= 780),
648+
`${label}: duyuru ikonu yanlış genişlikte görünüyor.`,
649+
);
650+
check(
651+
await announceTrigger.getAttribute('href') === '/duyurular',
652+
`${label}: duyuru ikonu JS'siz hâlde duyurular sayfasına gitmiyor.`,
653+
);
654+
if (viewport.width <= 780) {
655+
const sheetDialog = page.locator('[data-announcement-sheet]');
656+
check(!(await sheetDialog.evaluate((el) => el.open)), `${label}: duyuru sayfası kendiliğinden açık geldi.`);
657+
await announceTrigger.click();
658+
check(await sheetDialog.evaluate((el) => el.open), `${label}: duyuru sayfası tıklamayla açılmadı.`);
659+
check(
660+
new URL(page.url()).pathname !== '/duyurular',
661+
`${label}: duyuru ikonu sayfayı yerinde açmak yerine gezindi.`,
662+
);
663+
const sheetBox = await sheetDialog.boundingBox();
664+
check(
665+
Boolean(sheetBox) && Math.abs(sheetBox.y + sheetBox.height - viewport.height) <= 1,
666+
`${label}: duyuru sayfası ekranın altına yapışmadı.`,
667+
);
668+
await page.keyboard.press('Escape');
669+
check(!(await sheetDialog.evaluate((el) => el.open)), `${label}: duyuru sayfası Escape ile kapanmadı.`);
670+
}
671+
634672
check(await page.locator('html').getAttribute('data-theme') === 'light', `${label}: başlangıç teması light değil.`);
635673
await page.locator('[data-theme-toggle]').click();
636674
check(await page.locator('html').getAttribute('data-theme') === 'dark', `${label}: tema dark durumuna geçmedi.`);
@@ -933,7 +971,11 @@ if (errors.length === 0) {
933971
check(await page.locator('h1').first().textContent() === 'Duyurular', `${label}: duyurular sayfası başlığı yok.`);
934972
check(await page.locator('.announcement-empty').isVisible(), `${label}: duyurular sayfasında boş hâl görünmüyor.`);
935973
check(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `${label}: duyurular sayfası yatay taşıyor.`);
936-
check(await page.locator('.announcement-strip').count() === 0, `${label}: duyuru yokken şerit basılmış.`);
974+
/* Şerit kalktı: duyuruları ana sayfada sağ kolondaki panel, dar
975+
* ekranda header'daki ikon taşıyor. Markup'ının geri sızmadığını
976+
* ölçmeye devam ediyoruz — geri gelirse akışın tepesinde ikinci bir
977+
* duyuru yüzeyi olur. */
978+
check(await page.locator('.announcement-strip').count() === 0, `${label}: kaldırılan duyuru şeridi geri gelmiş.`);
937979
}
938980
await context.close();
939981
}));

‎scripts/orbit-public-page-tests.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,60 @@ describe('Orbit dynamic public pages', () => {
600600
assert.match(loud, /süreli yeniden bağlanabilir/u);
601601
});
602602

603+
/* Duyuru özeti. Mobil header'daki ikon bunu okuyor ve rozetin ne
604+
* göstereceği tamamen buradan çıkıyor: şiddet ve kimlikler. */
605+
test('serves the announcement summary with severity and ids for the badge', async () => {
606+
const quiet = await serveDynamicPublicPage(
607+
new Request('https://orbit.example/duyurular/ozet'),
608+
assets,
609+
new FakePublicRepository([]),
610+
);
611+
assert.ok(quiet);
612+
const quietBody = await quiet.text();
613+
assert.match(quietBody, /data-severity="none"/u);
614+
assert.match(quietBody, /data-ids=""/u);
615+
assert.match(quietBody, /yürürlükte olan bir duyuru yok/u);
616+
617+
const loudResponse = await serveDynamicPublicPage(
618+
new Request('https://orbit.example/duyurular/ozet'),
619+
assets,
620+
new FakePublicRepository([], [announcement()]),
621+
);
622+
assert.ok(loudResponse);
623+
const loud = await loudResponse.text();
624+
assert.match(loud, /data-severity="warning"/u);
625+
assert.match(loud, /data-ids="announcement-1"/u);
626+
/* Kartın kendisi paylaşılan renderer'dan geliyor: istemci JSON alıp
627+
* kendi kartını çizseydi duyuruların ikinci bir renderer'ı olurdu. */
628+
assert.match(loud, /announcement-brief/u);
629+
assert.match(loud, /süreli yeniden bağlanabilir/u);
630+
assert.equal(loudResponse.headers.get('content-type'), 'text/html; charset=utf-8');
631+
assert.equal(loudResponse.headers.get('cache-control'), 'public, max-age=60');
632+
});
633+
634+
/* En yüksek şiddet kazanıyor. Sıralamayı ölçmenin sebebi: bir kritik
635+
* duyuru, yanındaki üç bilgi duyurusu yüzünden sakin bir ikona
636+
* dönüşmemeli. Sayının değil sıranın iddiası bu, o yüzden her kademe
637+
* kendi karışımıyla sınanıyor. */
638+
for (const [expected, severities] of [
639+
['critical', ['info', 'critical', 'warning']],
640+
['warning', ['info', 'warning', 'info']],
641+
['info', ['info', 'info']],
642+
] as const) {
643+
test(`the badge takes the loudest severity: ${severities.join('+')} -> ${expected}`, async () => {
644+
const response = await serveDynamicPublicPage(
645+
new Request('https://orbit.example/duyurular/ozet'),
646+
assets,
647+
new FakePublicRepository([], severities.map((severity, index) => announcement({
648+
id: `announcement-${index}`,
649+
severity,
650+
}))),
651+
);
652+
assert.ok(response);
653+
assert.match(await response.text(), new RegExp(`data-severity="${expected}"`, 'u'));
654+
});
655+
}
656+
603657
test('does not allow Markdown or attribute content to inject scripts', () => {
604658
const html = renderPublicRecordCard(record({
605659
bodyMarkdown: '<script>alert(1)</script>\n\n[tehlikeli](javascript:alert(1))',

‎scripts/orbit-site-tests.mjs‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -737,8 +737,14 @@ check(!savedHtml.includes('data-saved-card='), 'Kaydedilenler bütün kayıt kar
737737
* Tavanlar bu turdan ÖNCEKİ değerlerin üstüne kabuk maliyeti eklenerek
738738
* kuruldu — yani sayfanın kendi gövdesine tanınan pay değişmedi. Bugünkü
739739
* gövdeler 21_376 ve 20_608; eski tavanlar 24_000 ve 22_000 idi, o pay
740-
* olduğu gibi duruyor. */
741-
const SHELL_BUDGET = 3219 + 2631;
740+
* olduğu gibi duruyor.
741+
*
742+
* Üçüncü kabuk parçası duyuru sayfası: tetikleyici 931, `<dialog>` 895, toplam
743+
* 1826 byte. Yalnız dar ekranda kullanılıyor ama her sayfanın HTML'inde
744+
* duruyor — kabuk tek ve viewport'a göre değişmiyor. Tetikleyicinin yarısı iki
745+
* ikon: hangisinin görüneceğine şiddet karar veriyor ve alternatif, ikon
746+
* yollarının istemcide ikinci bir kopyası olurdu. */
747+
const SHELL_BUDGET = 3219 + 2631 + 1826;
742748
check(
743749
searchHtml.length < 24_000 + SHELL_BUDGET,
744750
`Arama HTML bütçesi aşıldı: ${searchHtml.length} byte.`,
@@ -824,7 +830,12 @@ for (const post of publicPosts) {
824830
* Şu an en ağır sayfa /messages: 13.453 byte paylaşılan bundle + 1.094 byte
825831
* sayfaya özel, toplam 14.547. Akış ve gönderi sayfaları 13.453'te kalıyor.
826832
*
827-
* Tavan 15.500'den 15.600'e çıktı. Gerekçesi ölçülmüş: üç bölgeli yerleşim
833+
* Tavan 15.600'den 15.850'ye çıktı: duyuru paneli ve mobil duyuru sayfası
834+
* sıkıştırılmış CSS'e ekledi. Bu turda ölü `.announcement-strip` kuralları
835+
* (1491 byte ham) silinerek bir kısmı geri kazanıldı — şerit renderer'ı
836+
* kalktığı hâlde stilleri duruyordu.
837+
*
838+
* Bir önceki tur: tavan 15.500'den 15.600'e çıktı. Gerekçesi ölçülmüş: üç bölgeli yerleşim
828839
* (esneyen ray oluğu, 1480px bandı, header'ın çerçeveyle aynı ifadeyi
829840
* taşıması) sıkıştırılmış CSS'e 75 byte ekledi. Bu turda 34 byte ölü
830841
* `.context-rail` kuralı silinerek geri kazanıldı; kalanı yeni yapının
@@ -849,7 +860,7 @@ for (const file of htmlFiles) {
849860
if (gzip > heaviest.gzip) heaviest = { page: path.relative(DIST_DIR, file), raw, gzip };
850861
}
851862
check(heaviest.gzip > 0, 'Hiçbir sayfa derlenmiş CSS bundle\'ına bağlanmıyor.');
852-
check(heaviest.gzip < 15_600, `Gzip CSS bütçesi aşıldı: ${heaviest.page} ${heaviest.gzip} byte.`);
863+
check(heaviest.gzip < 15_850, `Gzip CSS bütçesi aşıldı: ${heaviest.page} ${heaviest.gzip} byte.`);
853864
check(heaviest.raw < 92_000, `Ham CSS emniyet sınırını aştı: ${heaviest.page} ${heaviest.raw} byte.`);
854865

855866
/* Font bütçesi.

‎src/components/Header.astro‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,26 @@ const searchQuery = Astro.url.searchParams.get('q') ?? '';
114114
<a class:list={['header-mobile-search', { active: normalizedPath === '/search' }]} href="/search" aria-label="Orbit'te ara" aria-current={normalizedPath === '/search' ? 'page' : undefined}>
115115
<Icon name="search" size={17} />
116116
</a>
117+
{/*
118+
Duyuru ikonu yalnız dar ekranda. Masaüstünde iki yol zaten var: sol
119+
raydaki "Duyurular" ve ana sayfanın sağ kolonundaki panel. Mobilde
120+
ikisi de yok — ray gizli, panel akışın en altına düşüyor — ve
121+
"Duyurular" alt çubuğun "Diğer" menüsünde, iki dokunuş ve bir sayfa
122+
yüklemesi uzakta.
123+
124+
Bir bağlantı, düğme değil: JavaScript inmeden de çalışıyor ve
125+
`/duyurular` sayfasına götürüyor. Script indiğinde tıklamayı devralıp
126+
sayfayı yerinde açıyor.
127+
128+
İki ikon birden basılıyor, hangisinin görüneceğine `data-severity`
129+
karar veriyor. Alternatif, istemcinin ikonu kendi çizmesiydi — o da
130+
ikon yollarının ikinci bir kopyası demekti.
131+
*/}
132+
<a class="header-announcements" href="/duyurular" data-announcement-trigger aria-label="Duyurular">
133+
<Icon name="info" size={17} className="announcement-icon-info" />
134+
<Icon name="alert" size={17} className="announcement-icon-alert" />
135+
<span class="header-announcements-dot" aria-hidden="true"></span>
136+
</a>
117137
<ThemeToggle />
118138
<a class="equinox-link" href="https://equinox.sametbasbug.dev">
119139
<span class="equinox-link-dot" aria-hidden="true"></span>
@@ -122,6 +142,28 @@ const searchQuery = Astro.url.searchParams.get('q') ?? '';
122142
</a>
123143
</div>
124144
</div>
145+
146+
{/*
147+
Duyuru sayfası. `<dialog>` bilerek: odak tuzağı, Escape ile kapanma ve
148+
arka planın erişilemez olması tarayıcıdan geliyor — üçünü elle yazmak
149+
üçünü de yanlış yazma fırsatı demek.
150+
151+
İçi boş geliyor ve `/duyurular/ozet`ten doluyor. Kabuğa gömmek, duyuru
152+
markup'ını her sayfanın HTML'ine eklemek olurdu ve o sayfaların çoğu
153+
worker'dan hiç geçmiyor.
154+
*/}
155+
<dialog class="announcement-sheet" data-announcement-sheet aria-labelledby="announcement-sheet-title">
156+
<header class="announcement-sheet-head">
157+
<h2 id="announcement-sheet-title">Duyurular</h2>
158+
<button type="button" data-announcement-close aria-label="Kapat">
159+
<Icon name="chevron" size={18} />
160+
</button>
161+
</header>
162+
<div class="announcement-sheet-body" data-announcement-sheet-body>
163+
<p class="announcement-panel-empty">Duyurular yükleniyor…</p>
164+
</div>
165+
<a class="announcement-sheet-all" href="/duyurular">Duyurular sayfasını aç</a>
166+
</dialog>
125167
</header>
126168

127169
<style>
@@ -139,6 +181,77 @@ const searchQuery = Astro.url.searchParams.get('q') ?? '';
139181
</style>
140182

141183
<script>
184+
/* Duyuru rozeti ve sayfası.
185+
*
186+
* Yalnız ikonun görünür olduğu genişlikte çalışıyor: masaüstünde ikon
187+
* gizli ve o istek boşuna gider.
188+
*
189+
* Okundu bilgisi `localStorage`'da, kimliklerle. Sunucuda tutmuyoruz —
190+
* ziyaretçi anonim ve bir rozet için hesap açtırmanın anlamı yok. Kimlikle
191+
* saklamanın sebebi sayıyla saklamamak: geri çekilen bir duyuru sayıyı
192+
* düşürüyor ve "3 okundu" kaydı yeni duyuruyu okunmuş sayıyordu. */
193+
const trigger = document.querySelector<HTMLAnchorElement>('[data-announcement-trigger]');
194+
const sheetDialog = document.querySelector<HTMLDialogElement>('[data-announcement-sheet]');
195+
const sheetBody = document.querySelector<HTMLElement>('[data-announcement-sheet-body]');
196+
197+
if (trigger && sheetDialog && sheetBody && getComputedStyle(trigger).display !== 'none') {
198+
const READ_KEY = 'orbit-announcements-read';
199+
200+
const readIds = (): Set<string> => {
201+
try {
202+
return new Set((localStorage.getItem(READ_KEY) ?? '').split(',').filter(Boolean));
203+
} catch {
204+
return new Set();
205+
}
206+
};
207+
208+
let currentIds: string[] = [];
209+
210+
void (async () => {
211+
try {
212+
const response = await fetch('/duyurular/ozet', { headers: { accept: 'text/html' } });
213+
if (!response.ok) return;
214+
const template = document.createElement('template');
215+
template.innerHTML = await response.text();
216+
const state = template.content.querySelector<HTMLElement>('[data-announcement-state]');
217+
if (!state) return;
218+
219+
currentIds = (state.dataset.ids ?? '').split(',').filter(Boolean);
220+
trigger.dataset.severity = state.dataset.severity ?? 'none';
221+
sheetBody.replaceChildren(...state.childNodes);
222+
223+
const seen = readIds();
224+
const unread = currentIds.filter((id) => !seen.has(id));
225+
if (unread.length > 0) trigger.dataset.unread = String(unread.length);
226+
} catch {
227+
/* Ağ yoksa bağlantı bağlantı olarak kalıyor: tıklayan `/duyurular`
228+
sayfasına gider. Sessiz başarısızlık burada doğru davranış —
229+
duyuru rozeti bir hata mesajı göstermeye değecek kadar kritik
230+
değil ve gösterse her çevrimdışı sekmede bağırırdı. */
231+
}
232+
})();
233+
234+
trigger.addEventListener('click', (event) => {
235+
/* Yeni sekmede açmak isteyen kişinin niyetini çalmıyoruz. */
236+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return;
237+
if (!sheetDialog.showModal) return;
238+
event.preventDefault();
239+
sheetDialog.showModal();
240+
delete trigger.dataset.unread;
241+
try {
242+
localStorage.setItem(READ_KEY, currentIds.join(','));
243+
} catch {}
244+
});
245+
246+
sheetDialog.querySelector('[data-announcement-close]')?.addEventListener('click', () => sheetDialog.close());
247+
/* Sayfanın dışına — yani karartmaya — basmak da kapatıyor. `<dialog>`
248+
tıklamayı kendi kutusunda alıyor, o yüzden hedefin diyalogun kendisi
249+
olması "boşluğa basıldı" demek. */
250+
sheetDialog.addEventListener('click', (event) => {
251+
if (event.target === sheetDialog) sheetDialog.close();
252+
});
253+
}
254+
142255
/* `<details>` dışarı tıklanınca kendiliğinden kapanmıyor. Menü açık kalıp
143256
sayfanın üstünde durursa, kişi onu kapatmak için tam da az önce bastığı
144257
düğmeyi bulmak zorunda kalıyor. Escape de kapatıyor. */

‎src/server/public/response.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,46 @@ async function renderFeedRoute(
208208
return htmlResponse(shell, html, request.method === 'HEAD');
209209
}
210210

211+
/**
212+
* Duyuruların HTML parçası. Mobil header'daki ikon ve açtığı sayfa bunu okur.
213+
*
214+
* Neden ayrı bir uç nokta: header her sayfada duruyor ama duyurular yalnız
215+
* ana sayfa route'unda enjekte ediliyordu — ve `/about`, `/topics`, `/iletisim`
216+
* gibi sayfalar worker'dan hiç geçmiyor, doğrudan statik dosya olarak
217+
* gidiyorlar. Kabuğa enjekte etmek rozeti bazı sayfalarda var, bazılarında yok
218+
* hâline getirirdi.
219+
*
220+
* JSON değil HTML dönüyor çünkü duyurunun görünüşü tek yerden gelmeli:
221+
* istemci JSON alıp kendi kartını çizseydi duyuruların İKİNCİ bir renderer'ı
222+
* doğardı ve ikisi zamanla ayrışırdı.
223+
*
224+
* Şiddet ve kimlikler öznitelikte: rozetin hangi ikonu göstereceği ve neyin
225+
* okunmuş sayılacağı bunlardan çıkıyor. Okundu bilgisi istemcide duruyor —
226+
* anonim ziyaretçi için sunucuda durum tutmuyoruz.
227+
*/
228+
async function renderAnnouncementSummaryRoute(repository: PublicRepository): Promise<Response> {
229+
const announcements = await repository.listPublicAnnouncements(Date.now());
230+
/* En yüksek şiddet kazanıyor: bir kritik duyuru, yanındaki üç bilgi
231+
* duyurusu yüzünden sakin bir ikona dönüşmemeli. */
232+
const severity = announcements.some((item) => item.severity === 'critical')
233+
? 'critical'
234+
: announcements.some((item) => item.severity === 'warning')
235+
? 'warning'
236+
: announcements.length > 0 ? 'info' : 'none';
237+
const ids = announcements.map((item) => item.id).join(',');
238+
const body = `<div data-announcement-state data-severity="${severity}" data-ids="${escapeHtml(ids)}">${renderAnnouncementPanel(announcements)}</div>`;
239+
return new Response(body, {
240+
headers: {
241+
'content-type': 'text/html; charset=utf-8',
242+
/* Duyuru nadir değişir ve bu parça her sayfa açılışında isteniyor.
243+
* Kenarda bir dakika tutmak yükü düşürüyor; bir dakikalık gecikme
244+
* yürürlüğe girmiş bir duyuru için kabul edilebilir. */
245+
'cache-control': 'public, max-age=60',
246+
'x-content-type-options': 'nosniff',
247+
},
248+
});
249+
}
250+
211251
async function renderAnnouncementsRoute(
212252
request: Request,
213253
assets: AssetsBinding,
@@ -341,6 +381,10 @@ export async function serveDynamicPublicPage(
341381
return await renderFeedRoute(request, assets, repository, feedMatch[1]);
342382
}
343383

384+
if (url.pathname === '/duyurular/ozet') {
385+
return await renderAnnouncementSummaryRoute(repository);
386+
}
387+
344388
if (url.pathname === '/duyurular' || url.pathname === '/duyurular/') {
345389
return await renderAnnouncementsRoute(request, assets, repository);
346390
}

0 commit comments

Comments
 (0)