-
Notifications
You must be signed in to change notification settings - Fork 10.7k
Expand file tree
/
Copy pathindex.astro
More file actions
2316 lines (2193 loc) · 101 KB
/
Copy pathindex.astro
File metadata and controls
2316 lines (2193 loc) · 101 KB
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
import Page from '../page';
import '../globals.css';
import { createRequire } from 'node:module';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import FaviconLinks from '../_components/favicon-links.astro';
import SiteAnalytics from '../_components/site-analytics.astro';
import ResourceHints from '../_components/resource-hints.astro';
import LocaleSwitcherScript from '../_components/locale-switcher-script.astro';
import PreciseLazyload from '../_components/precise-lazyload.astro';
import DownloadEngagementPrompt from '../_components/download-engagement-prompt.astro';
import {
heroBgImage,
heroBgSrcset,
ogDefaultImage,
OG_IMAGE_HEIGHT,
OG_IMAGE_WIDTH,
} from '../image-assets';
import {
LANDING_LOCALES,
alternateLinksForPath,
getHomeFaq,
getHomeSeo,
getLocaleDefinition,
localeFromPath,
localePath,
type LandingLocaleCode,
} from '../i18n';
import { getCatalogCounts } from '../_lib/catalog';
import { getGithubRepoMeta } from '../_lib/github';
import { clampDescription } from '../_lib/clamp-description';
import { DEEPSEEK_V4_PRO_CAMPAIGN } from '../_lib/deepseek-v4-pro-campaign';
import { getPricingCampaignContent } from '../_lib/pricing-campaign-content';
import { getHomeCampaignContent } from '../_lib/home-campaign-content';
const locale: LandingLocaleCode = localeFromPath(Astro.url.pathname);
const localeDef = getLocaleDefinition(locale);
const counts = await getCatalogCounts();
const github = await getGithubRepoMeta();
const { title, description } = getHomeSeo(locale, counts);
// Clamp the meta/OG/Twitter description; the full string still feeds JSON-LD.
const metaDescription = clampDescription(description);
const canonical = new URL(localePath(locale), Astro.site).toString();
const origin = Astro.site?.toString() ?? 'https://open-design.ai/';
const logoUrl = new URL('/android-chrome-512x512.png', Astro.site).toString();
const alternateLinks = alternateLinksForPath('/').map((entry) => ({
...entry,
href: new URL(entry.hrefPath, Astro.site).toString(),
}));
const xDefaultHref = new URL('/', Astro.site).toString();
const REPO_URL = 'https://github.com/nexu-io/open-design';
const RELEASES_URL = `${REPO_URL}/releases`;
const ISSUES_URL = `${REPO_URL}/issues`;
const DOCS_URL = `${REPO_URL}#readme`;
const LICENSE_URL = `${REPO_URL}/blob/main/LICENSE`;
const DISCORD_URL = 'https://discord.gg/mHAjSMV6gz';
const OFFICIAL_URL = `${origin}official/`;
const websiteSchema = {
'@type': 'WebSite',
'@id': `${origin}#website`,
name: 'OpenDesign',
alternateName: ['Open Design', 'open-design', 'opendesign', 'Open Design AI', 'OpenDesign AI', 'OD'],
url: origin,
inLanguage: localeDef.htmlLang,
availableLanguage: LANDING_LOCALES.map((entry) => entry.htmlLang),
publisher: { '@id': `${origin}#organization` },
};
const organizationSchema = {
'@type': 'Organization',
'@id': `${origin}#organization`,
name: 'OpenDesign',
alternateName: ['Open Design', 'open-design', 'opendesign', 'Open Design AI', 'OpenDesign AI', 'OD', 'nexu-io/open-design'],
url: origin,
logo: {
'@type': 'ImageObject',
url: logoUrl,
width: 512,
height: 512,
},
// Five canonical pillars — Google uses sameAs to merge entity claims
// across sources. Listing the official site, GitHub repo, release
// feed, README docs, and Discord here prevents capture sites from
// splitting the brand entity.
sameAs: [REPO_URL, RELEASES_URL, DOCS_URL, DISCORD_URL, OFFICIAL_URL],
};
const softwareSchema = {
'@type': 'SoftwareApplication',
'@id': `${origin}#software`,
name: 'OpenDesign',
alternateName: ['Open Design', 'open-design', 'opendesign', 'Open Design AI', 'OpenDesign AI', 'OD'],
description,
url: origin,
inLanguage: localeDef.htmlLang,
applicationCategory: 'DesignApplication',
operatingSystem: 'macOS, Windows',
license: 'https://www.apache.org/licenses/LICENSE-2.0',
softwareVersion: github.versionLabel,
downloadUrl: RELEASES_URL,
installUrl: `${origin}quickstart/`,
softwareHelp: { '@type': 'CreativeWork', url: DOCS_URL },
releaseNotes: RELEASES_URL,
codeRepository: REPO_URL,
discussionUrl: DISCORD_URL,
issueTracker: ISSUES_URL,
sameAs: [REPO_URL, RELEASES_URL, DOCS_URL, DISCORD_URL, OFFICIAL_URL, LICENSE_URL],
offers: {
'@type': 'Offer',
price: '0',
priceCurrency: 'USD',
},
publisher: { '@id': `${origin}#organization` },
};
const homepageGraph = {
'@context': 'https://schema.org',
'@graph': [websiteSchema, organizationSchema, softwareSchema],
};
const faq = getHomeFaq(locale, { origin, repo: REPO_URL });
const campaignPricingHref = localePath(locale, '/pricing/');
const campaignContent = getPricingCampaignContent(locale);
const homeCampaignContent = getHomeCampaignContent(locale);
const campaignCopy = {
badge: campaignContent.windowLabel,
title: homeCampaignContent.title,
detail: homeCampaignContent.detail,
windowLabel: campaignContent.windowLabel,
dayUnit: campaignContent.dayUnit,
linkLabel: campaignContent.linkLabel,
closeLabel: campaignContent.closeLabel,
};
const pageHtml = renderToStaticMarkup(
Page({ counts, github, locale, faq }) as ReturnType<typeof createElement>,
);
// The homepage globe (cobe) and the Method-section FallingText (matter-js) are
// below-the-fold progressive enhancements. Rather than inline their full
// runtimes (~96KB combined) into every homepage document, they are vendored
// into `public/enhancers/*.js` (see `scripts/vendor-enhancers.ts`) and injected
// ON DEMAND by the loaders at the end of <body> — only once their section
// nears the viewport, and never at all for reduced-motion readers in the
// physics case. The site still ships ZERO Astro-bundled / ES-module JavaScript;
// these are hand-vendored classic scripts, not `/_astro/*.js` build output, so
// the `Verify zero external JavaScript` gate's intent holds (it greps the built
// HTML for a literal external-script tag, which the runtime injection never
// emits). The `?v=` query busts the immutable edge cache when versions bump.
const requireFromHere = createRequire(import.meta.url);
const matterEnhancerUrl = `/enhancers/matter.min.js?v=${
(requireFromHere('matter-js/package.json') as { version: string }).version
}`;
const cobeEnhancerUrl = `/enhancers/cobe.js?v=${
(requireFromHere('cobe/package.json') as { version: string }).version
}`;
---
<!doctype html>
<html lang={localeDef.htmlLang} dir={localeDef.dir}>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#efe7d2" />
{/*
* First in <head> on purpose: a non-English visitor on the English root is
* redirected to their locale before the browser streams the rest of the
* document, so it aborts the wasted first-load instead of fully rendering /
* and then bouncing to /zh/ (etc.). The switcher UI wiring inside defers
* itself to DOMContentLoaded. Localized roots and canonical / autoredirect
* off pages no-op, so English/crawler traffic pays only a tiny inline read.
*/}
<LocaleSwitcherScript />
<title>{title}</title>
<meta name="description" content={metaDescription} />
<link rel="canonical" href={canonical} />
{alternateLinks.map((entry) => (
<link rel="alternate" hreflang={entry.hreflang} href={entry.href} />
))}
<link rel="alternate" hreflang="x-default" href={xDefaultHref} />
<FaviconLinks />
<ResourceHints />
<SiteAnalytics />
{/*
* Hero LCP preload. Cloudflare Pages turns this <link rel="preload"> into
* a 103 Early Hints response automatically when Early Hints is enabled in
* the dashboard, so the browser starts the image fetch before the HTML
* body finishes streaming.
*
* Only emitted on `/` — the rest of the site uses lighter hero treatment.
*/}
<link
rel="preload"
as="image"
href={heroBgImage}
imagesrcset={heroBgSrcset}
imagesizes="100vw"
fetchpriority="high"
/>
<meta property="og:type" content="website" />
<meta property="og:site_name" content="OpenDesign" />
<meta property="og:title" content={title} />
<meta property="og:description" content={metaDescription} />
<meta property="og:url" content={canonical} />
<meta property="og:image" content={ogDefaultImage} />
<meta property="og:image:width" content={String(OG_IMAGE_WIDTH)} />
<meta property="og:image:height" content={String(OG_IMAGE_HEIGHT)} />
<meta property="og:image:type" content="image/png" />
<meta property="og:locale" content={localeDef.ogLocale} />
{LANDING_LOCALES.filter((entry) => entry.code !== locale).map((entry) => (
<meta property="og:locale:alternate" content={entry.ogLocale} />
))}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={metaDescription} />
<meta name="twitter:image" content={ogDefaultImage} />
{/*
* Single @graph JSON-LD block — WebSite + Organization +
* SoftwareApplication.
*/}
<script is:inline type="application/ld+json" set:html={JSON.stringify(homepageGraph)} />
</head>
<body>
<div class="home-campaign-banner" data-home-campaign-banner data-campaign-window-label={campaignCopy.windowLabel} data-campaign-day-unit={campaignCopy.dayUnit} data-campaign-start-at={DEEPSEEK_V4_PRO_CAMPAIGN.startAt} data-campaign-end-at={DEEPSEEK_V4_PRO_CAMPAIGN.endAtExclusive} hidden>
<a class="home-campaign-banner__link" href={campaignPricingHref} aria-label={`${campaignCopy.title} · ${campaignCopy.linkLabel}`}>
<span class="home-campaign-banner__badge" data-home-campaign-countdown>{campaignCopy.badge}</span>
<span class="home-campaign-banner__divider" aria-hidden="true">|</span>
<strong>{campaignCopy.title}</strong>
<span class="home-campaign-banner__divider" aria-hidden="true">|</span>
<span class="home-campaign-banner__detail">{campaignCopy.detail}</span>
<span class="home-campaign-banner__cta" aria-hidden="true">→</span>
</a>
<button class="home-campaign-banner__close" type="button" aria-label={campaignCopy.closeLabel} data-home-campaign-close>×</button>
</div>
<Fragment set:html={pageHtml} />
<DownloadEngagementPrompt locale={locale} />
<style is:global>
:root { --home-campaign-banner-height: 0px; }
html.home-campaign-banner-active { --home-campaign-banner-height: 44px; }
.home-campaign-banner {
position: fixed;
z-index: 70;
top: 0;
left: 0;
right: 0;
min-height: var(--home-campaign-banner-height);
border-bottom: 1px solid color-mix(in srgb, #78ea57 36%, var(--line));
color: var(--ink);
background: #d8ffb5;
font-family: var(--sans);
font-size: 13px;
line-height: 1.25;
text-decoration: none;
box-shadow: 0 6px 24px rgb(38 38 38 / 6%);
}
.home-campaign-banner__link {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
min-height: var(--home-campaign-banner-height);
padding: 8px 64px 8px 24px;
color: inherit;
text-decoration: none;
}
.home-campaign-banner__badge {
display: inline-flex;
align-items: center;
padding: 4px 9px;
border-radius: 999px;
color: #102b05;
background: #68f22e;
font-size: 11px;
font-weight: 800;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.home-campaign-banner__divider { color: color-mix(in srgb, var(--ink) 26%, transparent); }
.home-campaign-banner__detail { color: var(--ink-mute); }
.home-campaign-banner__cta {
flex: 0 0 auto;
padding: 5px 10px;
border-radius: 999px;
color: #f7f7f3;
background: var(--ink);
font-weight: 750;
white-space: nowrap;
}
.home-campaign-banner__link:hover .home-campaign-banner__cta { transform: translateX(1px); }
.home-campaign-banner__close {
position: absolute;
top: 50%;
right: 14px;
z-index: 1;
display: grid;
place-items: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: 50%;
color: var(--ink);
background: transparent;
font: 19px/1 var(--sans);
opacity: .72;
cursor: pointer;
transform: translateY(-50%);
}
.home-campaign-banner__close:hover { background: rgb(38 38 38 / 7%); opacity: 1; }
.home-campaign-banner__close:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; opacity: 1; }
html.home-campaign-banner-dismissed { --home-campaign-banner-height: 0px; }
html.home-campaign-banner-dismissed .home-campaign-banner { display: none; }
.site-chrome { top: var(--home-campaign-banner-height); }
@media (max-width: 680px) {
html.home-campaign-banner-active { --home-campaign-banner-height: 52px; }
.home-campaign-banner__link {
justify-content: flex-start;
gap: 8px;
padding: 8px 48px 8px 14px;
font-size: 12px;
}
.home-campaign-banner__divider,
.home-campaign-banner__detail { display: none; }
.home-campaign-banner__cta { margin-left: auto; }
.home-campaign-banner__close { right: 10px; }
.hero { padding-top: calc(92px + var(--home-campaign-banner-height)); }
}
</style>
<script is:inline>
(() => {
const dismissKey = 'open-design:home-campaign-banner-dismissed:deepseek-v4-pro-fixed-window-countdown-v1';
const banner = document.querySelector('[data-home-campaign-banner]');
const campaignLink = banner?.querySelector('.home-campaign-banner__link');
const countdown = document.querySelector('[data-home-campaign-countdown]');
const close = document.querySelector('[data-home-campaign-close]');
const windowLabel = banner?.getAttribute('data-campaign-window-label') || 'Ends in';
const dayUnit = banner?.getAttribute('data-campaign-day-unit') || 'd';
const startAt = Date.parse(banner?.getAttribute('data-campaign-start-at') || '');
const endAt = Date.parse(banner?.getAttribute('data-campaign-end-at') || '');
const formatRemaining = (remainingMs) => {
const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const time = `${days}${dayUnit} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
return time;
};
let dismissed = false;
try {
if (window.localStorage.getItem(dismissKey) === '1') {
dismissed = true;
document.documentElement.classList.add('home-campaign-banner-dismissed');
}
} catch {}
let impressionTracked = false;
const updateCampaignVisibility = () => {
const now = Date.now();
const active = now >= startAt && now < endAt;
const visible = active && !dismissed;
if (banner) banner.hidden = !visible;
document.documentElement.classList.toggle('home-campaign-banner-active', visible);
if (!active || !countdown) return active;
const remainingMs = endAt - now;
countdown.textContent = `${windowLabel} ${formatRemaining(remainingMs)}`;
if (visible && !impressionTracked && typeof window.__odTrack === 'function') {
impressionTracked = true;
window.__odTrack('surface_view', {
page_name: 'landing_home', area: 'campaign_banner',
element: 'deepseek_v4_pro', campaign_id: 'deepseek_v4_pro',
user_state: 'unknown',
});
}
return active;
};
updateCampaignVisibility();
const campaignTimer = window.setInterval(updateCampaignVisibility, 1000);
window.addEventListener('pagehide', () => {
window.clearInterval(campaignTimer);
}, { once: true });
campaignLink?.addEventListener('click', (event) => {
const eligible = Date.now() >= startAt && Date.now() < endAt;
const attribution = eligible
? window.__odRecordCampaignEntry?.('landing_home_banner', 'deepseek_v4_pro')
: undefined;
window.__odTrack?.('ui_click', {
page_name: 'landing_home',
area: 'campaign_banner',
element: 'open_pricing',
...(eligible ? { campaign_id: 'deepseek_v4_pro' } : {}),
user_state: 'unknown',
...(attribution || {}),
});
if (attribution && window.__odAttributedUrl) {
event.preventDefault();
window.location.href = window.__odAttributedUrl(campaignLink.href, attribution);
}
});
close?.addEventListener('click', () => {
const eligible = Date.now() >= startAt && Date.now() < endAt;
window.__odTrack?.('ui_click', {
page_name: 'landing_home',
area: 'campaign_banner',
element: 'close',
...(eligible ? { campaign_id: 'deepseek_v4_pro' } : {}),
user_state: 'unknown',
});
document.documentElement.classList.add('home-campaign-banner-dismissed');
document.documentElement.classList.remove('home-campaign-banner-active');
if (banner) banner.hidden = true;
dismissed = true;
try { window.localStorage.setItem(dismissKey, '1'); } catch {}
});
})();
</script>
{/*
* Tighter than the catalog default (1500px): the homepage's heavy
* below-the-fold art — full-bleed section backdrops, product shots — must
* not join the initial request burst and starve the hero LCP of bandwidth.
* 600px still pre-loads roughly one viewport ahead so scrolling stays warm.
*/}
<PreciseLazyload imgRootMargin="600px 0px" />
{/*
* Enhancement infrastructure — defined before any enhancer runs so the
* below-the-fold defer helpers are available to every script that follows.
*/}
<script is:inline define:vars={{ matterEnhancerUrl, cobeEnhancerUrl }}>
window.__enhancerUrls = { matter: matterEnhancerUrl, cobe: cobeEnhancerUrl };
// Run `cb` once any element matching `selector` nears the viewport (one
// shot). Used to defer below-the-fold enhancers whose init eagerly pulls
// heavy art — the Labs dock preloads its ~500KB of preview stills, the
// contributor orbit builds ~350KB of avatars — so that art no longer
// competes with the hero LCP for bandwidth on first load.
window.__whenNear = (selector, cb, rootMargin) => {
const els = document.querySelectorAll(selector);
if (!els.length) return;
if (!('IntersectionObserver' in window)) {
cb();
return;
}
const io = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
io.disconnect();
cb();
}
},
{ rootMargin: rootMargin || '0px 0px 150% 0px' },
);
els.forEach((el) => io.observe(el));
};
// On-demand loader for the vendored enhancement runtimes (matter-js /
// cobe). Injects each classic script at most once and resolves once it
// has attached its global (`window.Matter` / `window.__cobe`). The script
// element is created at runtime (never authored as static markup), so the
// built HTML carries no external-script tag and the `Verify zero external
// JavaScript` gate stays green while ~96KB of decorative runtime leaves
// the critical document.
window.__loadEnhancer = (src) => {
const cache = (window.__enhancerCache = window.__enhancerCache || {});
return (
cache[src] ||
(cache[src] = new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = src;
s.async = true;
s.onload = () => resolve();
s.onerror = reject;
document.head.appendChild(s);
}))
);
};
</script>
<script is:inline>
(() => {
const formatStars = (count) => {
if (!Number.isFinite(count) || count <= 0) return '0';
if (count < 1000) return String(count);
return `${(count / 1000).toFixed(1).replace(/\.0$/, '')}K+`;
};
// Pull a clean 'v0.3.0'-style label from a GitHub release record.
// We prefer release.name (e.g. 'OpenDesign 0.3.0') because that's
// what we hand-author; fall back to tag_name (e.g.
// 'open-design-v0.3.0') with the project prefix stripped.
//
// Expected input shapes (release.name / release.tag_name):
// { name: 'OpenDesign 0.3.0', tag_name: 'v0.3.0' } → 'v0.3.0'
// { name: 'OpenDesign v0.3.0', tag_name: 'open-design-v0.3.0' } → 'v0.3.0'
// { name: '0.3.0-beta.1', tag_name: 'open-design_0.3.0' } → 'v0.3.0-beta.1' (name wins)
// { name: null, tag_name: 'open-design-v0.3.0' } → 'v0.3.0' (tag fallback)
// { name: null, tag_name: null } → null (caller skips)
const formatVersion = (release) => {
const fromTag = (tag) => {
if (typeof tag !== 'string') return null;
const cleaned = tag.replace(/^open-design[-_]?v?/i, '').trim();
return cleaned ? `v${cleaned.replace(/^v/, '')}` : null;
};
const fromName = (name) => {
if (typeof name !== 'string') return null;
const m = name.match(/(\d+\.\d+\.\d+(?:[-+][\w.]+)?)/);
return m ? `v${m[1]}` : null;
};
return fromName(release?.name) ?? fromTag(release?.tag_name) ?? null;
};
const enhanceHeader = () => {
const chrome = document.querySelector('[data-chrome-headroom]');
if (chrome) {
const navBar = chrome.querySelector('.nav');
const glassMap = chrome.querySelector('[data-nav-glass-map]');
// Liquid Glass displacement map — ported 1:1 from Inspira UI's
// LiquidGlass.vue `displacementImage` computed (radius 16, border
// 0.07, lightness 50, alpha 0.93, blur 11, blend "difference").
// Built at the live bar's pixel size so the edge refraction
// tracks the bar as it condenses; mirrors the component's
// ResizeObserver-driven data URI.
const buildGlassMap = (w, h) => {
// Pill radius — half the bar height — so the refraction follows
// the condensed capsule's fully rounded ends.
const radius = Math.round(Math.min(w, h) / 2);
const borderRatio = 0.07;
const lightness = 50;
const alpha = 0.93;
const blur = 11;
const blend = 'difference';
const inset = Math.min(w, h) * (borderRatio * 0.5);
// Opaque black (#000), NOT transparent (#0000): a transparent->red
// stop interpolates with straight alpha, so over black the R
// channel comes out quadratic (255*t^2) and its 0.5 neutral point
// lands at ~29% instead of 50%, shifting the refraction to one
// side. Opaque stops give a linear ramp centered at 50%. (Mirror
// of the same map builder in _components/header-enhancer.astro.)
const svg =
'<svg viewBox="0 0 ' + w + ' ' + h + '" xmlns="http://www.w3.org/2000/svg">' +
'<defs>' +
'<linearGradient id="red" x1="100%" y1="0%" x2="0%" y2="0%"><stop offset="0%" stop-color="#000"/><stop offset="100%" stop-color="red"/></linearGradient>' +
'<linearGradient id="blue" x1="0%" y1="0%" x2="0%" y2="100%"><stop offset="0%" stop-color="#000"/><stop offset="100%" stop-color="blue"/></linearGradient>' +
'</defs>' +
'<rect x="0" y="0" width="' + w + '" height="' + h + '" fill="black"/>' +
'<rect x="0" y="0" width="' + w + '" height="' + h + '" rx="' + radius + '" fill="url(#red)"/>' +
'<rect x="0" y="0" width="' + w + '" height="' + h + '" rx="' + radius + '" fill="url(#blue)" style="mix-blend-mode:' + blend + '"/>' +
'<rect x="' + inset + '" y="' + inset + '" width="' + (w - inset * 2) + '" height="' + (h - inset * 2) + '" rx="' + radius + '" fill="hsl(0 0% ' + lightness + '% / ' + alpha + ')" style="filter:blur(' + blur + 'px)"/>' +
'</svg>';
return 'data:image/svg+xml,' + encodeURIComponent(svg);
};
const syncGlassMap = () => {
if (!navBar || !glassMap) return;
const rect = navBar.getBoundingClientRect();
const w = Math.max(1, Math.round(rect.width));
const h = Math.max(1, Math.round(rect.height));
const uri = buildGlassMap(w, h);
glassMap.setAttribute('href', uri);
glassMap.setAttributeNS('http://www.w3.org/1999/xlink', 'href', uri);
};
// Debounced map rebuild — the capsule's width/height animate on
// condense, so rebuilding the displacement SVG every frame would
// re-rasterize the filter each frame and stutter. Rebuild once the
// size settles; the prior map covers the brief morph.
let mapTimer = 0;
const scheduleGlassMap = () => {
clearTimeout(mapTimer);
mapTimer = setTimeout(syncGlassMap, 140);
};
// Condense-on-scroll with hysteresis: condense past 64px, release
// below 24px. The dead-band stops a scroll that lingers near a
// single threshold from flipping the state — and the bar's
// geometry — back and forth (the "jitter"). rAF collapses each
// scroll burst to one read + at most one class change per frame.
const condenseOn = 64;
const condenseOff = 24;
let condensed = false;
let ticking = false;
const onScroll = () => {
ticking = false;
const y = window.scrollY;
if (!condensed && y > condenseOn) {
condensed = true;
chrome.classList.add('is-condensed');
} else if (condensed && y < condenseOff) {
condensed = false;
chrome.classList.remove('is-condensed');
}
};
window.addEventListener(
'scroll',
() => {
if (ticking) return;
ticking = true;
requestAnimationFrame(onScroll);
},
{ passive: true },
);
condensed = window.scrollY > condenseOn;
chrome.classList.toggle('is-condensed', condensed);
syncGlassMap();
if (navBar) {
if (window.ResizeObserver) {
new ResizeObserver(scheduleGlassMap).observe(navBar);
}
window.addEventListener('resize', scheduleGlassMap, { passive: true });
}
}
const starSlots = document.querySelectorAll('[data-github-stars]');
if (starSlots.length) {
fetch('https://api.github.com/repos/nexu-io/open-design', {
headers: { Accept: 'application/vnd.github+json' },
})
.then((r) => (r.ok ? r.json() : Promise.reject(new Error('http error'))))
.then((data) => {
if (typeof data?.stargazers_count === 'number') {
const label = formatStars(data.stargazers_count);
for (const slot of starSlots) slot.textContent = label;
}
})
.catch(() => {});
}
// Live contributor count for the testimonial headline ("N 贡献者").
// The total is the last page number when paginating one-per-page; if
// there's no Link header the list fits on one page, so its length is
// the total. Static "100+" fallback stays if the request fails / 403s.
const contribSlots = document.querySelectorAll('[data-github-contributors]');
if (contribSlots.length) {
fetch('https://api.github.com/repos/nexu-io/open-design/contributors?per_page=1', {
headers: { Accept: 'application/vnd.github+json' },
})
.then((r) => {
if (!r.ok) throw new Error('http error');
const link = r.headers.get('link') || '';
const last = link.match(/[?&]page=(\d+)>;\s*rel="last"/);
if (last) return parseInt(last[1], 10);
return r.json().then((arr) => (Array.isArray(arr) ? arr.length : null));
})
.then((n) => {
if (typeof n === 'number' && n > 0) {
for (const slot of contribSlots) slot.textContent = String(n);
// Feed the same live total into the "贡献者" stat card. Updating
// `data-countup-to` retargets the roll-up if it hasn't run yet;
// setting the text keeps the fallback correct (and fixes the
// value if the roll already finished before this resolved).
const card = document.querySelector('[data-github-contributors-countup]');
if (card) {
card.dataset.countupTo = String(n);
card.textContent = String(n) + (card.dataset.countupSuffix || '');
}
}
})
.catch(() => {});
}
// Latest stable release powers every "v0.x.y" badge on the page
// (topbar pulse, hero CTA-foot, footer download). Hits one
// unauthenticated API call per page view; the static fallback in
// each slot keeps the layout sane if the request fails or 403s.
const versionSlots = document.querySelectorAll('[data-github-version]');
if (versionSlots.length === 0) return;
fetch('https://api.github.com/repos/nexu-io/open-design/releases/latest', {
headers: { Accept: 'application/vnd.github+json' },
})
.then((r) => (r.ok ? r.json() : Promise.reject(new Error('http error'))))
.then((data) => {
const label = formatVersion(data);
if (!label) return;
for (const slot of versionSlots) slot.textContent = label;
})
.catch(() => {});
};
const enhanceWire = () => {
const track = document.querySelector('[data-wire-contributors-track]');
const count = document.querySelector('[data-wire-contributors-count]');
if (!track) return;
const roleOverrides = {
tw93: 'kami',
op7418: 'guizang',
alchaincyf: 'huashu',
OpenCoworkAI: 'codesign',
'nexu-io': 'studio',
lewislulu: 'html-ppt',
};
const roleFor = (login, contributions) =>
roleOverrides[login] ?? `${contributions} ${contributions === 1 ? 'commit' : 'commits'}`;
const isContributor = (value) =>
value &&
typeof value.login === 'string' &&
typeof value.html_url === 'string' &&
typeof value.type === 'string' &&
typeof value.contributions === 'number';
const renderContributor = (contributor, index) => {
const link = document.createElement('a');
link.className = 'wire-item is-link';
link.href = contributor.href;
link.target = '_blank';
link.rel = 'noreferrer noopener';
link.setAttribute('aria-label', `Open ${contributor.handle} on GitHub`);
link.dataset.liveWireItem = String(index);
const dot = document.createElement('span');
dot.className = 'wire-dot';
dot.textContent = '·';
const handle = document.createElement('span');
handle.className = 'wire-handle';
handle.textContent = `@${contributor.handle}`;
const role = document.createElement('span');
role.className = 'wire-role';
role.textContent = contributor.role;
link.append(dot, handle, role);
return link;
};
fetch('https://api.github.com/repos/nexu-io/open-design/contributors?per_page=12', {
headers: { Accept: 'application/vnd.github+json' },
})
.then((r) => (r.ok ? r.json() : Promise.reject(new Error('http error'))))
.then((data) => {
if (!Array.isArray(data)) return;
const live = data
.filter(isContributor)
.filter((c) => c.type !== 'Bot' && !c.login.endsWith('[bot]'))
.slice(0, 12)
.map((c) => ({
handle: c.login,
role: roleFor(c.login, c.contributions),
href: c.html_url,
}));
if (live.length === 0) return;
live.push({
handle: 'you',
role: 'be next',
href: 'https://github.com/nexu-io/open-design/graphs/contributors',
});
if (count) count.textContent = String(Math.max(0, live.length - 1));
track.replaceChildren(
...[...live, ...live].map((contributor, index) => renderContributor(contributor, index)),
);
})
.catch(() => {});
};
// ABOUT statement — "Text Scroll Reveal" (Magic UI / Inspira port).
// The copy is a sticky, vertically-centered paragraph inside a tall
// track (`[data-about-reveal]`); as the reader scrolls through, each
// token brightens in turn. Progress is the track top's travel past
// the viewport top (`-rect.top / innerHeight`), and token i lights
// over the range [i/n, (i+1)/n] — exactly the component's mapping.
const enhanceStatementReveal = () => {
const host = document.querySelector('[data-about-reveal]');
if (!host) return;
const words = host.querySelectorAll('[data-reveal-word]');
if (!words.length) return;
// Reduced motion: leave the copy at full ink (no scroll dependence).
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
host.classList.add('is-reveal-active');
const n = words.length;
let ticking = false;
const update = () => {
ticking = false;
const rect = host.getBoundingClientRect();
// Non-pinned mapping: reveal as the block travels up through the
// viewport. progress 0 when its top sits at 82% of the viewport
// (just risen into view), 1 by the time it reaches 22% (near the
// top) — so the copy lights word by word while it's on screen,
// without a tall pinned track.
const vh = window.innerHeight;
const start = vh * 0.82;
const end = vh * 0.22;
const progress = (start - rect.top) / (start - end);
for (let i = 0; i < n; i++) {
const start = i / n;
const end = (i + 1) / n;
let o;
if (progress <= start) o = 0;
else if (progress >= end) o = 1;
else o = (progress - start) / (end - start);
// Base faint 0.18 → full 1 (the dim-ghost → lit look).
words[i].style.opacity = String(0.18 + 0.82 * o);
}
};
const onScroll = () => {
if (ticking) return;
ticking = true;
requestAnimationFrame(update);
};
window.addEventListener('scroll', onScroll, { passive: true });
window.addEventListener('resize', onScroll, { passive: true });
update();
};
// Labs filter Dock — macOS-style proximity magnification (React Bits
// "Dock", vanilla port). Each item scales by its distance to the
// cursor using a triangular falloff over `dist` px; a short CSS
// transition stands in for the spring. Centers come from offset
// geometry (unaffected by the scale transform), so there's no
// feedback wobble. rAF-throttled; resets on leave; no-ops under
// reduced-motion.
// Lab clips ship as VP9 WebM (sharp at a fraction of the H.264 size) with
// the original .mp4 kept as a fallback. Prefer WebM where the browser can
// decode it (Chrome/Edge/Firefox/Safari 16+); older Safari keeps the mp4.
// `data-preview-video` carries the .mp4 path; this swaps the extension.
const labPrefersWebm = (() => {
try {
const v = document.createElement('video');
return !!(v.canPlayType && v.canPlayType('video/webm; codecs="vp9"'));
} catch (e) {
return false;
}
})();
const labClipSrc = (src) =>
labPrefersWebm && /\.mp4$/i.test(src || '') ? src.replace(/\.mp4$/i, '.webm') : src;
const enhanceLabDock = () => {
const dock = document.querySelector('[data-lab-dock]');
if (!dock) return;
// Prefetch the lab clips (Video / HyperFrames tiles) so switching to
// them is instant rather than waiting 1-2s for the first byte — but
// only once the lab section is about to scroll into view, not on page
// load. Most visitors who never reach the lab never pay the ~1.7MB.
// An IntersectionObserver with a one-viewport bottom margin fires the
// fetch just before the dock enters, then disconnects (one-shot).
// Falls back to an idle prefetch where IntersectionObserver is absent.
(function prefetchLabVideos() {
const srcs = Array.from(dock.querySelectorAll('[data-preview-video]'))
.map((el) => el.getAttribute('data-preview-video'))
.filter(Boolean)
.map(labClipSrc);
if (srcs.length === 0) return;
let done = false;
const run = () => {
if (done) return;
done = true;
srcs.forEach((src) => { try { fetch(src).catch(() => {}); } catch (e) {} });
};
if ('IntersectionObserver' in window) {
const io = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
io.disconnect();
run();
}
}, { rootMargin: '0px 0px 100% 0px' });
io.observe(dock);
} else if ('requestIdleCallback' in window) {
requestIdleCallback(run, { timeout: 4000 });
} else {
setTimeout(run, 2500);
}
})();
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
const items = Array.from(dock.querySelectorAll('[data-dock-item]'));
if (items.length === 0) return;
const MAX = 1.08; // peak scale (subtle pop, never towers over neighbours)
const DIST = 104; // px of cursor proximity that still magnifies
let ticking = false;
const apply = (cursorX) => {
const dockLeft = dock.getBoundingClientRect().left;
const x = cursorX - dockLeft;
for (const it of items) {
const center = it.offsetLeft + it.offsetWidth / 2;
const t = Math.max(0, 1 - Math.abs(x - center) / DIST);
// Keep the selected tile's CSS lift (translateY(-20px)) while we
// drive the magnify scale via inline transform.
const lift = it.classList.contains('active') ? 'translateY(-20px) ' : '';
it.style.transform = `${lift}scale(${(1 + (MAX - 1) * t).toFixed(3)})`;
}
};
dock.addEventListener(
'mousemove',
(event) => {
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
apply(event.clientX);
ticking = false;
});
},
{ passive: true },
);
dock.addEventListener('mouseleave', () => {
for (const it of items) it.style.transform = '';
});
};
// Labs Dock — the tabs switch the command-window preview (image + title
// overlay) in place, no navigation. The active mode also auto-advances
// left→right as a self-running showcase: it pauses on hover, only runs
// while the dock is on screen, and the auto-advance is disabled under
// reduced-motion (the click-to-switch behaviour stays active).
const enhanceLabAutoCycle = () => {
const dock = document.querySelector('[data-lab-dock]');
if (!dock) return;
const autoPlay = !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const items = Array.from(dock.querySelectorAll('[data-dock-item]'));
if (items.length < 2) return;
let previewImg = document.querySelector('[data-lab-preview] img');
// The Labs preview is now a CSS background on `.lab-stage` (no inner
// <img>), so this legacy <img> carousel no longer applies — switching
// is handled by `enhanceLabSwitch`. Bail before it touches a null img.
if (!previewImg) return;
const viewport = previewImg ? previewImg.parentElement : null;
const previewTitle = document.querySelector('[data-lab-preview-title]');
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// Preload every preview so switches are instant, no load flash.
for (const it of items) {
const src = it.getAttribute('data-preview-src');
if (src) {
const pre = new Image();
pre.src = src;
}
}
let index = items.findIndex((it) => it.classList.contains('active'));
if (index < 0) index = 0;
// Mark the active tile + sync the floating title for index `i`.
const setMeta = (i) => {
items.forEach((it, k) => it.classList.toggle('active', k === i));
const title = items[i].getAttribute('data-preview-title');
if (previewTitle && title) previewTitle.textContent = title;
};
// Swap the preview src in place — used for the initial paint and as
// the reduced-motion / same-index fallback.
const swapInPlace = (i) => {
setMeta(i);
const src = items[i].getAttribute('data-preview-src');
if (previewImg && src) {
previewImg.setAttribute('src', src);
// Keep the precise-lazyload observer from reverting our swap.
previewImg.setAttribute('data-precise-src', src);
}
};
const SLIDE_EASE = 'transform 560ms cubic-bezier(0.23, 1, 0.32, 1)';
// One PERSISTENT sliding track holds the images side by side; we only
// ever translate this single element and add/remove child images. It is
// never torn down or re-parented, which is what avoids the end-of-slide
// flash: previously `track.replaceWith(...)` destroyed a `will-change`
// compositor layer, and for one frame the compositor showed the stale
// texture (the outgoing image parked in the left gap) before repaint.
let track = null;
const ensureTrack = () => {
if (track) return;
track = document.createElement('div');
track.style.position = 'absolute';
track.style.inset = '0';
track.style.display = 'flex';
track.style.width = '100%';
track.style.willChange = 'transform';
track.style.transform = 'translateX(0)';
previewImg.style.flex = '0 0 100%';
previewImg.style.width = '100%';
viewport.appendChild(track);
track.appendChild(previewImg); // current image becomes the lone child
};
// The currently-running slide's finaliser, so a new slide (rapid click)
// can settle the previous one instantly before starting.
let activeCleanup = null;
// Slide to preview `i`: forward (dir +1) brings the incoming in from the
// right, backward (-1) from the left. The two images share the one track
// and move as a single layer, so their shared edge stays pixel-perfect
// (no seam / no 底图 bleed-through).
const slideTo = (i, dir) => {
const src = items[i].getAttribute('data-preview-src');
if (!previewImg || !viewport || reduceMotion || dir === 0 || !src) {
swapInPlace(i);
return;
}
// Settle any in-flight slide so we start from a clean resting state.
if (activeCleanup) activeCleanup();
setMeta(i);
ensureTrack();
const incoming = previewImg.cloneNode(false);
incoming.setAttribute('src', src);
// Src is already set, so the precise-lazyload observer has nothing to
// do — drop the attr so its MutationObserver ignores the clone.
incoming.removeAttribute('data-precise-src');