diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db47445..3c0e1ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,8 @@ jobs: node-version: 24 cache: npm - run: npm ci + - name: Compile the pinned Ionic component reference + run: npm run docs:sync:ionic - name: Refresh and verify public sponsor data run: | npm run sponsors:generate diff --git a/.github/workflows/deploy-cloudflare.yml b/.github/workflows/deploy-cloudflare.yml index 1e92599..1ad08d9 100644 --- a/.github/workflows/deploy-cloudflare.yml +++ b/.github/workflows/deploy-cloudflare.yml @@ -29,6 +29,8 @@ jobs: node-version: 24 cache: npm - run: npm ci + - name: Compile the pinned Ionic component reference + run: npm run docs:sync:ionic - name: Refresh all public sponsors before building run: npm run sponsors:generate env: diff --git a/.gitignore b/.gitignore index 5f7a221..73c45dd 100644 --- a/.gitignore +++ b/.gitignore @@ -50,3 +50,7 @@ Thumbs.db /projects/docs/public/assets/theme-preview/*.js /projects/docs/public/assets/theme-preview/*.css /projects/docs/public/assets/theme-preview/markup-*.html + +# Compiled by docs:sync:ionic before testing and building the portal. +/projects/docs/public/assets/ionic-components/ +/projects/docs/src/app/generated/ionic-components/ diff --git a/README.md b/README.md index 81fa7ae..4d6d4d8 100644 --- a/README.md +++ b/README.md @@ -61,3 +61,5 @@ checks that the committed snapshot is current. The generator excludes private sponsorships and follows every pagination cursor. If fetching fails, deployment stops rather than publishing a stale list. Local builds use the committed snapshot; to refresh it, run `GITHUB_TOKEN= npm run sponsors:generate` with a GitHub token provided through the environment. + +On a fresh checkout, run `npm run docs:sync:ionic` after installing dependencies to generate the [Ionic component reference](scripts/ionic-preview/README.md). diff --git a/package.json b/package.json index 4e97718..9cbd382 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "packageManager": "npm@11.7.0", "scripts": { "ng": "ng", + "docs:sync:ionic": "node scripts/preview-ionic-components.mjs", "docs:generate": "npm run docs:generate:content && node scripts/build-theme-preview.mjs", "docs:generate:content": "tsx scripts/generate-docs.ts", "seo:audit": "tsx scripts/seo-audit.ts", diff --git a/projects/docs/src/app/app.css b/projects/docs/src/app/app.css index f028f73..a7ee993 100644 --- a/projects/docs/src/app/app.css +++ b/projects/docs/src/app/app.css @@ -199,3 +199,27 @@ color: #f8fafc; font-size: 1rem; } + +.component-reference { + padding-bottom: 0; +} +.component-nav-entry { + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; + min-height: 44px; + padding: 10px 12px; + border-radius: 8px; + border: 0; + background: transparent; + color: #475569; + font: inherit; + font-size: 13px; + cursor: pointer; +} +.component-nav-entry:hover, +.component-nav-entry:focus-visible { + color: #1767d2; + background: #eff6ff; +} diff --git a/projects/docs/src/app/app.html b/projects/docs/src/app/app.html index 91c2c6f..2f5b54a 100644 --- a/projects/docs/src/app/app.html +++ b/projects/docs/src/app/app.html @@ -150,6 +150,30 @@

{{ guideCopy.otherGuides }}

} +
+

+ Component reference +

+ +

{{ guideCopy.reference }}

{{ guideCopy.reference }} [attr.inert]="showingLibraries() ? '' : null" [attr.aria-hidden]="showingLibraries() ? 'true' : null" > - @if (navigationProject(); as project) { + @if (componentPanel()) { + + } @else if (navigationProject(); as project) { + import('./docs/ionic-components-page').then((m) => m.IonicComponentsPage); const portalProjects = projectCatalog.filter((project) => !project.hostedUrl); const projectRoutes: Routes = portalProjects.flatMap((project) => [ @@ -62,6 +66,20 @@ export const routes: Routes = [ data: { chapter: chapter.id }, loadComponent: () => import('./docs/guide-page').then((module) => module.GuidePageComponent), })), + { path: 'components', loadComponent: componentPage }, + ...ionicComponents.map((item) => ({ + path: 'components/' + item.slug, + data: { slug: item.slug }, + resolve: { + blocks: () => + inject(LOCALE_ID).split('-')[0] === 'ja' + ? import('./generated/ionic-components/ja/catalog').then(({ catalog }) => + catalog.find((entry) => entry.slug === item.slug)!.load(), + ) + : item.load(), + }, + loadComponent: componentPage, + })), ...projectLegacyRoutes, ...projectRoutes, { path: 'not-found', component: NotFoundComponent }, diff --git a/projects/docs/src/app/app.spec.ts b/projects/docs/src/app/app.spec.ts index 4713503..8cb4363 100644 --- a/projects/docs/src/app/app.spec.ts +++ b/projects/docs/src/app/app.spec.ts @@ -130,7 +130,10 @@ describe('App', () => { ); } expect(compiled.querySelector('.guide-navigation a[href="/standard-setup"]')).not.toBeNull(); - expect(compiled.querySelector('.reference-navigation h2')?.textContent).toContain( + expect(compiled.querySelector('#component-reference-title')?.textContent).toContain( + 'Component reference', + ); + expect(compiled.querySelector('#package-reference-title')?.textContent).toContain( 'Package reference', ); expect(compiled.querySelector('details.reference-navigation')).toBeNull(); @@ -519,7 +522,7 @@ describe('App', () => { fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('.docs-rail')).toBeNull(); - const reference = compiled.querySelector('.reference-navigation')!; + const reference = compiled.querySelector('section[aria-labelledby="package-reference-title"]')!; expect(reference.querySelectorAll('app-library-picker a')).toHaveLength( projectsForLocale('en').filter((project) => !project.hostedUrl).length, ); diff --git a/projects/docs/src/app/app.ts b/projects/docs/src/app/app.ts index 151d146..ea3f6ff 100644 --- a/projects/docs/src/app/app.ts +++ b/projects/docs/src/app/app.ts @@ -33,6 +33,7 @@ import { } from '@angular/router'; import { ProjectSummary, projectGroupsForLocale, projectsForLocale } from './docs/docs-data'; import { LibraryPicker } from './docs/library-picker'; +import { IonicComponentsNavigation } from './docs/ionic-components-navigation'; import { ProjectNavigation } from './docs/project-navigation'; import { canonicalHomePath, localizedPublicPath } from './locale-path'; import { FooterSponsors } from './footer-sponsors/footer-sponsors'; @@ -61,6 +62,7 @@ export const INITIAL_DOCS_URL = makeStateKey('rdlabo-docs-initial-url'); RouterLink, LibraryPicker, ProjectNavigation, + IonicComponentsNavigation, LanguageMenu, FooterSponsors, ], @@ -137,8 +139,32 @@ export class App { protected readonly isSupport = computed(() => this.currentUrl().split(/[?#]/)[0] === '/support'); protected readonly activeProject = computed(() => this.#projectForUrl(this.currentUrl())); protected readonly navigationProject = computed(() => this.#projectForUrl(this.navigationUrl())); + protected readonly browsingComponents = signal(false); + protected readonly componentRoute = computed(() => + /^\/components(?:[/?#]|$)/.test(this.navigationUrl()), + ); + protected readonly componentPanel = computed( + () => this.browsingComponents() || this.componentRoute(), + ); + protected openComponents(): void { + this.#menuRevision++; + this.libraryPickerOpen.set(false); + this.browsingComponents.set(true); + this.#focusProjectNavigation(); + } + protected leaveComponents(): void { + this.browsingComponents.set(false); + this.openLibraryPicker(); + afterNextRender( + () => + this.#focusNavigationLink( + this.docsSidebar?.nativeElement.querySelector('#open-components'), + ), + { injector: this.#injector }, + ); + } protected readonly showingLibraries = computed( - () => !this.navigationProject() || this.libraryPickerOpen(), + () => (!this.navigationProject() && !this.componentPanel()) || this.libraryPickerOpen(), ); constructor() { @@ -249,6 +275,7 @@ export class App { } if (!(event instanceof NavigationEnd) || event.id !== this.#navigationId) return; const pending = this.pendingNavigation(); + this.browsingComponents.set(false); this.currentUrl.set(event.urlAfterRedirects); this.pendingNavigation.set(null); this.navigationError.set(null); @@ -326,6 +353,7 @@ export class App { } this.#menuRevision++; this.menuOpen.set(false); + this.browsingComponents.set(false); this.libraryPickerOpen.set(false); if (returnFocus) queueMicrotask(() => this.menuButton?.nativeElement.focus()); } @@ -445,7 +473,8 @@ export class App { this.#document.querySelector('dialog[open], app-language-menu details[open]') ) return; - if (this.navigationProject() && this.libraryPickerOpen()) this.closeLibraryPicker(); + if ((this.navigationProject() || this.componentRoute()) && this.libraryPickerOpen()) + this.closeLibraryPicker(); else if (this.mobileLayout()) this.closeMenu(); } diff --git a/projects/docs/src/app/docs/ionic-article-tabs.ts b/projects/docs/src/app/docs/ionic-article-tabs.ts new file mode 100644 index 0000000..6905463 --- /dev/null +++ b/projects/docs/src/app/docs/ionic-article-tabs.ts @@ -0,0 +1,30 @@ +import { Component, input, linkedSignal } from '@angular/core'; + +export interface ArticleTabs { + kind: 'tabs'; + panels: { label: string; html: string }[]; +} + +@Component({ + selector: 'app-ionic-article-tabs', + template: ` +
+ @for (panel of group().panels; track panel.label) { + + } +
+
+ `, + styles: ` + :host {display:block;overflow:hidden;margin:1rem 0 2rem;border-radius:.75rem;background:#f5f7fb} + .choices {display:flex;flex-wrap:wrap;padding:.375rem;gap:.25rem;background:#e9edf4} + button {border:0;border-radius:.5rem;background:transparent;color:#46556b;font:600 .875rem/1.5 system-ui;padding:.45rem .9rem;cursor:pointer} + button[aria-pressed=true] {background:white;color:#175bb3} + :host ::ng-deep .code pre {background:transparent;color:#203047;margin:0;padding:clamp(1rem,3vw,2rem);overflow:auto;border:0} + :host ::ng-deep .code pre code {background:transparent;color:inherit;font:400 .875rem/1.65 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre} + `, +}) +export class IonicArticleTabs { + readonly group = input.required(); + readonly active = linkedSignal(() => this.group().panels[0]); +} diff --git a/projects/docs/src/app/docs/ionic-component-demo.ts b/projects/docs/src/app/docs/ionic-component-demo.ts new file mode 100644 index 0000000..552a96e --- /dev/null +++ b/projects/docs/src/app/docs/ionic-component-demo.ts @@ -0,0 +1,87 @@ +import { Component, computed, ElementRef, inject, input, linkedSignal, signal, viewChild } from '@angular/core'; +import { DomSanitizer } from '@angular/platform-browser'; + +export interface IonicDemo { + kind: 'demo'; + src: string; + mode: string; + console: boolean; + examples: { name: string; files: { name: string; html: string }[] }[]; +} +@Component({ + selector: 'app-ionic-component-demo', + host: { '(window:message)': 'receive($event)' }, + template: ` +
+
+
+ @for (ex of demo().examples; track ex.name) { + + } +
+
+ @for (t of themes; track t.key) { + + } +
+
+ + @if (demo().console) { {{ log() }} } +
+
+ @if (example().files.length > 1) { +
+ @for (f of example().files; track f.name) { + + } +
+ } +
+
+ `, + styles: ` + :host { display:block;margin:1.5rem 0 2.5rem;color:#172033 } + .example,.code{overflow:hidden;border:1px solid #dbe3ed;border-radius:.75rem} + .code{margin-top:.75rem;background:#f6f8fb} + .controls{display:flex;gap:.15rem;flex-wrap:wrap;padding:.4rem .55rem;background:white;border-bottom:1px solid #e2e8f0} + button{background:transparent;border:0;border-radius:2rem;padding:.5rem .8rem;color:#475569;font:600 .875rem/1.5 system-ui;cursor:pointer} + button[aria-pressed=true]{background:#e6efff;color:#1459b8}button:disabled{opacity:.45} + iframe{width:100%;height:clamp(18rem,49vh,27rem);display:block;border:0} + .toolbar{display:flex;flex-wrap:wrap;align-items:center;border-bottom:1px solid #dbe3ed} + .toolbar .controls{border:0} + .toolbar .controls + .controls{border-inline-start:1px solid #dbe3ed} + .code{background:#f5f7fb;border:0} + .files{background:#e9edf4;display:flex;overflow-x:auto} + .files button{display:flex;align-items:center;gap:.55rem;flex:none;white-space:nowrap;border-radius:0;color:#46556b;padding:.75rem 1rem;font-size:.8rem;font-weight:500} + .files button[aria-pressed=true]{background:#f5f7fb;color:#172943;box-shadow:inset 0 2px #2866bf} + .short-path{display:none} + @media(max-width:600px){.files .full-path,.files .ext{display:none}.files .short-path{display:inline}.files button{padding:.75rem .65rem}} + .ext{font:700 .7rem/1 monospace;color:#225bb0;text-transform:uppercase} + .code pre{background:transparent;color:#203047;margin:0;padding:clamp(1rem,3vw,2rem);overflow:auto;border:0;border-radius:0} + .code pre code{font:400 .875rem/1.65 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:transparent;color:inherit;padding:0;white-space:pre} + output{display:block;padding:.65rem 1rem;font:.8rem/1.5 monospace;color:#475569} + output:empty{display:none} + @media(max-width:600px){.toolbar .controls{width:100%}.toolbar .controls + .controls{border-inline-start:0;border-top:1px solid #edf0f4}} + + `, +}) +export class IonicComponentDemo { + readonly demo = input.required(); + readonly themes = [{key:'ios27',mode:'ios',label:'iOS 27'},{key:'ios26',mode:'ios',label:'iOS 26'},{key:'md',mode:'md',label:'MD3'}]; + readonly names: Record = {angular:'Angular',javascript:'JavaScript',react:'React',vue:'Vue'}; + readonly theme = linkedSignal(() => this.demo().mode === 'md' ? 'md' : 'ios27'); + readonly example = linkedSignal(() => this.demo().examples.find(e => e.name === 'angular') ?? this.demo().examples[0]); + readonly file = linkedSignal(() => this.example().files[0]); + readonly log = signal(''); + readonly frame = viewChild>('frame'); + readonly #sanitizer = inject(DomSanitizer); + readonly url = computed(() => this.#sanitizer.bypassSecurityTrustResourceUrl( + '/assets/ionic-components/'+this.demo().src+'?ionic:mode='+(this.theme()==='md'?'md':'ios')+'&theme='+this.theme())); + choose(theme: string) { this.log.set(''); this.theme.set(theme); } + receive(event: MessageEvent) { + if (this.demo().console && event.source === this.frame()?.nativeElement.contentWindow && event.origin === location.origin && typeof event.data?.ionicDemoLog === 'string') this.log.set(event.data.ionicDemoLog); + } +} diff --git a/projects/docs/src/app/docs/ionic-components-navigation.ts b/projects/docs/src/app/docs/ionic-components-navigation.ts new file mode 100644 index 0000000..d1d9d62 --- /dev/null +++ b/projects/docs/src/app/docs/ionic-components-navigation.ts @@ -0,0 +1,38 @@ +import { afterNextRender, Component, inject, Injector, output } from '@angular/core'; +import { RouterLink, RouterLinkActive } from '@angular/router'; +import { catalog } from '../generated/ionic-components/catalog'; + +@Component({ + selector: 'app-ionic-components-navigation', + imports: [RouterLink, RouterLinkActive], + styleUrl: './project-navigation.css', + template: ` +
+ +

Components

+
+ + `, +}) +export class IonicComponentsNavigation { + readonly catalog = catalog; + readonly back = output(); + readonly #injector = inject(Injector); + reveal(active: boolean, link: HTMLAnchorElement) { + if (active) afterNextRender(() => { + const list = link.parentElement; + if (!list) return; + const row = link.getBoundingClientRect(); + const bounds = list.getBoundingClientRect(); + if (row.bottom > bounds.bottom) list.scrollTop += row.bottom - bounds.bottom + 12; + else if (row.top < bounds.top) list.scrollTop -= bounds.top - row.top + 12; + }, {injector:this.#injector}); + } +} diff --git a/projects/docs/src/app/docs/ionic-components-page.css b/projects/docs/src/app/docs/ionic-components-page.css new file mode 100644 index 0000000..2f9ce69 --- /dev/null +++ b/projects/docs/src/app/docs/ionic-components-page.css @@ -0,0 +1,24 @@ +.directory{max-width:1100px;margin:auto;padding:clamp(24px,4vw,48px)} +.directory ul{list-style:none;padding:0;margin:2rem 0;display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr));gap:.25rem 1.5rem} +.directory li a{display:block;padding:.5rem 0;color:#175bb3} +.setup-header .guide-kind{display:inline-block;margin-bottom:10px} +article{min-width:0} +article :is(h2,h3,h4){scroll-margin-top:6rem} +footer{margin-top:3rem;font-size:.875rem;color:#475569} +:host ::ng-deep .docs-page-article table{display:block;max-width:100%;overflow-x:auto} +:host ::ng-deep .docs-page-article details{margin:.5rem 0} +.directory input{display:block;margin-top:1.5rem;width:min(100%,28rem);padding:.7rem 1rem;border:1px solid #cbd5e1;border-radius:.6rem} + +.source-note { + display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; + gap:.5rem 1rem; margin-bottom:1.65rem; padding:.75rem 1rem; + background:#f1f5fb; border-radius:.6rem; color:#516177; + font-size:.8125rem; line-height:1.5; +} +.source-copy {display:grid;gap:.1rem} +.source-title {font-weight:650;color:#293d57} +.source-note a {display:inline-flex;align-items:center;gap:.3rem;color:#175bb3;font-weight:600;text-decoration:none} +.source-note a:hover,.source-note a:focus-visible {text-decoration:underline;text-underline-offset:.18em} + +/* Upstream prose sometimes displays the full URL as its link text. */ +:host ::ng-deep .docs-page-article a { overflow-wrap: anywhere; } diff --git a/projects/docs/src/app/docs/ionic-components-page.ts b/projects/docs/src/app/docs/ionic-components-page.ts new file mode 100644 index 0000000..fae5937 --- /dev/null +++ b/projects/docs/src/app/docs/ionic-components-page.ts @@ -0,0 +1,97 @@ +import { Component, computed, effect, inject, LOCALE_ID, signal } from '@angular/core'; +import { NgTemplateOutlet } from '@angular/common'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { catalog, revision } from '../generated/ionic-components/catalog'; +import { catalog as japaneseCatalog, revision as japaneseRevision } from '../generated/ionic-components/ja/catalog'; +import { localizedPublicPath } from '../locale-path'; +import { IonicComponentDemo, type IonicDemo } from './ionic-component-demo'; +import { SeoService } from './seo.service'; + +import { IonicArticleTabs, type ArticleTabs } from './ionic-article-tabs'; + +type Block = ArticleTabs | IonicDemo | {kind:'html';html:string} | {kind:'heading';id:string;level:number;text:string}; + +@Component({ + imports: [IonicComponentDemo, IonicArticleTabs, RouterLink, NgTemplateOutlet], + styleUrls: ['./guide-article.css','./ionic-components-page.css'], + template: ` + + + + @if (entry(); as item) { +
+
Components

{{ item.title }}

+ +
+ @for (b of blocks(); track $index) { + @switch (b.kind) { + @case ('html') {
} + @case ('heading') { + @switch (b.level) { + @case (2) {

{{ b.text }}

} + @case (3) {

{{ b.text }}

} + @default {

{{ b.text }}

} + } + } + @case ('tabs') {} + @case ('demo') {} + } + } + +
+
+ } @else { +

Components

+ + +
+ } + `, +}) +export class IonicComponentsPage { + readonly #locale = inject(LOCALE_ID); + readonly articleLocale = this.#locale.split('-')[0] === 'ja' ? 'ja' : 'en'; + readonly catalog = this.articleLocale === 'ja' ? japaneseCatalog : catalog; + readonly contentsLabel = $localize`:@@onThisPage:On this page`; + readonly query = signal(''); + readonly filtered = computed(() => this.catalog.filter(item => item.title.toLowerCase().includes(this.query().trim().toLowerCase()))); + readonly source = 'https://github.com/ionic-team/ionic-docs/blob/'+(this.articleLocale === 'ja' ? japaneseRevision : revision)+'/docs/api/'; + readonly #data = toSignal(inject(ActivatedRoute).data); + readonly entry = computed(() => this.catalog.find(e=>e.slug===this.#data()?.['slug'])); + protected readonly locale = this.#locale; + readonly officialUrl = computed(() => 'https://ionicframework.com/docs/' + (this.articleLocale === 'ja' ? 'ja/' : '') + (this.entry() ? 'api/' + this.entry()!.slug : 'components')); + readonly path = computed(() => localizedPublicPath(this.#locale,'/components'+(this.entry()?'/'+this.entry()!.slug:''))); + readonly blocks = computed(() => { + const articlePath = this.path(); + const directoryPath = localizedPublicPath(this.#locale, '/components'); + // A fragment in generated HTML otherwise resolves against the site's . + const localizeLinks = (html: string) => html.replace( + /(]*?\shref=")(#|\/components\/)/gi, + (_, start: string, target: string) => start + (target === '#' ? articlePath + '#' : directoryPath + '/'), + ); + const blocks = (this.#data()?.['blocks'] ?? []) as Block[]; + return blocks.map(block => { + if (block.kind === 'html') return { ...block, html: localizeLinks(block.html) }; + if (block.kind === 'tabs') return { + ...block, + panels: block.panels.map(panel => ({ ...panel, html: localizeLinks(panel.html) })), + }; + return block; + }); + }); + readonly #seo = inject(SeoService); + constructor() { + effect(()=>this.#seo.setPage({title:this.entry()?.title ?? 'Components',description:this.entry()?.description ?? 'Ionic components with iOS and Material Design theme previews.',path:'/components'+(this.entry()?'/'+this.entry()!.slug:'')})); + } +} diff --git a/projects/docs/src/locale/messages.de.xlf b/projects/docs/src/locale/messages.de.xlf index d4b7a89..1b1fc79 100644 --- a/projects/docs/src/locale/messages.de.xlf +++ b/projects/docs/src/locale/messages.de.xlf @@ -2,6 +2,9 @@ + From the official Ionic DocsAus der offiziellen Ionic-Dokumentation + Live demos use WebView Native UI themes.Die Live-Demos verwenden die Themes von WebView Native UI. + View originalOriginal lesen Skip to content Zum Inhalt springen @@ -645,6 +648,11 @@ FilesDateien Choose your setupEinrichtung auswählen The browser demo shows theme styling and Web interactions. Native controls and Android device colors require the native app on a supported device.Die Browser-Demo zeigt das Theme-Design und Web-Interaktionen. Native Steuerelemente und Android-Gerätefarben benötigen die native App auf einem unterstützten Gerät. + Component referenceKomponentenreferenz + Ionic componentsIonic-Komponenten + Filter componentsKomponenten filtern + Source on Ionic DocsQuelle in Ionic Docs + Third-party noticesHinweise zu Drittanbietern diff --git a/projects/docs/src/locale/messages.en.xlf b/projects/docs/src/locale/messages.en.xlf index dba3d0f..c12ec8d 100644 --- a/projects/docs/src/locale/messages.en.xlf +++ b/projects/docs/src/locale/messages.en.xlf @@ -682,5 +682,13 @@ Choose your setup The browser demo shows theme styling and Web interactions. Native controls and Android device colors require the native app on a supported device. + Component reference + Ionic components + From the official Ionic Docs + Live demos use WebView Native UI themes. + View original + Filter components + Source on Ionic Docs + Third-party notices diff --git a/projects/docs/src/locale/messages.fr.xlf b/projects/docs/src/locale/messages.fr.xlf index 880f8d1..151c75b 100644 --- a/projects/docs/src/locale/messages.fr.xlf +++ b/projects/docs/src/locale/messages.fr.xlf @@ -2,6 +2,9 @@ + From the official Ionic DocsSource : documentation officielle Ionic + Live demos use WebView Native UI themes.Les démos utilisent les thèmes de WebView Native UI. + View originalLire l’original Skip to content Aller au contenu @@ -645,6 +648,11 @@ FilesFichiers Choose your setupChoisir votre intégration The browser demo shows theme styling and Web interactions. Native controls and Android device colors require the native app on a supported device.La démo dans le navigateur montre le style du thème et les interactions Web. Les contrôles natifs et les couleurs Android nécessitent l’application native sur un appareil compatible. + Component referenceRéférence des composants + Ionic componentsComposants Ionic + Filter componentsFiltrer les composants + Source on Ionic DocsSource sur Ionic Docs + Third-party noticesMentions des tiers \ No newline at end of file diff --git a/projects/docs/src/locale/messages.ja.xlf b/projects/docs/src/locale/messages.ja.xlf index ba053e6..b68fe95 100644 --- a/projects/docs/src/locale/messages.ja.xlf +++ b/projects/docs/src/locale/messages.ja.xlf @@ -2,6 +2,9 @@ + From the official Ionic DocsIonic 公式ドキュメントより + Live demos use WebView Native UI themes.ライブデモには WebView Native UI のテーマを適用しています。 + View original原文を読む WebView Native UI DocumentationWebView Native UI ドキュメント This page couldn’t be loaded. Reload the documentation to try again.ページを読み込めませんでした。ドキュメントを再読み込みしてください。 Reload documentationドキュメントを再読み込み @@ -88,6 +91,11 @@ Filesファイル Choose your setup導入方法を選ぶ The browser demo shows theme styling and Web interactions. Native controls and Android device colors require the native app on a supported device.ブラウザーデモではテーマの見た目とWeb側の操作を確認できます。ネイティブコントロールとAndroid端末の配色は、対応端末のネイティブアプリで確認してください。 + Component referenceコンポーネントリファレンス + Ionic componentsIonic コンポーネント + Filter componentsコンポーネントを絞り込む + Source on Ionic DocsIonic Docs の原稿 + Third-party noticesサードパーティに関する表記 diff --git a/projects/docs/src/styles.css b/projects/docs/src/styles.css index c80a580..d9e33c1 100644 --- a/projects/docs/src/styles.css +++ b/projects/docs/src/styles.css @@ -353,3 +353,29 @@ pagefind-modal-trigger.docs-search:empty { [appHeadingLinks] :is(h2, h3, h4, h5, h6):hover > .header-anchor-link { color: #1767d2; } + +:is(app-ionic-component-demo, app-ionic-article-tabs) + .code + .token:is(.keyword, .atrule, .decorator) { + color: #a82b64; +} +:is(app-ionic-component-demo, app-ionic-article-tabs) + .code + .token:is(.string, .attr-value, .regex) { + color: #09674c; +} +:is(app-ionic-component-demo, app-ionic-article-tabs) + .code + .token:is(.function, .tag, .class-name) { + color: #155bab; +} +:is(app-ionic-component-demo, app-ionic-article-tabs) + .code + .token:is(.attr-name, .number, .boolean, .selector, .property) { + color: #6945a0; +} +:is(app-ionic-component-demo, app-ionic-article-tabs) + .code + .token:is(.comment, .punctuation, .operator) { + color: #516174; +} diff --git a/scripts/build-output.test.ts b/scripts/build-output.test.ts index b7f9dbb..10aa4a8 100644 --- a/scripts/build-output.test.ts +++ b/scripts/build-output.test.ts @@ -7,6 +7,7 @@ import { gunzipSync } from 'node:zlib'; import { JSDOM } from 'jsdom'; import { DOCS_LOCALES, PUBLISHED_DOCS_LOCALES } from '../shared/docs-locales'; import { projectDefinitions } from './project-manifest'; +import { catalog as ionicComponents } from '../projects/docs/src/app/generated/ionic-components/catalog'; import { PROJECTS_EN } from '../projects/docs/src/app/generated/project-catalog.generated'; import { CURRENT_SPONSORS, @@ -343,6 +344,24 @@ test('prerendered locales include reusable hydration data', async () => { } }); +test('prerenders the official Japanese component article with its shared live demos', async () => { + const html = await readFile('dist/docs/browser/ja/components/action-sheet/index.html', 'utf8'); + const { window } = new JSDOM(html); + try { + const article = window.document.querySelector('article')!; + assert.equal(article.closest('[lang]')?.getAttribute('lang'), 'ja'); + assert.match(article.querySelector('#properties')!.textContent!, /プロパティ/); + assert.match(article.textContent!, /アクションシート/); + assert.equal(article.querySelectorAll('app-ionic-component-demo').length, 6); + assert.equal( + window.document.querySelector('.source-note a')?.getAttribute('href'), + 'https://ionicframework.com/docs/ja/api/action-sheet', + ); + } finally { + window.close(); + } +}); + test('builds bounded search indexes for every published language with the component UI', async () => { const searchDirectory = new URL('../dist/docs/browser/pagefind/', import.meta.url); const files = await readdir(searchDirectory, { recursive: true }); @@ -350,7 +369,7 @@ test('builds bounded search indexes for every published language with the compon assert.ok(files.includes('pagefind-component-ui.css')); const canonicalPages = PROJECTS_EN.filter((project) => !project.hostedUrl).reduce( (count, project) => count + 1 + project.pages.length, - 3 + GUIDE_CHAPTERS.length, // Home, standard setup, support and shared guide chapters. + 4 + GUIDE_CHAPTERS.length + ionicComponents.length, // Home, setup, support, component index and articles. ); for (const { code } of PUBLISHED_DOCS_LOCALES) { assert.ok( diff --git a/scripts/ionic-preview/Playground.tsx b/scripts/ionic-preview/Playground.tsx new file mode 100644 index 0000000..74b4674 --- /dev/null +++ b/scripts/ionic-preview/Playground.tsx @@ -0,0 +1,26 @@ +import React from 'react'; + +// MDX imports are executable components. Render each file during the upstream +// static build so every framework's code survives without a React runtime. +export default function Playground({ code, src, mode, showConsole, title }) { + return ( +
+ {Object.entries(code).map(([framework, example]: [string, any]) => ( +
+ {Object.entries(example.files ?? { '': example }).map( + ([filename, Content]: [string, any]) => ( +
+ +
+ ), + )} +
+ ))} +
+ ); +} diff --git a/scripts/ionic-preview/README.md b/scripts/ionic-preview/README.md new file mode 100644 index 0000000..6b55bae --- /dev/null +++ b/scripts/ionic-preview/README.md @@ -0,0 +1,15 @@ +# Sync Ionic component references + +Run from the docs repository with Node.js 24 and its npm dependencies installed. + +```sh +npm run docs:sync:ionic +``` + +The command downloads the pinned English and Japanese Ionic Docs revisions, builds its MDX with the upstream Docusaurus toolchain and exports the component articles and demos. The package lock selects the local Ionic runtime and themes. Japanese routes use the official translation/jp articles and the pinned ionic-jp API definitions. English, French and German routes show the English articles. Each article footer links to its original revision. Distribution credits and license texts are generated under `projects/docs/public/assets/ionic-components`. + +PR CI and the production deployment workflow run this step after npm ci. On a fresh local checkout, run it once before starting, testing, or building the portal. The generated article modules and demo assets are ignored by Git. + +To review an update locally, run `npm run docs:sync:ionic -- `. Update the default SHA after verifying the result. Review package versions and core.json SHA-256 digests in `upstream-inputs.mjs` if the Ionic API version changes. Check the upstream API package license when updating its version. The current license snapshot is from [ionic-framework at the API package's gitHead](https://github.com/ionic-team/ionic-framework/blob/68a2fea5fa1db1c729ed81a29f10d0b1b4c399c7/LICENSE). + +The generator replaces both generated directories after compilation and export succeed. Run the portal build and inspect a component page after syncing. The synchronization and publication steps are separate. diff --git a/scripts/ionic-preview/config.cjs b/scripts/ionic-preview/config.cjs new file mode 100644 index 0000000..43f2dcf --- /dev/null +++ b/scripts/ionic-preview/config.cjs @@ -0,0 +1,4 @@ +const config = require('./docusaurus.config'); +config.presets[0][1].googleTagManager = false; +config.plugins = config.plugins.filter((plugin) => typeof plugin !== 'function'); +module.exports = config; diff --git a/scripts/ionic-preview/export.mjs b/scripts/ionic-preview/export.mjs new file mode 100644 index 0000000..802d24d --- /dev/null +++ b/scripts/ionic-preview/export.mjs @@ -0,0 +1,206 @@ +import { cp, mkdir, readFile, readdir, writeFile } from 'node:fs/promises'; +import { join, posix } from 'node:path'; +import { load } from 'cheerio'; +import { japaneseDocsRef } from './upstream-inputs.mjs'; + +// Upstream demos import the version's shared CSS and JS from different nesting depths. +export async function normalizeDemoImports(usage) { + for (const file of await readdir(usage, { recursive: true })) { + if (!file.endsWith('/demo.html')) continue; + const path = join(usage, file); + const original = await readFile(path, 'utf8'); + const normalized = original.replace( + /((?:src|href)=["'])(?:\.\.\/)+(common\.(?:css|js))(?=["'])/g, + (_, attr, name) => attr + posix.relative(posix.dirname(file), name), + ); + if (normalized !== original) await writeFile(path, normalized); + } +} + +export async function exportPortalComponents(work, output, ref) { + const assets = 'projects/docs/public/assets/ionic-components'; + await mkdir(assets, { recursive: true }); + await cp(join(work, 'LICENSE'), join(assets, 'LICENSE')); + const demos = await exportArticles(work, output, ref); + const japaneseDemos = await exportArticles(work, join(output, 'ja'), japaneseDocsRef, 'ja'); + for (const file of japaneseDemos) demos.add(file); + const runtime = join(output, 'preview-assets'); + // Ionic loads component bundles and SVG icons by name at runtime. + await cp(join(runtime, 'dist'), join(assets, 'runtime/dist'), { recursive: true }); + for (const theme of ['ios26', 'ios27', 'md']) { + await cp(join(runtime, theme + '.css'), join(assets, 'runtime', theme + '.css')); + } + const styles = new Set(); + for (const file of [...demos, 'usage/v9/common.js', 'usage/v9/common.css']) { + const source = await readFile(join(output, file), 'utf8'); + await mkdir(join(assets, posix.dirname(file)), { recursive: true }); + await writeFile(join(assets, file), source); + for (const match of source.matchAll( + /\/assets\/ionic-components\/runtime\/(css\/[\w/-]+(?:\.[\w-]+)*\.css)/g, + )) { + styles.add(match[1]); + } + } + for (const file of styles) { + const source = await readFile(join(runtime, file), 'utf8'); + await mkdir(join(assets, 'runtime', posix.dirname(file)), { recursive: true }); + await writeFile( + join(assets, 'runtime', file), + source.replace(/\/\*# sourceMappingURL=[^*]+\*\//g, ''), + ); + } + await normalizeDemoImports(join(assets, 'usage/v9')); +} + +export async function exportArticles(work, output, ref, locale = 'en') { + const modules = join( + 'projects/docs/src/app/generated/ionic-components', + locale === 'ja' ? 'ja' : '', + ); + await mkdir(modules, { recursive: true }); + const files = (await readdir(join(work, 'docs/api'))) + .filter((name) => name.endsWith('.mdx')) + .sort(); + const catalog = []; + const demos = new Set(); + for (const file of files) { + const slug = file.slice(0, -4); + if (locale === 'ja') { + // Docusaurus falls back to English when the translated MDX is absent. + // Fail the sync rather than publish an English article marked as Japanese. + await readFile(join(work, 'i18n/ja/docusaurus-plugin-content-docs/current/api', file)); + } + const $ = load(await readFile(join(output, 'api', slug, 'index.html'), 'utf8')); + const article = $('.theme-doc-markdown'); + const title = article.find('h1').first().text(); + if (!title) throw Error('Missing article: ' + slug); + const description = $('meta[name=description]').attr('content') ?? ''; + article.find('header').first().remove(); + article.find('.hash-link,.encapsulation-pill,button,script,style').remove(); + article.find('pre code').each((_, code) => { + const lines = $(code).children('.token-line'); + lines.children('br').remove(); + if (lines.length) + $(code).html( + lines + .map((_, line) => $(line).html() ?? '') + .get() + .join('\n'), + ); + }); + article.find('a[href]').each((_, link) => { + const originalHref = $(link).attr('href'); + const href = originalHref.replace(/^\/docs\/ja\/api\//, '/docs/api/'); + if (href.startsWith('/docs/api/')) + $(link).attr('href', href.replace('/docs/api/', '/components/')); + else if (href.startsWith('/docs/')) $(link).attr('href', 'https://ionicframework.com' + href); + }); + article.find('img[src],source[src],video[src]').each((_, el) => { + const src = $(el).attr('src'); + if (src.startsWith('/docs/')) $(el).attr('src', 'https://ionicframework.com' + src); + }); + // Some translations leave a note open across a new section. Keep the + // note's introduction and expose the following sections to the renderer. + for (const note of article.children('.theme-admonition').toArray()) { + if (!$(note).find('[data-ionic-demo]').length) continue; + const body = $(note).children().last(); + const section = body.children('h2,h3,[data-ionic-demo]').first(); + const following = section.nextAll().addBack().toArray(); + $(note).after(following); + } + const blocks = []; + for (const node of article.contents()) { + const el = $(node); + const src = el.attr('data-ionic-demo'); + if (src) { + if (!/^usage\/v9\/[\w/-]+\/demo\.html$/.test(src)) + throw Error('Unexpected demo path: ' + src); + demos.add(src); + const examples = el + .find('[data-framework]') + .map((_, group) => ({ + name: $(group).attr('data-framework'), + files: $(group) + .children() + .map((_, item) => ({ + name: $(item).attr('data-filename'), + html: $(item).find('pre code').html() ?? '', + })) + .get(), + })) + .get(); + blocks.push({ + kind: 'demo', + src, + examples, + mode: el.attr('data-mode') ?? '', + console: el.attr('data-console') !== undefined, + }); + } else if (el.hasClass('tabs-container')) { + const labels = el.find('> [role=tablist] > [role=tab]'); + const panels = el.find('> div > [role=tabpanel]'); + if (!panels.length || labels.length !== panels.length) + throw Error('Incomplete tabs: ' + slug); + blocks.push({ + kind: 'tabs', + panels: panels + .map((i, panel) => ({ + label: labels + .eq(i) + .text() + .replace(/^Javascript$/, 'JavaScript'), + html: $(panel).html(), + })) + .get(), + }); + } else if (/^h[2-6]$/.test(node.name ?? '')) { + blocks.push({ + kind: 'heading', + level: Number(node.name[1]), + id: el.attr('id'), + text: el.text(), + }); + } else { + const html = $.html(node); + if (!html.trim() || node.type === 'comment') continue; + if (blocks.at(-1)?.kind === 'html') blocks.at(-1).html += html; + else blocks.push({ kind: 'html', html }); + } + } + if (article.find('[data-ionic-demo]').length !== blocks.filter((b) => b.kind === 'demo').length) + throw Error('Nested demo: ' + slug); + // Keep whole examples together while respecting the portal's JS chunk budget. + const parts = []; + let part = []; + let bytes = 0; + for (const block of blocks) { + const size = Buffer.byteLength(JSON.stringify(block)); + if (part.length && bytes + size > 400_000) { + parts.push(part); + part = []; + bytes = 0; + } + part.push(block); + bytes += size; + } + parts.push(part); + const imports = []; + for (const [index, content] of parts.entries()) { + const filename = slug + (index ? '.' + index : '') + '.json'; + await writeFile(join(modules, filename), JSON.stringify(content)); + imports.push(`import('./${filename}').then(m => m.default as unknown[])`); + } + const loadExpression = + imports.length === 1 + ? imports[0] + : `Promise.all([${imports.join(',')}]).then(parts => parts.flat())`; + catalog.push( + ` { ...${JSON.stringify({ slug, title, description })}, load: () => ${loadExpression} },`, + ); + } + await writeFile( + join(modules, 'catalog.ts'), + `export const revision = '${ref}';\nexport const catalog = [\n${catalog.join('\n')}\n];\n`, + ); + return demos; +} diff --git a/scripts/ionic-preview/install-generated.mjs b/scripts/ionic-preview/install-generated.mjs new file mode 100644 index 0000000..2efc61e --- /dev/null +++ b/scripts/ionic-preview/install-generated.mjs @@ -0,0 +1,63 @@ +import { mkdir, mkdtemp, rename, rm } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { exportPortalComponents } from './export.mjs'; +import { installDistributionNotices } from './upstream-inputs.mjs'; + +const destinations = [ + 'projects/docs/public/assets/ionic-components', + 'projects/docs/src/app/generated/ionic-components', +]; + +// Both destinations contain generator-owned files. Stage complete replacements so +// a failed export preserves the previous snapshot and upstream deletions propagate. +export async function installGenerated(work, output, ref) { + const root = process.cwd(); + const cache = resolve('.angular'); + await mkdir(cache, { recursive: true }); + const lock = join(cache, 'ionic-components-sync.lock'); + await mkdir(lock); + let stage; + let preserveBackup = false; + try { + stage = await mkdtemp(join(cache, 'ionic-components-sync-')); + try { + process.chdir(stage); + await exportPortalComponents(work, output, ref); + } finally { + process.chdir(root); + } + await installDistributionNotices(work, join(stage, destinations[0]), ref); + const changes = []; + try { + for (const destination of destinations) { + const target = resolve(destination); + await mkdir(dirname(target), { recursive: true }); + const backup = join(stage, 'previous-' + changes.length); + const change = { target, backup, hadPrevious: false, installed: false }; + changes.push(change); + try { + await rename(target, backup); + change.hadPrevious = true; + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + await rename(join(stage, destination), target); + change.installed = true; + } + } catch (error) { + try { + for (const change of changes.reverse()) { + if (change.installed) await rm(change.target, { recursive: true }); + if (change.hadPrevious) await rename(change.backup, change.target); + } + } catch (rollbackError) { + preserveBackup = true; + throw new AggregateError([error, rollbackError], 'Previous files retained in ' + stage); + } + throw error; + } + } finally { + if (stage && !preserveBackup) await rm(stage, { recursive: true, force: true }); + await rm(lock, { recursive: true }); + } +} diff --git a/scripts/ionic-preview/licenses/ionic-framework.txt b/scripts/ionic-preview/licenses/ionic-framework.txt new file mode 100644 index 0000000..92621d0 --- /dev/null +++ b/scripts/ionic-preview/licenses/ionic-framework.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2015-present Drifty Co. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/ionic-preview/upstream-inputs.mjs b/scripts/ionic-preview/upstream-inputs.mjs new file mode 100644 index 0000000..87b9326 --- /dev/null +++ b/scripts/ionic-preview/upstream-inputs.mjs @@ -0,0 +1,167 @@ +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { cp, mkdir, readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +export const japaneseDocsRef = '48f35c8a956fb55661dcbdbb474f848adb70431b'; +const japaneseApiRef = '0e9f7c7e21496f3ad4582af3b6e53b22658cac1d'; +const japaneseApiDigest = '18a5ba4e5d4f09ccffeffe6693a44490d0fdc1a26d7de5196caf0a8d9e3e2ea1'; + +export async function prepareJapaneseDocs(work) { + const target = join(work, 'i18n/ja/docusaurus-plugin-content-docs/current'); + await mkdir(target, { recursive: true }); + const archive = join(work, 'translation-ja.tgz'); + execFileSync('curl', [ + '-fsSL', + 'https://codeload.github.com/ionic-team/ionic-docs/tar.gz/' + japaneseDocsRef, + '-o', + archive, + ]); + execFileSync('tar', [ + '-xzf', + archive, + '-C', + target, + '--strip-components=2', + 'ionic-docs-' + japaneseDocsRef + '/docs', + ]); + const file = join(work, 'api-ja.json'); + execFileSync('curl', [ + '-fsSL', + 'https://raw.githubusercontent.com/ionic-jp/ionic-docs/' + + japaneseApiRef + + '/scripts/data/translated-api.json', + '-o', + file, + ]); + if ( + createHash('sha256') + .update(await readFile(file)) + .digest('hex') !== japaneseApiDigest + ) + throw Error('Unexpected Japanese API definitions'); +} + +const apiInputs = [ + { + major: '8', + version: '8.8.20', + sha256: '7b3182b656c01a58cb1fa35cd956e60156cb2a62a1e235eb695416f55aa34bd5', + }, + { + major: '9', + version: '9.0.0', + sha256: '2f201959495aa9e17c0e0fef0edbcbd4b7e3db5f65f5d43194e4ec27229dd8a7', + }, +]; +export const ionicCore = 'node_modules/@ionic/angular/node_modules/@ionic/core'; + +export async function pinApiInputs(work) { + const current = apiInputs.at(-1); + const runtime = JSON.parse(await readFile(join(ionicCore, 'package.json'), 'utf8')); + if (runtime.version !== current.version) + throw new Error('Update the pinned API definitions to match the demo runtime'); + const versions = JSON.parse(await readFile(join(work, 'versions.json'), 'utf8')); + if ( + versions.join(',') !== + apiInputs + .slice(0, -1) + .map((x) => 'v' + x.major) + .join(',') + ) { + throw new Error('Review and pin the API inputs for the new Ionic Docs versions'); + } + for (const { major, version, sha256 } of apiInputs) { + const file = join(work, 'api-v' + major + '.json'); + execFileSync('curl', [ + '-fsSL', + 'https://unpkg.com/@ionic/docs@' + version + '/core.json', + '-o', + file, + ]); + if ( + createHash('sha256') + .update(await readFile(file)) + .digest('hex') !== sha256 + ) { + throw new Error('Unexpected core.json for @ionic/docs@' + version); + } + } + // Keep the upstream rendering logic. Only replace its mutable registry input. + const plugin = join(work, 'plugins/docusaurus-plugin-ionic-component-api/index.js'); + const fetchJapanese = + 'await fetch(`https://raw.githubusercontent.com/ionic-jp/ionic-docs/main/scripts/data/translated-api.json`)'; + const original = await readFile(plugin, 'utf8'); + if (original.split(fetchJapanese).length !== 2) + throw Error('Review the upstream Japanese API adapter'); + const source = original.replace( + fetchJapanese, + '({text: () => require("node:fs/promises").readFile(require("node:path").resolve(__dirname, "../../api-ja.json"), "utf8")})', + ); + const fetchApi = 'await fetch(`https://unpkg.com/@ionic/docs@${npmTag}/core.json`)'; + if (source.split(fetchApi).length !== 2) throw new Error('Review the upstream API input adapter'); + await writeFile( + plugin, + source.replace( + fetchApi, + '({text: () => require("node:fs/promises").readFile(require("node:path").resolve(__dirname, "../../api-" + version + ".json"), "utf8")})', + ), + ); +} + +export async function installDistributionNotices(work, assets, revision) { + const licenses = join(assets, 'licenses'); + await mkdir(licenses, { recursive: true }); + const packages = [ + [ionicCore, 'ionic-core'], + ['node_modules/ionicons', 'ionicons'], + ...['ios26', 'ios27', 'md3'].map((theme) => [ + 'node_modules/@rdlabo/ionic-theme-' + theme, + 'ionic-theme-' + theme, + ]), + ]; + await cp( + 'scripts/ionic-preview/licenses/ionic-framework.txt', + join(licenses, 'ionic-docs-api.txt'), + ); + const notices = [ + 'WebView Native UI component reference', + '', + 'Articles and live examples are compiled from Ionic Docs (Apache-2.0).', + 'Source: https://github.com/ionic-team/ionic-docs/tree/' + revision, + 'Japanese articles: https://github.com/ionic-team/ionic-docs/tree/' + japaneseDocsRef, + 'Japanese API definitions: https://github.com/ionic-jp/ionic-docs/blob/' + + japaneseApiRef + + '/scripts/data/translated-api.json', + 'See LICENSE for the complete Apache License.', + 'Changes: rendered the original articles and code samples for this portal;', + 'live examples load local runtimes and themes and forward console output.', + '', + 'API definitions: @ionic/docs@' + + apiInputs.at(-1).version + + ' (see licenses/ionic-docs-api.txt).', + 'SHA-256 of core.json: ' + apiInputs.at(-1).sha256, + '', + ]; + for (const [dir, basename] of packages) { + const { name, version } = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')); + const filename = basename + '.txt'; + await cp(join(dir, 'LICENSE'), join(licenses, filename)); + notices.push(name + '@' + version + ': licenses/' + filename); + } + await cp( + 'node_modules/@rdlabo/ionic-theme-md3/THIRD_PARTY_NOTICES.md', + join(licenses, 'ionic-theme-md3-notices.md'), + ); + notices.push( + 'Material Design 3 theme notices: licenses/ionic-theme-md3-notices.md', + '', + 'Roboto fonts: Copyright 2011 Google Inc. All Rights Reserved. Apache-2.0 (see LICENSE).', + ); + await mkdir(join(assets, 'usage/fonts'), { recursive: true }); + for (const weight of ['Regular', 'Medium']) { + const font = 'Roboto-' + weight + '.ttf'; + await cp(join(work, 'static/fonts', font), join(assets, 'usage/fonts', font)); + } + await writeFile(join(assets, 'NOTICE.txt'), notices.join('\n') + '\n'); +} diff --git a/scripts/preview-ionic-components.mjs b/scripts/preview-ionic-components.mjs new file mode 100644 index 0000000..e560e73 --- /dev/null +++ b/scripts/preview-ionic-components.mjs @@ -0,0 +1,106 @@ +// Compile upstream MDX with Node 24, then export the articles to the Angular portal. +import { execFileSync } from 'node:child_process'; +import { cp, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { installGenerated } from './ionic-preview/install-generated.mjs'; +import { build } from 'esbuild'; +import { ionicCore, pinApiInputs, prepareJapaneseDocs } from './ionic-preview/upstream-inputs.mjs'; + +const ref = process.argv[2] ?? 'a79918700e48c6ae3c8c14e06964d413c7b219ef'; +if (!/^[a-f0-9]{40}$/.test(ref)) throw new Error('Expected an ionic-docs commit SHA'); +const work = await mkdtemp(join(tmpdir(), 'ionic-docs-')); +try { + const run = (cmd, args) => execFileSync(cmd, args, { cwd: work, stdio: 'inherit' }); + run('curl', [ + '-fsSL', + `https://codeload.github.com/ionic-team/ionic-docs/tar.gz/${ref}`, + '-o', + 'source.tgz', + ]); + run('tar', ['-xzf', 'source.tgz', '--strip-components=1']); + run('npm', ['ci', '--ignore-scripts', '--legacy-peer-deps', '--no-audit']); + await prepareJapaneseDocs(work); + await pinApiInputs(work); + run('node', ['scripts/native.mjs']); + run('node', ['scripts/cli.mjs']); + // Release history is outside the component export. Its upstream loader + // requires this JSON module even though no release pages are distributed. + await writeFile( + join(work, 'src/components/page/reference/ReleaseNotes/release-notes.json'), + '[]', + ); + + await cp( + 'scripts/ionic-preview/Playground.tsx', + join(work, 'src/components/global/Playground/index.tsx'), + ); + await cp('scripts/ionic-preview/config.cjs', join(work, 'preview.config.cjs')); + await writeFile( + join(work, 'src/theme/TOC/index.tsx'), + "export {default} from '@theme-original/TOC';\n", + ); + + const assets = join(work, 'static/preview-assets'); + await mkdir(assets, { recursive: true }); + for (const folder of ['css', 'dist/ionic']) { + await cp(join(ionicCore, folder), join(assets, folder), { + recursive: true, + }); + } + await build({ + entryPoints: { + ios26: '@rdlabo/ionic-theme-ios26/styles/class.css', + ios27: '@rdlabo/ionic-theme-ios27/styles/class.css', + md: '@rdlabo/ionic-theme-md3/styles/theme.css', + }, + outdir: assets, + bundle: true, + minify: true, + }); + const usage = join(work, 'static/usage/v9'); + const cdn = 'https://cdn.jsdelivr.net/npm/@ionic/core@9/'; + for (const file of await readdir(usage, { recursive: true })) { + if (!file.endsWith('/demo.html') && file !== 'common.js') continue; + const path = join(usage, file); + let source = (await readFile(path, 'utf8')).replaceAll( + cdn, + '/assets/ionic-components/runtime/', + ); + if (file === 'common.js') { + source = + '// Modified by WebView Native UI: use local resources and forward console output.\n' + + source; + source += + "\nwindow.addEventListener('console', ({detail}) => parent.postMessage({ionicDemoLog:detail.message},location.origin));\n"; + } + if (file.endsWith('.html')) { + source = source.replace( + '', + ` + `, + ); + } + await writeFile(path, source); + } + const output = resolve('dist/ionic-components/docs'); + run('node', [ + 'node_modules/@docusaurus/core/bin/docusaurus.mjs', + 'build', + '--config', + 'preview.config.cjs', + '--out-dir', + output, + ]); + await installGenerated(work, output, ref); +} finally { + await rm(work, { recursive: true, force: true }); +}