Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions Scripts/build-website.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { fileURLToPath } from 'node:url';
import path from 'node:path';
import os from 'node:os';
import { createHash } from 'node:crypto';
import { guidePath, renderGuide, renderGuideCards, tutorialContent } from '../website/tutorials.mjs';

export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const appInfo = await readFile(path.join(root, 'AppResources/Info.plist'), 'utf8');
Expand Down Expand Up @@ -85,7 +86,9 @@ export function renderPage(template, language, copy, screenshots, assetVersions,
`<script id="software-schema" type="application/ld+json">${JSON.stringify(schema).replace(/</g, '\\u003c')}</script>`
].join('\n ');
const languageLinks = languages.map(l => `<a href="${prefix}${localePath(l.id)}" lang="${l.locale}" hreflang="${l.locale}" data-language="${l.id}"${l.id === language.id ? ' aria-current="page"' : ''}>${l.name}</a>`).join('\n ');
const values = { ...copy, head, languageLinks,
const guideLabel = tutorialContent.locales[language.id]?.nav;
const guideNav = guideLabel ? `<a href="#guides">${escape(guideLabel)}</a>` : '';
const values = { ...copy, head, languageLinks, guideNav, guideCards: renderGuideCards(language.id, prefix),
armDownloadURL: `https://github.com/ixiehao/MP4Flow/releases/latest/download/MP4Flow-${appVersion}-arm64.dmg`,
intelDownloadURL: `https://github.com/ixiehao/MP4Flow/releases/latest/download/MP4Flow-${appVersion}-x86_64.dmg`, scriptVersion: assetVersions.script, locale: language.locale, language: language.id, languageName: language.name,
privacyURL: `https://github.com/ixiehao/MP4Flow/blob/main/PRIVACY${language.id === 'ja' ? '.ja' : ''}.md` };
Expand All @@ -97,7 +100,7 @@ export function renderPage(template, language, copy, screenshots, assetVersions,
}
let result = template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
if (!(key in values)) throw new Error(`Missing template value: ${key}`);
return ['head', 'languageLinks'].includes(key) ? values[key] : escape(values[key]).replace(/\n/g, '<br />');
return ['head', 'languageLinks', 'guideNav', 'guideCards'].includes(key) ? values[key] : escape(values[key]).replace(/\n/g, '<br />');
});
result = result.replace('<html lang=', `<html data-language="${language.id}" data-root="${prefix}" lang=`);
result = result.replace(/(href|src)="(assets\/|styles\.css|app\.js)/g, `$1="${prefix}$2`);
Expand All @@ -122,6 +125,23 @@ export async function buildSite(output = path.join(root, '_site')) {
await readFile(path.join(root, 'website', shot.src));
}
}
const guideLanguages = languages.filter(language => language.id in tutorialContent.locales);
for (const [slug, guide] of Object.entries(tutorialContent.guides)) {
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug) || !/^[a-zA-Z0-9-]+\.(mkv|mov|mp4)$/.test(guide.sample)) {
throw new Error(`Invalid tutorial source: ${slug}`);
}
await readFile(path.join(root, 'website/assets/tutorials', guide.sample));
for (const { id } of guideLanguages) {
const { media } = guide[id];
const imagePath = `assets/tutorials/v${tutorialContent.captureVersion.replaceAll('.', '')}-${guide.capture}-${id}.webp`;
if (media.src !== imagePath || !Number.isSafeInteger(media.width) || media.width <= 0
|| !Number.isSafeInteger(media.height) || media.height <= 0) {
throw new Error(`Invalid tutorial screenshot: ${slug}/${id}`);
}
const hash = createHash('sha256').update(await readFile(path.join(root, 'website', media.src))).digest('hex');
if (hash !== media.sha256) throw new Error(`Changed tutorial screenshot: ${slug}/${id}`);
}
}
await rm(output, { recursive: true, force: true });
await mkdir(output, { recursive: true });
await cp(path.join(root, 'website/assets'), path.join(output, 'assets'), { recursive: true });
Expand All @@ -135,8 +155,23 @@ export async function buildSite(output = path.join(root, '_site')) {
const english = languages.find(language => language.id === 'en');
await mkdir(path.join(output, 'en'), { recursive: true });
await writeFile(path.join(output, 'en/index.html'), renderPage(template, english, catalogs.en, screenshots, assetVersions, 'en/'));
const alternates = [...languages.map(l => ({ locale: l.locale, url: siteURL + localePath(l.id) })), { locale: 'x-default', url: siteURL }];
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n${languages.map(l => ` <url><loc>${siteURL}${localePath(l.id)}</loc>\n${alternates.map(a => ` <xhtml:link rel="alternate" hreflang="${a.locale}" href="${a.url}" />`).join('\n')}\n </url>`).join('\n')}\n</urlset>\n`;
const sitemapGroup = (editions, route) => editions.map(language => {
const alternates = [...editions, { locale: 'x-default', id: 'en' }];
return ` <url><loc>${siteURL}${route(language.id)}</loc>\n${alternates.map(a => ` <xhtml:link rel="alternate" hreflang="${a.locale}" href="${siteURL}${route(a.id)}" />`).join('\n')}\n </url>`;
});
const entries = sitemapGroup(languages, localePath);
for (const [slug, guide] of Object.entries(tutorialContent.guides)) {
for (const language of guideLanguages) {
const directory = path.join(output, guidePath(slug, language.id));
const media = guide[language.id].media;
await mkdir(directory, { recursive: true });
await writeFile(path.join(directory, 'index.html'), renderGuide({
slug, language, languages, siteURL, styles, siteCopy: catalogs[language.id], media
}));
}
entries.push(...sitemapGroup(guideLanguages, id => guidePath(slug, id)));
}
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n${entries.join('\n')}\n</urlset>\n`;
await writeFile(path.join(output, 'sitemap.xml'), sitemap);
return output;
}
Expand Down
39 changes: 32 additions & 7 deletions Scripts/search-content.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,19 @@ def language_ids(config):
def page_url(config, language):
return config['site_url'] + ('' if language == 'en' else language + '/')

def inspect_page(html, canonical, language, urls):
def tutorial_groups(config):
if 'tutorial_source' not in config:
return []
content = json.loads((ROOT/config['tutorial_source']).read_text())
ids = list(content['locales'])
require('en' in ids and set(ids) <= set(language_ids(config)), 'Invalid tutorial languages')
groups = []
for slug in content['guides']:
require(re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', slug), 'Invalid tutorial slug')
groups.append({language: page_url(config, language)+'guides/'+slug+'/' for language in ids})
return groups

def inspect_page(html, canonical, language, urls, site=None):
doc = Document(html)
root, main, title = doc.find('html'), doc.find('main'), doc.find('title')
require(root is not None and root.attrs.get('lang', '').split('-')[0] == language, f'{canonical}: wrong HTML language')
Expand All @@ -146,14 +158,15 @@ def inspect_page(html, canonical, language, urls):
md = doc.find('link', type='text/markdown')
require(md is not None and urljoin(canonical, md.attrs.get('href', '')) == canonical+'index.md', f'{canonical}: missing Markdown alternate')
descriptor = doc.find('link', rel='describedby')
require(descriptor is not None and urljoin(canonical, descriptor.attrs.get('href', '')) == urls['en']+'llms.txt', f'{canonical}: missing AI reading index')
require(descriptor is not None and urljoin(canonical, descriptor.attrs.get('href', '')) == (site or urls['en'])+'llms.txt', f'{canonical}: missing AI reading index')
schemas = [json.loads(node.text()) for node in doc.root.nodes() if node.tag == 'script' and node.attrs.get('type') == 'application/ld+json']
require(schemas, f'{canonical}: missing structured data')
graphs = [entry for schema in schemas for entry in schema.get('@graph', [schema])]
require(any(node.get('@type') in ('SoftwareApplication', 'WebSite', 'ProfilePage') for node in graphs), f'{canonical}: missing page/application schema')
types = ('Article',) if site else ('SoftwareApplication', 'WebSite', 'ProfilePage')
require(any(node.get('@type') in types for node in graphs), f'{canonical}: missing page/application schema')
for node in graphs:
if node.get('@type') == 'SoftwareApplication':
require(node.get('url') == canonical and node.get('description') == description.attrs['content'], f'{canonical}: application facts differ from metadata')
if node.get('@type') in ('SoftwareApplication', 'Article'):
require(node.get('url') == canonical and node.get('description') == description.attrs['content'], f'{canonical}: structured data differs from metadata')
body = markdown(doc.find('body'), canonical)
text = '# ' + title.text().strip() + '\n\n> ' + description.attrs['content'].strip() + '\n\n<' + canonical + '>\n\n' + body
text = re.sub(r'[\t ]+\n', '\n', text)
Expand All @@ -177,9 +190,11 @@ def build(config, check=False):
ids = language_ids(config)
urls = {language: page_url(config, language) for language in ids}
site = config['site_url']
tutorials = tutorial_groups(config)
canonical_pages = [canonical for group in [urls, *tutorials] for canonical in group.values()]
sitemap = ET.fromstring((directory/'sitemap.xml').read_text())
locations = [node.text for node in sitemap.findall('{*}url/{*}loc')]
require(len(locations) == len(urls) and set(locations) == set(urls.values()), 'Sitemap does not match actual canonical languages')
require(len(locations) == len(canonical_pages) and set(locations) == set(canonical_pages), 'Sitemap does not match actual canonical pages')
summaries = {}
for language, canonical in urls.items():
folder = directory/('' if language == 'en' else language)
Expand All @@ -188,6 +203,15 @@ def build(config, check=False):
compare_or_write(folder/'index.md', text, check)
lines = ['# '+config['name'], '', '> '+summaries['en'], '', '## Pages', '']
lines += [f'- [{LANGUAGE_NAMES.get(language, language)}]({canonical}index.md)' for language, canonical in urls.items()]
if tutorials:
lines += ['', '## Guides', '']
for group in tutorials:
for language, canonical in group.items():
folder = directory/canonical.removeprefix(site)
text, _ = inspect_page((folder/'index.html').read_text(), canonical, language, group, site)
compare_or_write(folder/'index.md', text, check)
title = text.splitlines()[0].removeprefix('# ')
lines.append(f'- [{title} ({LANGUAGE_NAMES[language]})]({canonical}index.md)')
if config.get('projects'):
lines += ['', '## Projects', '']
lines += [f'- [{project["name"]}]({project["url"]}): {project["description"]}' for project in config['projects']]
Expand All @@ -196,13 +220,14 @@ def build(config, check=False):
compare_or_write(directory/'indexnow-key.txt', ownership_key(config)+'\n', check)
for url in config.get('root_sitemaps', []):
require('Sitemap: '+url in (directory/'robots.txt').read_text(), 'Domain-root robots is missing '+url)
return len(ids)
return len(canonical_pages)

def notification(config):
base = config['site_url']
origin = urlsplit(base)
require(origin.scheme == 'https' and base.endswith('/') and not origin.query and not origin.fragment, 'Use the production HTTPS directory')
urls = [page_url(config, language) for language in language_ids(config)]
urls += [canonical for group in tutorial_groups(config) for canonical in group.values()]
require(all(url.startswith(base) and not urlsplit(url).query for url in urls), 'URLs must stay in this project scope')
return {'host': origin.netloc, 'key': ownership_key(config), 'keyLocation': base+'indexnow-key.txt', 'urlList': urls}

Expand Down
20 changes: 18 additions & 2 deletions Scripts/tests/website.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'node:path';
import os from 'node:os';
import { createHash } from 'node:crypto';
import { appVersion, buildSite, languages, localePath, readCatalogs, siteURL } from '../build-website.mjs';
import { guidePath, tutorialContent } from '../../website/tutorials.mjs';

test('seven canonical pages are complete, crawlable and use matching real screenshots', async t => {
const output = await mkdtemp(path.join(os.tmpdir(), 'mp4flow-website-test-'));
Expand Down Expand Up @@ -142,12 +143,27 @@ test('seven canonical pages are complete, crawlable and use matching real screen
assert.ok(chineseReadme.includes('[官方网站](https://ixiehao.github.io/MP4Flow/zh/)'));
});
const sitemap = await readFile(path.join(output, 'sitemap.xml'), 'utf8');
assert.equal((sitemap.match(/<loc>/g) ?? []).length, 7);
assert.equal((sitemap.match(/xhtml:link/g) ?? []).length, 56);
const guideLanguages = Object.keys(tutorialContent.locales);
const guideCount = Object.keys(tutorialContent.guides).length * guideLanguages.length;
assert.equal((sitemap.match(/<loc>/g) ?? []).length, languages.length + guideCount);
assert.equal((sitemap.match(/xhtml:link/g) ?? []).length, 56 + guideCount * (guideLanguages.length + 1));
assert.doesNotMatch(sitemap, /https:\/\/ixiehao.github.io\/MP4Flow\/en\//);
assert.match(sitemap, /<loc>https:\/\/ixiehao.github.io\/MP4Flow\/zh\/<\/loc>/);
await assert.rejects(stat(path.join(output, 'locales')));
await assert.rejects(stat(path.join(output, 'Scripts')));
const sample = await readFile(path.join(output, 'assets/tutorials/Patterns.mkv'));
assert.equal(sample.subarray(0, 4).toString('hex'), '1a45dfa3');
for (const [slug, guide] of Object.entries(tutorialContent.guides)) {
for (const id of guideLanguages) {
const route = guidePath(slug, id);
const html = await readFile(path.join(output, route, 'index.html'), 'utf8');
assert.ok(sitemap.includes(`<loc>${siteURL}${route}</loc>`));
assert.ok(html.includes(`rel="canonical" href="${siteURL}${route}"`));
assert.ok(html.includes(`<h1 id="guide-title">${guide[id].title}</h1>`));
assert.equal((html.match(/<link rel="alternate" hreflang=/g) ?? []).length, guideLanguages.length + 1);
assert.equal((html.match(/<li><h2>/g) ?? []).length, 3);
}
}
});

test('42 localized captures match their provenance and actual JPEG dimensions', async () => {
Expand Down
8 changes: 7 additions & 1 deletion docs/WEBSITE.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ The existing GitHub Pages site stays at <https://ixiehao.github.io/MP4Flow/>.

- `website/index.html` is the shared template; `website/locales/*.json` contains all public copy, accessible labels and metadata.
- `Scripts/build-website.mjs` uses Node.js standard libraries to generate `_site/`. No framework, package install or runtime translation request is required.
- Each generated page contains its full translation, canonical URL, reciprocal `hreflang` links, share metadata and structured data. The build also creates the seven-page sitemap.
- Each generated page contains its full translation, canonical URL, reciprocal `hreflang` links, share metadata and structured data. The build also creates the sitemap for the seven home pages and the localized guides.
- English is served directly at the root, including without JavaScript. The old `/MP4Flow/en/` remains an English alias with the root as its canonical URL; only the seven canonical routes appear in the sitemap.
- Existing `?lang=en`, `?lang=ja` and other supported language links redirect to the corresponding page, preserving the section and other query parameters. Explicit page URLs take priority over browser language or old preferences.
- Query-language routing uses the generated language links rather than maintaining a second route map in JavaScript.
Expand All @@ -38,6 +38,12 @@ Phone layouts show one visual article per row; wider screens use two columns. Ke

The FAQ uses the same full-width, pale rounded panel as the surrounding sections. Place its heading beside the disclosure cards on desktop and above them on phones. Keep the native `details` controls, visible keyboard focus and a generous question hit area; long translations and expanded answers must remain inside their cards.

## Task guides

`website/tutorials.json` holds three task guides in English, Simplified Chinese and Japanese. The builder publishes standalone Guides pages with reciprocal language links, an equivalent Markdown page, and sitemap entries. Homepage links appear in those three languages.

Each guide uses a synthetic downloadable example, three steps and a check of the exported result. The screenshots were captured from the matching released App in isolated macOS CI windows. Their version, dimensions, hashes, captions and alternate text are in the same catalog. Publish only the inspected WebP derivatives and the sample inputs.

## Native installer messaging

The hero highlights a lightweight native macOS app. “About 3 MB” describes each compressed, architecture-specific DMG; it excludes separately installed FFmpeg/ffprobe. Keep that distinction visible in the download section. Apple Silicon (`arm64`) and Intel (`x86_64`) downloads are explicit choices, with an About This Mac hint; do not infer CPU architecture from a browser user agent. The static generator reads the release version from `AppResources/Info.plist` for download asset names and `SoftwareApplication.softwareVersion`. Confirm both assets exist before deploying a new version of these links. Screenshot provenance retains its actual capture version.
Expand Down
3 changes: 2 additions & 1 deletion search-content.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"directory": "_site",
"source_url": "https://github.com/ixiehao/MP4Flow",
"key_file": "website/indexnow-key.txt",
"language_source": "website/locales/*.json"
"language_source": "website/locales/*.json",
"tutorial_source": "website/tutorials.json"
}
Loading
Loading