Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat(studio): load interface languages from explicit JSON packs
kashorind1168c1ba237
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8b12e797..0d1bdece 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -34,6 +34,7 @@ Live Builds additionally need Python 3.10–3.13, uv, ffmpeg and Chromium. The| A new Author Package | [Adding an Author Package](https://hypit.ai/guide/author-packages/) || A new Provider | [Adding a Provider](https://hypit.ai/guide/providers/) || Component internals | [Component Anatomy](https://hypit.ai/guide/component-anatomy/) |+| Studio interface translations | [Localizing Studio](packages/studio/LOCALIZATION.md) || Compilation, Runs and Builds | [Runtime](https://hypit.ai/guide/runtime/) || Naming, module boundaries, wire data | [Conventions](https://hypit.ai/guide/conventions/) || Tests and environment-gated suites | [Testing](https://hypit.ai/guide/testing/) |diff --git a/CONTRIBUTING.zh-CN.md b/CONTRIBUTING.zh-CN.mdindex 71cee0f1..9751fed3 100644--- a/CONTRIBUTING.zh-CN.md+++ b/CONTRIBUTING.zh-CN.md@@ -27,6 +27,7 @@ pnpm install --frozen-lockfile| --- | --- || 新增 Author 包 | [添加 Author 包](https://hypit.ai/zh/guide/author-packages/) || 新增 Provider | [添加 Provider](https://hypit.ai/zh/guide/providers/) |+| Studio 界面翻译 | [Studio 本地化](packages/studio/LOCALIZATION.md) || 编译、Run 与 Build | [Runtime](https://hypit.ai/zh/guide/runtime/) || 命名、模块边界、wire 数据 | [代码规范](https://hypit.ai/zh/guide/conventions/) || 测试与依赖环境的测试套件 | [测试](https://hypit.ai/zh/guide/testing/) |diff --git a/docs/guide/develop.md b/docs/guide/develop.mdindex 338fd74b..f573b43a 100644--- a/docs/guide/develop.md+++ b/docs/guide/develop.md@@ -55,5 +55,6 @@ hypit/| [Adding an author package](./author-packages.md) | Step-by-step: new component, Surface, vocabulary and preview, activation || [Models and Providers](./providers.md) | Select accounts and APIs; develop a Model or Provider package || [Runtime](./runtime.md) | Profile, Workspace, execution and lifecycle boundaries |+| [Studio localization](https://github.com/hypit-ai/hypit/blob/main/packages/studio/LOCALIZATION.md) | Translate interface messages; load a local JSON file or an installed language pack || [Testing](./testing.md) | Test runner, patterns, examples, boundary tests || [Conventions](./conventions.md) | Naming, module boundaries, wire data, TypeScript config |diff --git a/docs/quickstart/preview.md b/docs/quickstart/preview.mdindex 3f0caf2a..11a6d283 100644--- a/docs/quickstart/preview.md+++ b/docs/quickstart/preview.md@@ -5,7 +5,7 @@ description: Explore a composition, its Sources and Results, and edit its timingStudio opens an editable video project in the browser. Play the composition, move through itsframes, select words or graphics on the timeline, and change the properties a component exposes.-It is also a useful way to hand over a finished project alongside the exported video.+Switch to **Comments** for a larger picture and timestamped feedback. Both views work before export.## Open the work you want to edit@@ -18,6 +18,11 @@ Open the address printed by the command. Studio uses the Author Source and materthat Run. To keep generated material while editing, select completed Outputs with[`build-record` and `satisfy`](./run.md#reusing-results).+The **globe menu**, to the left of **Studio / Comments**, selects the interface language.+English and Simplified Chinese are included. The first visit follows your browser language;+later visits remember your choice. Switching preserves the playhead, selection and comment draft.+It changes the interface, while your Script, video captions and comments keep their own content.+| Argument | Use || --- | --- || `--run <file.svrun>` | Select the Run to open. |@@ -25,12 +30,23 @@ that Run. To keep generated material while editing, select completed Outputs wit| `--workspace <directory>` | Set the project boundary for Source access and edits. || `--port <number>` | Request a browser-server port; the default is `5179`. |-The selected target must lead to one Film and its time source. A spoken performance supplies a-Timeline; an animation can supply an authored ProgramSpace. Both support visual components and+The selected target must lead to one Film and its Timeline. Placed Takes add their semantic anchors;+an animation can use a Timeline with an explicit end and no Takes. Both support visual components andproperty editing. The material needed to display the composition must already be available throughthe Run. Studio can perform media preparation supported by the selected Runtime; submit generationand encoded renders through `hypit build`.+## Review together in Comments++Open the printed URL ending in `#comments` to watch the current composition with a notes column.+Click the picture to play or pause, then leave a comment at the selected time. Clicking a saved note+returns to that frame. Notes appear in time order; their numbers follow submission order.++Comments are saved in the project's `FEEDBACK.json`. You and your Agent can read, edit and mark them+complete. Sending a note saves it; tell your Agent when the feedback is ready to work through.+Switch to **Studio** to explore the timeline, Sources, Results and the controls components expose.+Opening either view does not encode a video or submit an export Build.+## Explore the projectThe library at the left has three views:@@ -65,16 +81,22 @@ Moving a shared Selection or Moment changes its position in the Script, so all cthat change. Editing a shared Frame or Recipe can likewise affect several appearances.Check the save status after an edit. If recompilation fails, Studio reports the error and restores-the previous files. Use Apply or Reset for a structured Inspector draft. The Run and loaded Source+the previous files. List and record controls save complete, valid values when editing ends and show+a completion hint for incomplete values. The Run and loaded Sourcefiles are watched; restart Studio after changing installed packages, component code or Runtimeselection so those changes are loaded too.## Sound and deliveryPreview playback includes the AudioTracks selected in Film, such as speech, music and effects.-The exported video's audio is assembled by the render's media pipeline. Deliver the encoded video;-Studio lets the recipient explore the editable composition as well.+The exported video's audio is assembled by the render's media pipeline. When the composition is+ready for delivery, run its export Build to create the encoded video. Studio and Comments remain+available to explore the editable work and discuss further changes.For component authors, [Studio Temporal Lineage](../guide/studio-temporal-windows.md) explains semanticediting, and the [Companion SDK](https://github.com/hypit-ai/hypit/blob/main/packages/studio-adapter/README.md)explains how to expose component entities and controls.++To add another interface language, load a local JSON translation with `--locale-pack ./language.json`.+The [localization guide](https://github.com/hypit-ai/hypit/blob/main/packages/studio/LOCALIZATION.md)+explains translation files, checking missing entries and sharing a language pack.diff --git a/docs/zh/guide/develop.md b/docs/zh/guide/develop.mdindex e33b4b9f..6328688a 100644--- a/docs/zh/guide/develop.md+++ b/docs/zh/guide/develop.md@@ -55,5 +55,6 @@ hypit/| [添加 Author 包](./author-packages.md) | 分步说明:新增组件、Surface、词表与预览图、activation || [模型与 Provider](./providers.md) | 选择账户与 API,开发 Model 或 Provider 包 || [Runtime](./runtime.md) | Profile、Workspace、执行与生命周期边界 |+| [Studio 本地化](https://github.com/hypit-ai/hypit/blob/main/packages/studio/LOCALIZATION.md) | 翻译界面文案,加载本地 JSON 或已安装的语言包 || [测试](./testing.md) | 测试运行器、写法、示例、boundary tests || [代码规范](./conventions.md) | 命名、模块边界、wire 数据、TypeScript 配置 |diff --git a/docs/zh/quickstart/preview.md b/docs/zh/quickstart/preview.mdindex ea835940..78379083 100644--- a/docs/zh/quickstart/preview.md+++ b/docs/zh/quickstart/preview.md@@ -3,7 +3,7 @@ title: Hypit Studiodescription: 浏览编排、Source 和 Result,编辑作品的时机与外观。----Studio 在浏览器中打开可编辑的视频项目。你可以播放编排、逐帧查看,在时间线上选择词语或图形,并修改组件公开的属性。交付成片时,也可以一起打开 Studio,展示作品的可编辑结构。+Studio 在浏览器中打开可编辑的视频项目。你可以播放编排、逐帧查看,在时间线上选择词语或图形,并修改组件公开的属性。切换到 **Comments** 可以用更大的画面查看作品、按时间留下反馈。两个视图都可以在导出之前使用。## 打开要编辑的作品@@ -14,6 +14,8 @@ hypit studio --run build.svrun打开命令打印的网址。Studio 使用这份 Run 选择的 Author Source 和素材。编辑时要保留已生成素材,可以通过 [`build-record` 与 `satisfy`](./run.md) 选择已完成的 Output。+**Studio / Comments 左侧的地球菜单**可以切换界面语言,内置英文和简体中文。首次访问跟随浏览器语言,之后记住你的选择。切换时保留播放位置、选中状态和评论草稿;稿子、视频字幕和评论内容保持原样。+| 参数 | 用途 || --- | --- || `--run <file.svrun>` | 选择要打开的 Run。 |@@ -21,7 +23,13 @@ hypit studio --run build.svrun| `--workspace <directory>` | 设置 Source 访问与修改的项目边界。 || `--port <number>` | 指定浏览器服务端口,默认请求 `5179`。 |-所选目标需要指向一个 Film 及其时间来源。说话表演可以提供 Timeline,动画可以使用作者声明的 ProgramSpace,两者都支持视觉组件与属性编辑。显示编排所需的素材应已通过 Run 提供。Studio 可以完成所选 Runtime 支持的媒体准备;生成和编码渲染通过 `hypit build` 提交。+所选目标需要指向一个 Film 及其 Timeline。放入的 Take 带来对应的语义锚点;纯动画也使用 Timeline,声明结束时间、不放入 Take 即可。两者都支持视觉组件与属性编辑。显示编排所需的素材应已通过 Run 提供。Studio 可以完成所选 Runtime 支持的媒体准备;生成和编码渲染通过 `hypit build` 提交。++## 在 Comments 一起看作品++打开命令打印的、以 `#comments` 结尾的网址,可以在画面旁看到评论区。点击画面播放或暂停,在选定时间留下意见;点击已保存的评论即可回到对应帧。评论按时间排列,编号按留言顺序显示。++评论保存在项目的 `FEEDBACK.json` 中,你和 Agent 都可以读取、修改、标记完成。发送评论会保存意见;写好后告诉 Agent 开始处理即可。切换到 **Studio** 则可以查看时间线、Source、Result,以及组件公开的控件。打开两个视图都不会编码视频,也不会提交导出 Build。## 浏览项目@@ -45,10 +53,12 @@ Inspector 显示所选实体的属性。可编辑字段与时间线手柄由组Source 编辑修改所选 `.svml`、`.svs` 或 `.svrun` 文件。支持的 Inspector 修改和时间线手势会写回对应作者值,然后用同一份 Run 重新编译。移动共享的 Selection 或 Moment,会改变它在 Script 中的位置,使用它的组件随之更新;修改共享 Frame 或 Recipe,也可能影响多个画面元素。-编辑后查看保存状态。重新编译失败时,Studio 显示错误并恢复之前的文件。结构化 Inspector 草稿使用 Apply 或 Reset。Run 和已加载 Source 文件会被监听;更换安装包、组件代码或 Runtime 选择后,需要重启 Studio 来加载这些变化。+编辑后查看保存状态。重新编译失败时,Studio 显示错误并恢复之前的文件。列表与记录控件在结束编辑时保存完整、有效的值;未填写完整时会显示提示。Run 和已加载 Source 文件会被监听;更换安装包、组件代码或 Runtime 选择后,需要重启 Studio 来加载这些变化。## 声音与交付-预览播放包含 Film 选中的 AudioTrack,例如口播、音乐与音效。导出视频的音频由渲染的媒体管线装配。交付编码后的成片,同时可以用 Studio 浏览其可编辑编排。+预览播放包含 Film 选中的 AudioTrack,例如口播、音乐与音效。导出视频的音频由渲染的媒体管线装配。作品准备好交付后,运行导出 Build 得到编码后的成片;Studio 与 Comments 仍可用于查看可编辑作品、沟通后续修改。组件作者可以阅读 [Studio 时间谱系](../guide/studio-temporal-windows.md) 了解语义编辑,以及 [Companion SDK](https://github.com/hypit-ai/hypit/blob/main/packages/studio-adapter/README.md) 了解如何公开组件实体和控件。++需要其他界面语言时,可以通过 `--locale-pack ./language.json` 加载本地 JSON 译文。[本地化指南](https://github.com/hypit-ai/hypit/blob/main/packages/studio/LOCALIZATION.md) 介绍译文格式、缺项检查和语言包分享方法。diff --git a/packages/studio/LOCALIZATION.md b/packages/studio/LOCALIZATION.mdnew file mode 100644index 00000000..a39e3c29--- /dev/null+++ b/packages/studio/LOCALIZATION.md@@ -0,0 +1,98 @@+# Localizing Studio++Studio owns its interface messages; a language pack supplies their wording. The+English catalog in [locales/en.json](locales/en.json) is the complete list of+message IDs. [Simplified Chinese](locales/zh-CN.json) uses exactly the same format+as any additional language. A pack is JSON data, not executable code.++## Add a language++Copy `locales/en.json`, change `locale` (a BCP 47 tag such as `ja` or `pt-BR`),+`name` (the language's native name), and translate the message values. Keep the+message IDs. `direction` is `ltr` or `rtl` and controls translated text; it does+not reverse the physical video timeline or canvas coordinates.++A small, valid starting point is:++```json+{+ "locale": "ja",+ "name": "日本語",+ "direction": "ltr",+ "messages": {+ "app.studio": "スタジオ",+ "app.comments": "コメント",+ "app.language": "言語"+ }+}+```++Missing messages use English, so a partial translation is useful immediately.+Text is displayed as text, never interpreted as HTML. Preserve named variables+such as `{name}` and `{count}`; their order may change to suit the language.+Messages with `{count}` can be strings or plural forms:++```json+{ "one": "{count} item", "other": "{count} items" }+```++Use the language's `Intl.PluralRules` categories (`zero`, `one`, `two`, `few`,+`many`, `other`); `other` is required. Numbers and interface dates use the chosen+locale. Choose natural full sentences instead of assembling translated fragments.++Check and load your file:++```sh+hypit studio --check-locale ./ja.json+hypit studio --run ./render.svrun --locale-pack ./ja.json+```++The check lists missing translations and unknown IDs and reports malformed+messages or renamed variables. It does not open a Run or require a Runtime.+Relative file paths start at the command's working directory; prefix them with+`./` or `../`. Repeat `--locale-pack` to load multiple languages. Packs are read+at server startup; restart Studio after editing a pack. An explicitly loaded+pack with an existing locale replaces that locale's pack, with English fallback+for any omitted messages.++## Share a language pack++A local file is sufficient. For reuse, publish it through an ordinary package+under your own scope; there is no Hypit language registry or separate approval+step. Export the JSON file in the package's `package.json`, for example:++```json+{+ "name": "@your-scope/studio-ja",+ "version": "1.0.0",+ "files": ["ja.json"],+ "exports": { "./locale.json": "./ja.json" }+}+```++Install it using the project's package manager, then load it explicitly:++```sh+hypit studio --run ./render.svrun --locale-pack @your-scope/studio-ja/locale.json+```++Package exports resolve from the project, or `--package-root` when specified.+Studio reads the resolved JSON without importing package code. It neither scans+for language packs nor installs missing packages.++## Interface behavior and ownership++The globe menu to the left of **Studio / Comments** lists loaded languages by+their native names. The first visit follows the browser's language preferences;+subsequent visits retain the choice saved in that browser. Switching updates+marked labels in place, preserving the playhead, selection and comment draft.++Only Studio-owned interface text belongs in this catalog. Component names,+Companion-supplied labels, Source code, user comments and raw service diagnostics+retain their original text. Language packs do not change the Companion ABI,+Core, compilation, or rendering. A component remains the owner of its labels.++When adding Studio UI, give each message a stable ID in the English catalog and+use the helpers in `src/ui/i18n.ts` for text and attributes. Do not use English+wording as IDs, inspect DOM text to guess what needs translation, or put language+branches into components. Keep interpolation values separate from message text.diff --git a/packages/studio/README.md b/packages/studio/README.mdindex cf0ca441..d85019b0 100644--- a/packages/studio/README.md+++ b/packages/studio/README.md@@ -258,3 +258,16 @@ audibility regions and target-relative fades. Web Audio gain nodes schedule theon the same clock, including silence and amplification above unity. Visual video elements stay muted;the Film's selected AudioTracks own composition sound. Seeking is silent. This path is independent ofwhich component emitted a clip.++### Interface language++The globe menu to the left of **Studio / Comments** selects a language. English+and Simplified Chinese are included; additional JSON language packs can be loaded+with `--locale-pack`, from local files or installed package exports. The first+visit follows browser preferences, and later visits remember the user's choice.+Switching preserves the playhead, selection and comment draft.++[Localizing Studio](LOCALIZATION.md) explains the message catalog, plural forms,+translation checks and language-pack distribution. Only Studio-owned interface+text is translated; Companion labels, project content and raw diagnostics retain+their original text. The Companion ABI is unchanged.diff --git a/packages/studio/locales/en.json b/packages/studio/locales/en.jsonnew file mode 100644index 00000000..45059f03--- /dev/null+++ b/packages/studio/locales/en.json@@ -0,0 +1,197 @@+{+ "locale": "en",+ "name": "English",+ "direction": "ltr",+ "messages": {+ "app.comments": "Comments",+ "app.language": "Language",+ "app.studio": "Studio",+ "app.studio-view": "Studio view",+ "comments.all": "All",+ "comments.caught-up": "All caught up",+ "comments.delete-comment": "Delete comment",+ "comments.done": "Done",+ "comments.draw-soon": "Draw — coming later",+ "comments.edit-comment": "Edit comment",+ "comments.edit-comment-text": "Edit comment text",+ "comments.emoji-soon": "Emoji — coming later",+ "comments.empty": "A note starts here",+ "comments.empty-hint": "Pause on a frame and describe what you would like to change.",+ "comments.filter-comments": "Filter comments",+ "comments.filter-hint": "Switch filters to see the other comments.",+ "comments.go-to-this-frame": "Go to this frame",+ "comments.loading-comments": "Loading comments…",+ "comments.mark-complete": "Mark complete",+ "comments.no-completed-comments": "No completed comments",+ "comments.open": "Open",+ "comments.placeholder": "What would you like to change?",+ "comments.read-failed": "Could not read comments.",+ "comments.refresh-comments": "Refresh comments",+ "comments.reopen-comment": "Reopen comment",+ "comments.save-failed": "Could not save comment.",+ "comments.send-comment": "Send comment",+ "comments.send-shortcut": "Send comment (Enter)",+ "comments.use-current-frame": "Use current frame",+ "comments.write-a-comment": "Write a comment",+ "common.cancel": "Cancel",+ "common.cancelled": "Cancelled",+ "common.compile-failed": "Compile failed",+ "common.completed": "Completed",+ "common.copied": "Copied",+ "common.failed": "Failed",+ "common.invalid-value": "Invalid value",+ "common.needs-attention": "Needs attention",+ "common.queued": "Queued",+ "common.refresh": "Refresh",+ "common.running": "Running",+ "common.save": "Save",+ "common.save-failed": "Save failed",+ "common.saved": "Saved",+ "common.saving": "Saving",+ "common.waiting": "Waiting",+ "inspector.add-color": "Add color",+ "inspector.add-item": "Add item",+ "inspector.anchor.program-end": "Timeline end{detail}",+ "inspector.anchor.program-start": "Timeline start{detail}",+ "inspector.anchor.segment-end": "Segment end{detail}",+ "inspector.anchor.segment-start": "Segment start{detail}",+ "inspector.anchor.token-end": "Word end{detail}",+ "inspector.anchor.token-start": "Word start{detail}",+ "inspector.aspect-ratio": "Aspect ratio",+ "inspector.author": "Author",+ "inspector.build": "Build",+ "inspector.candidates": "Candidates",+ "inspector.canvas": "Canvas",+ "inspector.duration": "Duration",+ "inspector.empty": "No details for this selection",+ "inspector.end": "End",+ "inspector.end-anchor": "End semantic anchor",+ "inspector.frame-rate": "Frame rate",+ "inspector.frames": "Frames",+ "inspector.how": "How",+ "inspector.invalid-fields": "Complete the required fields with valid values to save.",+ "inspector.item-count": {+ "one": "{count} item",+ "other": "{count} items"+ },+ "inspector.moment": "Moment",+ "inspector.moment-anchor": "Moment semantic anchor",+ "inspector.move-down": "Move down",+ "inspector.move-up": "Move up",+ "inspector.project": "Project",+ "inspector.properties": "Properties",+ "inspector.remove-item": "Remove item",+ "inspector.resolution": "Resolution",+ "inspector.run": "Run",+ "inspector.semantic-anchors": "Semantic anchors",+ "inspector.sources": "Sources",+ "inspector.start": "Start",+ "inspector.start-anchor": "Start semantic anchor",+ "inspector.structured-value": "Structured value",+ "inspector.targets": "Targets",+ "inspector.timeline": "Timeline",+ "inspector.timing": "Timing",+ "inspector.tracks": "Tracks",+ "inspector.use-color": "Use {color}",+ "inspector.when": "When",+ "inspector.where": "Where",+ "library.all-media": "All media",+ "library.all-tasks": "All tasks",+ "library.artifacts": "Artifacts",+ "library.audio": "Audio",+ "library.clear-task-filter": "Clear task filter",+ "library.data": "Data",+ "library.display-name": "Display name",+ "library.enter-name": "Enter a name.",+ "library.finished": "Finished",+ "library.image": "Image",+ "library.images": "Images",+ "library.in-progress": "In progress",+ "library.loading-media": "Loading media…",+ "library.loading-more": "Loading more…",+ "library.loading-tasks": "Loading tasks…",+ "library.media-categories": "Media categories",+ "library.media-category": "Media category",+ "library.media-hint": "Images, videos and audio published as file Outputs appear here, including those from ongoing Builds.",+ "library.name-failed": "Could not save the name",+ "library.name-pending": "{name}\nNaming is available when this Build finishes",+ "library.no-files-in-this-category": "No files in this category",+ "library.no-media": "No media",+ "library.no-tasks-here": "No tasks here",+ "library.no-tasks-in-progress": "No tasks in progress",+ "library.preview-name": "Preview {name}",+ "library.preview-unavailable": "Preview unavailable",+ "library.referenced-source-files": "Referenced source files",+ "library.refresh-failed": "Refresh failed: {detail}",+ "library.refresh-failed-retained": "Refresh failed: {detail} · Previous view retained",+ "library.refresh-interrupted": "Refresh interrupted",+ "library.refresh-media": "Refresh media",+ "library.refresh-tasks": "Refresh tasks",+ "library.refreshing": "Refreshing…",+ "library.rename-hint": "{name}\nDouble-click or press F2 to rename",+ "library.return-to-task": "Return to task",+ "library.source": "Source",+ "library.studio-library": "Studio library",+ "library.task-categories": "Task categories",+ "library.task-return": "{name} · Return to task",+ "library.tasks": "Tasks",+ "library.unavailable": "Library unavailable",+ "library.updated": "Updated {time}",+ "library.video": "Video",+ "library.video-loading-preview": "Video · Loading preview",+ "library.videos": "Videos",+ "library.view-media": "View media",+ "library.view-task-media": "View task media",+ "player.audio-waveform": "Audio waveform",+ "player.back-5-seconds": "Back 5 seconds",+ "player.back-to-composition": "Back to composition",+ "player.composition-time": "Composition time",+ "player.elements-at-this-point": "Elements at this point",+ "player.forward-5-seconds": "Forward 5 seconds",+ "player.frame-loading": "Loading frame…",+ "player.frame-unavailable": "Frame unavailable",+ "player.hovered-frame": "Hovered frame",+ "player.media-failed": "This media could not be opened in the browser.",+ "player.media-time": "Media time",+ "player.mute": "Mute",+ "player.next-frame": "Next frame",+ "player.pause": "Pause",+ "player.play": "Play",+ "player.preview": "Preview",+ "player.previous-frame": "Previous frame",+ "player.unmute": "Unmute",+ "source.changed-outside-studio": "Changed outside Studio",+ "source.edit-source": "Edit source",+ "source.keep-lines-unwrapped": "Keep lines unwrapped",+ "source.read-source": "Read source",+ "source.save-failed-status": "Save failed ({status})",+ "source.saving-before-switch": "Saving before switch",+ "source.svml-source": "SVML source",+ "source.unsaved": "Unsaved",+ "source.wrap-lines": "Wrap lines",+ "tasks.copy-error": "Copy error",+ "tasks.copy-manually": "Select the text to copy",+ "tasks.no-runtime": "No Runtime is selected. Saved tasks are available under Finished.",+ "tasks.progress": "{completed}/{total} steps complete",+ "tasks.refresh-hint": "Refresh to read the latest task status.",+ "tasks.saved-only": "Saved project Results · no Runtime selected",+ "timeline.fit-timeline": "Fit timeline",+ "timeline.moment-name": "Moment {name}",+ "timeline.overlapping-timeline-objects": "Overlapping timeline objects",+ "timeline.resize-timeline-track-labels": "Resize timeline track labels",+ "timeline.resize-track-labels": "Resize track labels",+ "timeline.segment-name": "Segment {name}",+ "timeline.segments": "Segments",+ "timeline.select": "Select",+ "timeline.selection-name": "Selection {name}",+ "timeline.selections-and-moments": "Selections and Moments",+ "timeline.words": "Words",+ "timeline.zoom-in": "Zoom in",+ "timeline.zoom-out": "Zoom out",+ "inspector.color-picker": "{label} picker",+ "timeline.segment-count": {+ "one": "{count} segment",+ "other": "{count} segments"+ }+ }+}diff --git a/packages/studio/locales/zh-CN.json b/packages/studio/locales/zh-CN.jsonnew file mode 100644index 00000000..e361e766--- /dev/null+++ b/packages/studio/locales/zh-CN.json@@ -0,0 +1,191 @@+{+ "locale": "zh-CN",+ "name": "简体中文",+ "direction": "ltr",+ "messages": {+ "app.comments": "评论",+ "app.language": "语言",+ "app.studio": "工作台",+ "app.studio-view": "工作区视图",+ "comments.all": "全部",+ "comments.caught-up": "评论都已处理",+ "comments.delete-comment": "删除评论",+ "comments.done": "已完成",+ "comments.draw-soon": "批注 · 即将支持",+ "comments.edit-comment": "编辑评论",+ "comments.edit-comment-text": "编辑评论内容",+ "comments.emoji-soon": "表情 · 即将支持",+ "comments.empty": "留下第一条评论",+ "comments.empty-hint": "暂停在想调整的画面,说说你的想法。",+ "comments.filter-comments": "筛选评论",+ "comments.filter-hint": "切换筛选,查看其他评论。",+ "comments.go-to-this-frame": "跳转到这一帧",+ "comments.loading-comments": "加载评论中…",+ "comments.mark-complete": "标为已完成",+ "comments.no-completed-comments": "暂无已完成评论",+ "comments.open": "待处理",+ "comments.placeholder": "想调整哪里?",+ "comments.read-failed": "无法读取评论。",+ "comments.refresh-comments": "刷新评论",+ "comments.reopen-comment": "标为待处理",+ "comments.save-failed": "无法保存评论。",+ "comments.send-comment": "发送评论",+ "comments.send-shortcut": "发送评论(Enter)",+ "comments.use-current-frame": "使用当前帧",+ "comments.write-a-comment": "写评论",+ "common.cancel": "取消",+ "common.cancelled": "已取消",+ "common.compile-failed": "编译失败",+ "common.completed": "已完成",+ "common.copied": "已复制",+ "common.failed": "失败",+ "common.invalid-value": "无效的值",+ "common.needs-attention": "需要处理",+ "common.queued": "排队中",+ "common.refresh": "刷新",+ "common.running": "运行中",+ "common.save": "保存",+ "common.save-failed": "保存失败",+ "common.saved": "已保存",+ "common.saving": "保存中",+ "common.waiting": "等待中",+ "inspector.add-color": "添加颜色",+ "inspector.add-item": "添加条目",+ "inspector.anchor.program-end": "时间线终点{detail}",+ "inspector.anchor.program-start": "时间线起点{detail}",+ "inspector.anchor.segment-end": "段尾{detail}",+ "inspector.anchor.segment-start": "段头{detail}",+ "inspector.anchor.token-end": "词尾{detail}",+ "inspector.anchor.token-start": "词头{detail}",+ "inspector.aspect-ratio": "画幅比例",+ "inspector.author": "源文件",+ "inspector.build": "构建",+ "inspector.candidates": "候选实现",+ "inspector.canvas": "画布",+ "inspector.duration": "时长",+ "inspector.empty": "当前选中项没有详细信息",+ "inspector.end": "终点",+ "inspector.end-anchor": "终点语义锚点",+ "inspector.frame-rate": "帧率",+ "inspector.frames": "帧数",+ "inspector.how": "样式",+ "inspector.invalid-fields": "请正确填写必填项后保存。",+ "inspector.item-count": "{count} 项",+ "inspector.moment": "时刻",+ "inspector.moment-anchor": "时刻语义锚点",+ "inspector.move-down": "下移",+ "inspector.move-up": "上移",+ "inspector.project": "项目",+ "inspector.properties": "属性",+ "inspector.remove-item": "移除条目",+ "inspector.resolution": "分辨率",+ "inspector.run": "运行方案",+ "inspector.semantic-anchors": "语义锚点",+ "inspector.sources": "引用文件",+ "inspector.start": "起点",+ "inspector.start-anchor": "起点语义锚点",+ "inspector.structured-value": "结构化值",+ "inspector.targets": "目标产物",+ "inspector.timeline": "时间线",+ "inspector.timing": "时间",+ "inspector.tracks": "轨道",+ "inspector.use-color": "使用 {color}",+ "inspector.when": "时间",+ "inspector.where": "位置",+ "library.all-media": "全部素材",+ "library.all-tasks": "全部任务",+ "library.artifacts": "产物",+ "library.audio": "音频",+ "library.clear-task-filter": "清除任务筛选",+ "library.data": "数据",+ "library.display-name": "显示名称",+ "library.enter-name": "请输入名称。",+ "library.finished": "已结束",+ "library.image": "图片",+ "library.images": "图片",+ "library.in-progress": "进行中",+ "library.loading-media": "加载素材中…",+ "library.loading-more": "加载更多…",+ "library.loading-tasks": "加载任务中…",+ "library.media-categories": "素材分类",+ "library.media-category": "素材分类",+ "library.media-hint": "这里展示已产出的图片、视频和音频,也包括正在构建的任务产物。",+ "library.name-failed": "无法保存名称",+ "library.name-pending": "{name}\n构建完成后可以重命名",+ "library.no-files-in-this-category": "此分类暂无素材",+ "library.no-media": "暂无素材",+ "library.no-tasks-here": "暂无任务",+ "library.no-tasks-in-progress": "没有进行中的任务",+ "library.preview-name": "预览 {name}",+ "library.preview-unavailable": "暂时无法预览",+ "library.referenced-source-files": "引用的源文件",+ "library.refresh-failed": "刷新失败:{detail}",+ "library.refresh-failed-retained": "刷新失败:{detail} · 已保留上次视图",+ "library.refresh-interrupted": "刷新已中断",+ "library.refresh-media": "刷新素材",+ "library.refresh-tasks": "刷新任务",+ "library.refreshing": "刷新中…",+ "library.rename-hint": "{name}\n双击或按 F2 重命名",+ "library.return-to-task": "返回任务",+ "library.source": "源文件",+ "library.studio-library": "项目资源",+ "library.task-categories": "任务分类",+ "library.task-return": "{name} · 返回任务",+ "library.tasks": "任务",+ "library.unavailable": "资源暂时不可用",+ "library.updated": "更新于 {time}",+ "library.video": "视频",+ "library.video-loading-preview": "视频 · 加载预览中",+ "library.videos": "视频",+ "library.view-media": "查看产物",+ "library.view-task-media": "查看任务产物",+ "player.audio-waveform": "音频波形",+ "player.back-5-seconds": "后退 5 秒",+ "player.back-to-composition": "返回作品",+ "player.composition-time": "作品播放进度",+ "player.elements-at-this-point": "此处的元素",+ "player.forward-5-seconds": "前进 5 秒",+ "player.frame-loading": "加载画面中…",+ "player.frame-unavailable": "画面暂时不可用",+ "player.hovered-frame": "悬停画面",+ "player.media-failed": "浏览器无法打开此素材。",+ "player.media-time": "素材播放进度",+ "player.mute": "静音",+ "player.next-frame": "下一帧",+ "player.pause": "暂停",+ "player.play": "播放",+ "player.preview": "预览",+ "player.previous-frame": "上一帧",+ "player.unmute": "取消静音",+ "source.changed-outside-studio": "文件已在外部更改",+ "source.edit-source": "编辑源文件",+ "source.keep-lines-unwrapped": "不自动换行",+ "source.read-source": "查看源文件",+ "source.save-failed-status": "保存失败({status})",+ "source.saving-before-switch": "切换前保存中",+ "source.svml-source": "SVML 源文件",+ "source.unsaved": "未保存",+ "source.wrap-lines": "自动换行",+ "tasks.copy-error": "复制错误信息",+ "tasks.copy-manually": "请选择文字复制",+ "tasks.no-runtime": "尚未选择运行环境,可在「已结束」中查看保存的任务。",+ "tasks.progress": "已完成 {completed}/{total} 步",+ "tasks.refresh-hint": "点击刷新,查看最新任务状态。",+ "tasks.saved-only": "项目中保存的结果 · 未选择运行环境",+ "timeline.fit-timeline": "适配时间线",+ "timeline.moment-name": "时刻 {name}",+ "timeline.overlapping-timeline-objects": "重叠的时间线对象",+ "timeline.resize-timeline-track-labels": "调整轨道名称区宽度",+ "timeline.resize-track-labels": "调整轨道名称区宽度",+ "timeline.segment-name": "片段 {name}",+ "timeline.segments": "片段",+ "timeline.select": "选择",+ "timeline.selection-name": "区间 {name}",+ "timeline.selections-and-moments": "区间与时刻",+ "timeline.words": "词语",+ "timeline.zoom-in": "放大",+ "timeline.zoom-out": "缩小",+ "inspector.color-picker": "{label}取色器",+ "timeline.segment-count": "{count} 个片段"+ }+}diff --git a/packages/studio/src/localization-node.ts b/packages/studio/src/localization-node.tsnew file mode 100644index 00000000..356a0297--- /dev/null+++ b/packages/studio/src/localization-node.ts@@ -0,0 +1,46 @@+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { isAbsolute, resolve } from "node:path";+import type { Plugin } from "vite";+import { builtinLanguages, languageCoverage, readLanguagePack } from "./localization.js";+import type { LanguagePack } from "./localization.js";++export async function loadLanguagePack(specifier: string, cwd: string, packageRoot: string): Promise<LanguagePack> {+ const path = isAbsolute(specifier) || specifier.startsWith(".")+ ? resolve(cwd, specifier)+ : createRequire(resolve(packageRoot, "package.json")).resolve(specifier);+ try { return readLanguagePack(JSON.parse(await readFile(path, "utf8"))); }+ catch (error) { throw new Error(`Language pack ${specifier}: ${error instanceof Error ? error.message : String(error)}`); }+}++export function describeLanguagePack(pack: LanguagePack): string {+ const { missing, unknown } = languageCoverage(pack);+ return [`${pack.name} (${pack.locale})`,+ `Missing translations (${missing.length}; English is used): ${missing.join(", ") || "none"}`,+ `Unknown message IDs (${unknown.length}): ${unknown.join(", ") || "none"}`,+ ].join("\n");+}++export async function studioLanguages(specifiers: readonly string[], cwd: string, packageRoot: string): Promise<readonly LanguagePack[]> {+ const packs = new Map(builtinLanguages.map(pack => [pack.locale, pack]));+ for (const specifier of specifiers) {+ const pack = await loadLanguagePack(specifier, cwd, packageRoot);+ packs.set(pack.locale, pack);+ }+ return [...packs.values()];+}++export function studioLocalizationPlugin(packs: readonly LanguagePack[]): Plugin {+ return {+ name: "hypit-studio-localization",+ configureServer(server) {+ server.middlewares.use((request, response, next) => {+ if (new URL(request.url ?? "/", "http://localhost").pathname !== "/__studio/locales") return next();+ if (request.method !== "GET") { response.statusCode = 405; response.end(); return; }+ response.setHeader("content-type", "application/json; charset=utf-8");+ response.setHeader("cache-control", "no-store");+ response.end(JSON.stringify(packs));+ });+ },+ };+}diff --git a/packages/studio/src/localization.ts b/packages/studio/src/localization.tsnew file mode 100644index 00000000..8991a0fb--- /dev/null+++ b/packages/studio/src/localization.ts@@ -0,0 +1,85 @@+import english from "../locales/en.json" with { type: "json" };+import chinese from "../locales/zh-CN.json" with { type: "json" };++export type Message = keyof typeof english.messages;+export type MessageValue = string | ({ readonly other: string } & Partial<Record<Intl.LDMLPluralRule, string>>);+export type LanguagePack = {+ readonly locale: string;+ /** Native language name, displayed without translation. */+ readonly name: string;+ readonly direction: "ltr" | "rtl";+ readonly messages: Readonly<Record<string, MessageValue>>;+};+export const defaultLanguage: LanguagePack = english as LanguagePack;+export const builtinLanguages: readonly LanguagePack[] = [defaultLanguage, chinese as LanguagePack];+export type MessageValues = Readonly<Record<string, string | number>>;+const plurals = new Set(["zero", "one", "two", "few", "many", "other"]);+const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);+const variants = (message: MessageValue): readonly string[] => typeof message === "string" ? [message] : Object.values(message);+const variables = (text: string): string[] => [...new Set([...text.matchAll(/\{(\w+)\}/gu)].map(match => match[1]!))].sort();++/** Read data, never executable translation code. Partial translations remain useful. */+export function readLanguagePack(value: unknown): LanguagePack {+ if (!record(value) || typeof value.locale !== "string" || typeof value.name !== "string" || !value.name.trim()+ || (value.direction !== "ltr" && value.direction !== "rtl") || !record(value.messages)) {+ throw new Error("A Studio language pack needs locale, name, direction (ltr/rtl) and messages.");+ }+ const locale = Intl.getCanonicalLocales(value.locale)[0];+ if (!locale) throw new Error("A Studio language pack needs a BCP 47 locale.");+ const messages: Record<string, MessageValue> = {};+ for (const [id, message] of Object.entries(value.messages)) {+ if (typeof message !== "string" && (!record(message) || typeof message.other !== "string"+ || Object.entries(message).some(([form, text]) => !plurals.has(form) || typeof text !== "string"))) {+ throw new Error(`${id}: expected text or plural forms with an 'other' form.`);+ }+ const translated = message as MessageValue;+ const original = Object.hasOwn(defaultLanguage.messages, id) ? defaultLanguage.messages[id] : undefined;+ if (original !== undefined) {+ const expected = variables(variants(original)[0]!).join(",");+ for (const text of variants(translated)) {+ if (variables(text).join(",") !== expected) throw new Error(`${id}: preserve the named variables {${expected.split(",").join("}, {")}}.`);+ }+ if (typeof translated !== "string" && !variables(variants(original)[0]!).includes("count")) {+ throw new Error(`${id}: plural forms require a count variable.`);+ }+ }+ messages[id] = translated;+ }+ return { locale, name: value.name, direction: value.direction, messages };+}++export function languageCoverage(pack: LanguagePack): { missing: string[]; unknown: string[] } {+ return {+ missing: Object.keys(defaultLanguage.messages).filter(id => !Object.hasOwn(pack.messages, id)),+ unknown: Object.keys(pack.messages).filter(id => !Object.hasOwn(defaultLanguage.messages, id)),+ };+}++export function chooseLanguage(packs: readonly LanguagePack[], preferences: readonly string[]): LanguagePack {+ for (const preference of preferences) {+ let locale: string;+ try { locale = Intl.getCanonicalLocales(preference)[0]!; } catch { continue; }+ const exact = packs.find(pack => pack.locale === locale);+ if (exact) return exact;+ // Match regional/script variants without a list of special language cases.+ const requested = new Intl.Locale(locale).maximize();+ const related = packs.find(pack => {+ const candidate = new Intl.Locale(pack.locale).maximize();+ return candidate.language === requested.language && candidate.script === requested.script;+ });+ if (related) return related;+ }+ return packs.find(pack => pack.locale === defaultLanguage.locale) ?? defaultLanguage;+}++export function formatMessage(pack: LanguagePack, id: Message, values: MessageValues = {}): string {+ const translated = pack.messages[id];+ const message = translated ?? defaultLanguage.messages[id]!;+ const locale = translated === undefined ? defaultLanguage.locale : pack.locale;+ const template = typeof message === "string" ? message+ : message[new Intl.PluralRules(locale).select(Number(values.count))] ?? message.other;+ return template.replace(/\{(\w+)\}/gu, (match, key: string) => {+ const value = values[key];+ return typeof value === "number" ? new Intl.NumberFormat(pack.locale).format(value) : value ?? match;+ });+}diff --git a/packages/studio/src/style.css b/packages/studio/src/style.cssindex e8f8c27f..1d0ba25f 100644--- a/packages/studio/src/style.css+++ b/packages/studio/src/style.css@@ -142,7 +142,7 @@ button:focus-visible, textarea:focus-visible {white-space: nowrap;}.topbar-right { justify-self: end; display: flex; align-items: center; min-width: 0; }-.view-tabs { display: flex; align-items: center; gap: 2px; margin-left: 16px; padding: 2px; border-radius: 5px; background: var(--subtab-surface); }+.view-tabs { display: flex; flex: 0 0 auto; white-space: nowrap; align-items: center; gap: 2px; margin-left: 16px; padding: 2px; border-radius: 5px; background: var(--subtab-surface); }.view-tabs button {display: flex; align-items: center; gap: 7px; height: 24px; padding: 0 10px;border: 0; border-radius: 4px; color: var(--text-3); background: transparent;@@ -150,6 +150,18 @@ button:focus-visible, textarea:focus-visible {.view-tabs button[aria-selected="true"] { color: var(--subtab-active-text); background: var(--subtab-active-surface); }.view-tabs button:focus-visible { outline: 1px solid #8a8f99; outline-offset: -1px; }.view-tabs .icon { width: 14px; height: 14px; }+.parameter-select.language-select { width: auto; flex: 0 0 auto; margin-left: 10px; }+.language-select .language-toggle {+ display: grid; place-items: center; grid-template-columns: 1fr;+ width: 28px; height: 28px; padding: 0;+ color: var(--subtab-active-text); background: var(--subtab-surface);+ border-color: var(--line);+}+.language-toggle .icon { width: 16px; height: 16px; }+.language-select .parameter-select-menu { width: max-content; min-width: 150px; max-width: 240px; }+.language-select .parameter-select-option { font-family: var(--font-ui); text-align: start; }+.topbar { position: relative; z-index: 40; }+.meta {color: var(--text-3);font: 500 11px/1 var(--font-ui);@@ -1560,8 +1572,8 @@ button:focus-visible, textarea:focus-visible {.failure:empty { display: none; }@media (max-width: 920px) {- .meta, .topbar-right { display: none; }- .topbar { grid-template-columns: 1fr minmax(120px, 1fr); }+ .meta, .topbar-right .status { display: none; }+ .topbar { grid-template-columns: auto minmax(0, 1fr) auto; }.upper-shell { grid-template-columns: minmax(320px, var(--source-width)) 8px minmax(300px, 1fr); }.workspace-handle, .workspace-panel { display: none; }}diff --git a/packages/studio/src/ui/artifact-name.ts b/packages/studio/src/ui/artifact-name.tsindex 5d12ece7..9b91dbc0 100644--- a/packages/studio/src/ui/artifact-name.ts+++ b/packages/studio/src/ui/artifact-name.ts@@ -1,3 +1,5 @@+import { uiAttr, uiText, userText } from "./i18n.js";+/** Two-line label with an expanding editor; the caller owns persistence. */export function createArtifactName(options: {readonly name: string;@@ -15,7 +17,7 @@ export function createArtifactName(options: {text.className = "artifact-name-text";text.textContent = name;label.append(text);- label.title = options.editable ? `${name}\nDouble-click or press F2 to rename` : `${name}\nNaming is available when this Build finishes`;+ uiAttr(label, "title", options.editable ? "library.rename-hint" : "library.name-pending", { name });element.append(label);label.addEventListener("click", (event) => { event.stopPropagation(); options.select(); });let editing = false;@@ -30,7 +32,7 @@ export function createArtifactName(options: {field.className = "artifact-name-editor";field.value = name;field.rows = 1;- field.setAttribute("aria-label", "Display name");+ uiAttr(field, "aria-label", "library.display-name");const error = document.createElement("span");error.className = "artifact-name-error";error.setAttribute("role", "status");@@ -53,17 +55,17 @@ export function createArtifactName(options: {if (!editing || saving) return;const value = field.value.trim();if (value === name) { close(); return; }- if (value.length === 0) { error.textContent = "Enter a name."; return; }+ if (value.length === 0) { uiText(error, "library.enter-name"); return; }saving = true;field.readOnly = true;- error.textContent = "Saving…";+ uiText(error, "common.saving");try {name = await options.save(value);text.textContent = name;- label.title = `${name}\nDouble-click or press F2 to rename`;+ uiAttr(label, "title", "library.rename-hint", { name });close();} catch (cause) {- error.textContent = cause instanceof Error ? cause.message : String(cause);+ userText(error, cause instanceof Error ? cause.message : String(cause));} finally {saving = false;field.readOnly = false;diff --git a/packages/studio/src/ui/artifact-preview.ts b/packages/studio/src/ui/artifact-preview.tsindex 4fcff89e..e137b324 100644--- a/packages/studio/src/ui/artifact-preview.ts+++ b/packages/studio/src/ui/artifact-preview.ts@@ -1,3 +1,4 @@+import { uiAttr, uiText, userText } from "./i18n.js";import type { StudioArtifactView } from "../shared.js";import { audioPreview } from "./material-preview.js";@@ -35,7 +36,7 @@ export function createArtifactPreview(changed: () => void) {error.setAttribute("role", "status");const failed = () => {if (generation !== current) return;- error.textContent = "This media could not be opened in the browser.";+ uiText(error, "player.media-failed");error.hidden = false;changed();};@@ -61,14 +62,14 @@ export function createArtifactPreview(changed: () => void) {if (audio) {const wave = document.createElement("div");wave.className = "stage-audio-wave";- wave.textContent = "Audio";+ uiText(wave, "library.audio");element.append(wave);void audioPreview(url).then((waveform) => {if (generation !== current || waveform === undefined) return;const image = document.createElement("img");image.src = waveform;- image.alt = "Audio waveform";- wave.replaceChildren(image);+ uiAttr(image, "alt", "player.audio-waveform");+ userText(wave, ""); wave.replaceChildren(image);});}}diff --git a/packages/studio/src/ui/code.ts b/packages/studio/src/ui/code.tsindex f932e069..cf0af920 100644--- a/packages/studio/src/ui/code.ts+++ b/packages/studio/src/ui/code.ts@@ -1,3 +1,4 @@+import { t, userText, uiAttribute, uiText, uiAttr } from "./i18n.js";import type { Range, StudioSnapshot, StudioSourceView } from "../shared.js";import { icon, setIcon } from "./icons.js";import { intentTones } from "./markers.js";@@ -77,10 +78,10 @@ export function createCodePane(): CodePane {<strong class="code-location" data-path></strong><div class="code-actions"><span class="code-save-state" data-save-state></span>- <button type="button" class="icon-button code-wrap" data-wrap aria-label="Wrap lines" aria-pressed="false" title="Wrap lines">+ <button type="button" class="icon-button code-wrap" data-wrap ${uiAttribute("aria-label", "source.wrap-lines")} aria-pressed="false" ${uiAttribute("title", "source.wrap-lines")}>${icon("wrap")}</button>- <button type="button" class="icon-button code-mode" data-mode aria-label="Edit source" title="Edit source">+ <button type="button" class="icon-button code-mode" data-mode ${uiAttribute("aria-label", "source.edit-source")} ${uiAttribute("title", "source.edit-source")}><span data-mode-icon>${icon("edit")}</span></button></div>`;@@ -88,7 +89,7 @@ export function createCodePane(): CodePane {element.className = "code";element.innerHTML = `<div class="code-scroll"><svg class="range-canvas" aria-hidden="true"></svg></div>- <textarea class="code-editor" data-editor spellcheck="false" aria-label="SVML source"></textarea>`;+ <textarea class="code-editor" data-editor spellcheck="false" ${uiAttribute("aria-label", "source.svml-source")}></textarea>`;const path = toolbar.querySelector<HTMLElement>("[data-path]")!;const scroll = element.querySelector<HTMLElement>(".code-scroll")!;const canvas = element.querySelector<SVGSVGElement>(".range-canvas")!;@@ -116,8 +117,8 @@ export function createCodePane(): CodePane {wrapped = value;element.classList.toggle("is-wrapped", wrapped);wrap.setAttribute("aria-pressed", String(wrapped));- wrap.setAttribute("aria-label", wrapped ? "Keep lines unwrapped" : "Wrap lines");- wrap.title = wrapped ? "Keep lines unwrapped" : "Wrap lines";+ uiAttr(wrap, "aria-label", wrapped ? "source.keep-lines-unwrapped" : "source.wrap-lines");+ uiAttr(wrap, "title", wrapped ? "source.keep-lines-unwrapped" : "source.wrap-lines");window.requestAnimationFrame(draw);};@@ -125,8 +126,8 @@ export function createCodePane(): CodePane {editing = value;element.classList.toggle("is-editing", editing);setIcon(modeIcon, editing ? "eye" : "edit");- mode.setAttribute("aria-label", editing ? "Read source" : "Edit source");- mode.title = editing ? "Read source" : "Edit source";+ uiAttr(mode, "aria-label", editing ? "source.read-source" : "source.edit-source");+ uiAttr(mode, "title", editing ? "source.read-source" : "source.edit-source");if (editing) {editor.value = sourceText;editingRevision = snapshotRevision;@@ -143,7 +144,7 @@ export function createCodePane(): CodePane {saveInFlight = true;let accepted = false;let acceptedRevision = savingRevision;- saveState.textContent = "Saving";+ uiText(saveState, "common.saving");saveState.className = "code-save-state saving";try {const response = await fetch("/__studio/source", {@@ -153,7 +154,7 @@ export function createCodePane(): CodePane {});if (!response.ok) {const reason = await response.text();- throw new Error(reason || `Save failed (${response.status})`);+ throw new Error(reason || t("source.save-failed-status", { status: response.status }));}const result = await response.json() as { readonly revision?: unknown };if (typeof result.revision === "number") acceptedRevision = result.revision;@@ -163,15 +164,15 @@ export function createCodePane(): CodePane {sourceText = savingText;dirty = false;}- saveState.textContent = "Saved";+ uiText(saveState, "common.saved");saveState.className = "code-save-state saved";window.setTimeout(() => {- if (!dirty) saveState.textContent = "";+ if (!dirty) userText(saveState, "");}, 1200);} catch (error) {- saveState.textContent = error instanceof Error && error.message.includes("changed")- ? "Changed outside Studio"- : "Save failed";+ uiText(saveState, error instanceof Error && error.message.includes("changed")+ ? "source.changed-outside-studio"+ : "common.save-failed");saveState.className = "code-save-state error";} finally {saveInFlight = false;@@ -189,7 +190,7 @@ export function createCodePane(): CodePane {wrap.addEventListener("click", () => setWrapped(!wrapped));editor.addEventListener("input", () => {dirty = true;- saveState.textContent = "Unsaved";+ uiText(saveState, "source.unsaved");saveState.className = "code-save-state dirty";if (saveTimer !== undefined) window.clearTimeout(saveTimer);saveTimer = window.setTimeout(() => void save(), 480);@@ -308,7 +309,7 @@ export function createCodePane(): CodePane {imports: [],};if (activeSource !== undefined && activeSource.path !== sourceFile.path && dirty) {- saveState.textContent = "Saving before switch";+ uiText(saveState, "source.saving-before-switch");saveState.className = "code-save-state saving";void save();return false;diff --git a/packages/studio/src/ui/comments.ts b/packages/studio/src/ui/comments.tsindex c230e4da..74fbb828 100644--- a/packages/studio/src/ui/comments.ts+++ b/packages/studio/src/ui/comments.ts@@ -1,3 +1,4 @@+import { t, uiLabel, uiAttribute, uiText, uiAttr, type Message } from "./i18n.js";import { feedbackClock } from "../feedback.js";import type { FeedbackComment, FeedbackMutation, FeedbackView } from "../feedback.js";import { icon } from "./icons.js";@@ -11,28 +12,28 @@ export function createComments(store: Store, stage: Stage) {element.className = "comments-panel";element.innerHTML = `<div class="pane-heading comments-heading">- <div class="pane-title">${icon("comments")}<h2>Comments</h2><span data-count></span></div>- <button type="button" class="comments-icon" data-refresh aria-label="Refresh comments" title="Refresh comments">${icon("refresh")}</button>+ <div class="pane-title">${icon("comments")}<h2>${uiLabel("app.comments")}</h2><span data-count></span></div>+ <button type="button" class="comments-icon" data-refresh ${uiAttribute("aria-label", "comments.refresh-comments")} ${uiAttribute("title", "comments.refresh-comments")}>${icon("refresh")}</button></div>- <div class="comments-filters" role="group" aria-label="Filter comments">- <button type="button" data-filter="all" aria-pressed="true">All</button>- <button type="button" data-filter="open" aria-pressed="false">Open</button>- <button type="button" data-filter="done" aria-pressed="false">Done</button>+ <div class="comments-filters" role="group" ${uiAttribute("aria-label", "comments.filter-comments")}>+ <button type="button" data-filter="all" aria-pressed="true">${uiLabel("comments.all")}</button>+ <button type="button" data-filter="open" aria-pressed="false">${uiLabel("comments.open")}</button>+ <button type="button" data-filter="done" aria-pressed="false">${uiLabel("comments.done")}</button></div><div class="comments-error" role="status" aria-live="polite" hidden></div>- <div class="comments-list" aria-label="Comments"></div>+ <div class="comments-list" ${uiAttribute("aria-label", "app.comments")}></div><form class="comment-composer"><div class="comment-anchor">- <button type="button" class="comment-time" data-current-time title="Use current frame" aria-label="Use current frame">${icon("when")}<span>00:00.00</span></button>+ <button type="button" class="comment-time" data-current-time ${uiAttribute("title", "comments.use-current-frame")} ${uiAttribute("aria-label", "comments.use-current-frame")}>${icon("when")}<span>00:00.00</span></button></div><div class="comment-input">- <textarea rows="3" aria-label="Write a comment" placeholder="What would you like to change?" spellcheck="true" enterkeyhint="send"></textarea>+ <textarea rows="3" ${uiAttribute("aria-label", "comments.write-a-comment")} ${uiAttribute("placeholder", "comments.placeholder")} spellcheck="true" enterkeyhint="send"></textarea><div class="comment-input-actions"><div class="comment-tools">- <button type="button" class="comments-icon" aria-label="Emoji — coming later" title="Emoji — coming later" disabled>${icon("smile")}</button>- <button type="button" class="comments-icon" aria-label="Draw — coming later" title="Draw — coming later" disabled>${icon("edit")}</button>+ <button type="button" class="comments-icon" ${uiAttribute("aria-label", "comments.emoji-soon")} ${uiAttribute("title", "comments.emoji-soon")} disabled>${icon("smile")}</button>+ <button type="button" class="comments-icon" ${uiAttribute("aria-label", "comments.draw-soon")} ${uiAttribute("title", "comments.draw-soon")} disabled>${icon("edit")}</button></div>- <button class="comment-submit" type="submit" aria-label="Send comment" title="Send comment (Enter)" disabled>${icon("send")}</button>+ <button class="comment-submit" type="submit" ${uiAttribute("aria-label", "comments.send-comment")} ${uiAttribute("title", "comments.send-shortcut")} disabled>${icon("send")}</button></div></div></form>`;@@ -68,10 +69,10 @@ export function createComments(store: Store, stage: Stage) {submit.disabled = busy || view === undefined || anchor === undefined || input.value.trim().length === 0;};const capture = (): void => { stage.pause(); anchor = currentAnchor(); renderAnchor(); };- const button = (name: string, label: string, action: () => void): HTMLButtonElement => {+ const button = (name: string, label: Message, action: () => void): HTMLButtonElement => {const node = document.createElement("button");node.type = "button"; node.className = "comments-icon";- node.innerHTML = icon(name); node.title = label; node.setAttribute("aria-label", label);+ node.innerHTML = icon(name); uiAttr(node, "title", label); uiAttr(node, "aria-label", label);node.disabled = busy;node.addEventListener("click", (event) => { event.stopPropagation(); action(); });return node;@@ -101,8 +102,8 @@ export function createComments(store: Store, stage: Stage) {const empty = document.createElement("div");empty.className = "comments-empty";empty.innerHTML = `${icon(filter === "done" ? "check" : "comments")}<strong></strong><p></p>`;- empty.querySelector("strong")!.textContent = view === undefined ? "Loading comments…" : filter === "done" ? "No completed comments" : filter === "open" ? "All caught up" : "A note starts here";- empty.querySelector("p")!.textContent = filter === "all" ? "Pause on a frame and describe what you would like to change." : "Switch filters to see the other comments.";+ uiText(empty.querySelector("strong")!, view === undefined ? "comments.loading-comments" : filter === "done" ? "comments.no-completed-comments" : filter === "open" ? "comments.caught-up" : "comments.empty");+ uiText(empty.querySelector("p")!, filter === "all" ? "comments.empty-hint" : "comments.filter-hint");list.append(empty);}for (const { comment, number } of comments) {@@ -114,31 +115,31 @@ export function createComments(store: Store, stage: Stage) {const label = document.createElement("span"); label.className = "comment-number"; label.textContent = `#${number}`;const time = document.createElement("span"); time.className = "comment-time"; time.textContent = feedbackClock(comment.at);location.append(time);- location.title = "Go to this frame"; location.addEventListener("click", () => locate(comment));+ uiAttr(location, "title", "comments.go-to-this-frame"); location.addEventListener("click", () => locate(comment));row.addEventListener("click", (event) => {if ((event.target as Element).closest("button, form") !== null || window.getSelection()?.isCollapsed === false) return;locate(comment);});const actions = document.createElement("div"); actions.className = "comment-actions";- const resolve = button("check", comment.resolved ? "Reopen comment" : "Mark complete", () => {+ const resolve = button("check", comment.resolved ? "comments.reopen-comment" : "comments.mark-complete", () => {void mutate({ type: "replace", before: comment, comment: { ...comment, resolved: !comment.resolved } });});resolve.classList.toggle("is-done", comment.resolved === true);resolve.setAttribute("aria-pressed", String(comment.resolved === true));- actions.append(label, resolve, button("edit", "Edit comment", () => {+ actions.append(label, resolve, button("edit", "comments.edit-comment", () => {editing = { id: comment.id, before: comment, text: comment.text }; selected = comment.id; render();list.querySelector<HTMLTextAreaElement>(".comment-edit textarea")?.focus();- }), button("trash", "Delete comment", () => { void mutate({ type: "delete", before: comment }); }));+ }), button("trash", "comments.delete-comment", () => { void mutate({ type: "delete", before: comment }); }));head.append(location, actions); row.append(head);if (editing?.id === comment.id) {const edit = document.createElement("form"); edit.className = "comment-edit";const text = document.createElement("textarea"); text.rows = 3; text.value = editing.text;- text.setAttribute("aria-label", "Edit comment text");+ uiAttr(text, "aria-label", "comments.edit-comment-text");text.addEventListener("input", () => { if (editing !== undefined) editing.text = text.value; });const controls = document.createElement("div"); controls.className = "comment-edit-actions";- const cancel = document.createElement("button"); cancel.type = "button"; cancel.textContent = "Cancel";+ const cancel = document.createElement("button"); cancel.type = "button"; uiText(cancel, "common.cancel");cancel.addEventListener("click", () => { editing = undefined; render(); });- const save = document.createElement("button"); save.type = "submit"; save.textContent = "Save"; save.disabled = busy;+ const save = document.createElement("button"); save.type = "submit"; uiText(save, "common.save"); save.disabled = busy;controls.append(cancel, save); edit.append(text, controls);edit.addEventListener("submit", (event) => {event.preventDefault();@@ -161,7 +162,7 @@ export function createComments(store: Store, stage: Stage) {try {const response = await fetch("/__studio/feedback");const data = await response.json() as FeedbackView & { error?: string };- if (!response.ok) throw new Error(data.error ?? "Could not read comments.");+ if (!response.ok) throw new Error(data.error ?? t("comments.read-failed"));if (request !== fetchId) return;if (JSON.stringify(view) !== JSON.stringify(data)) { view = data; render(); }showError(); renderAnchor();@@ -173,7 +174,7 @@ export function createComments(store: Store, stage: Stage) {try {const response = await fetch("/__studio/feedback", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(mutation) });const data = await response.json() as FeedbackView & { error?: string };- if (!response.ok) throw new Error(data.error ?? "Could not save comment.");+ if (!response.ok) throw new Error(data.error ?? t("comments.save-failed"));++fetchId; view = data; busy = false; saved?.();if (mutation.type === "delete" && selected === mutation.before.id) selected = undefined;if (mutation.type === "delete" && editing?.id === mutation.before.id) editing = undefined;diff --git a/packages/studio/src/ui/dropdown.ts b/packages/studio/src/ui/dropdown.tsnew file mode 100644index 00000000..d999fa01--- /dev/null+++ b/packages/studio/src/ui/dropdown.ts@@ -0,0 +1,68 @@+/** Shared listbox interaction for Studio controls. Callers own the options and values. */+export function bindDropdown(control: HTMLElement, trigger: HTMLButtonElement, menu: HTMLElement, options: readonly HTMLButtonElement[]) {+ const close = (restoreFocus = false): void => {+ control.classList.remove("open", "open-up");+ trigger.setAttribute("aria-expanded", "false");+ menu.hidden = true;+ if (restoreFocus) trigger.focus();+ };+ const open = (focus: "selected" | "first" | "last" = "selected"): void => {+ control.classList.add("open");+ trigger.setAttribute("aria-expanded", "true");+ menu.hidden = false;+ control.classList.remove("open-up");+ const scroll = control.closest<HTMLElement>(".workspace-scroll");+ if (scroll !== null) {+ const menuBox = menu.getBoundingClientRect();+ const scrollBox = scroll.getBoundingClientRect();+ if (menuBox.bottom > scrollBox.bottom && trigger.getBoundingClientRect().top - menuBox.height >= scrollBox.top) {+ control.classList.add("open-up");+ }+ }+ const target = focus === "first" ? options[0]+ : focus === "last" ? options.at(-1)+ : options.find((option) => option.classList.contains("active")) ?? options[0];+ target?.focus();+ };+ const moveOptionFocus = (offset: number): void => {+ const current = options.indexOf(document.activeElement as HTMLButtonElement);+ const next = current < 0 ? 0 : (current + offset + options.length) % options.length;+ options[next]?.focus();+ };++ trigger.addEventListener("click", () => {+ if (control.classList.contains("open")) close(false);+ else open();+ });+ trigger.addEventListener("keydown", (event) => {+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ event.stopPropagation();+ open(event.key === "ArrowDown" ? "first" : "last");+ } else if (event.key === "Escape" && control.classList.contains("open")) {+ event.preventDefault();+ event.stopPropagation();+ close(false);+ }+ });+ menu.addEventListener("keydown", (event) => {+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ event.stopPropagation();+ moveOptionFocus(event.key === "ArrowDown" ? 1 : -1);+ } else if (event.key === "Home" || event.key === "End") {+ event.preventDefault();+ event.stopPropagation();+ options[event.key === "Home" ? 0 : options.length - 1]?.focus();+ } else if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ close(true);+ }+ });+ control.addEventListener("focusout", (event) => {+ if (event.relatedTarget instanceof Node && control.contains(event.relatedTarget)) return;+ close(false);+ });+ return { close };+}diff --git a/packages/studio/src/ui/i18n.ts b/packages/studio/src/ui/i18n.tsnew file mode 100644index 00000000..3217b128--- /dev/null+++ b/packages/studio/src/ui/i18n.ts@@ -0,0 +1,109 @@+import { builtinLanguages, chooseLanguage, formatMessage, readLanguagePack } from "../localization.js";+import type { LanguagePack, Message, MessageValues } from "../localization.js";+import { bindDropdown } from "./dropdown.js";+import { icon } from "./icons.js";+export type { Message } from "../localization.js";++type Attribute = "title" | "aria-label" | "placeholder" | "alt";+const attributes: readonly Attribute[] = ["title", "aria-label", "placeholder", "alt"];+const storageKey = "hypit-studio.language";+let languages = builtinLanguages;+let language = chooseLanguage(languages, navigator.languages);++export async function initializeI18n(): Promise<void> {+ const response = await fetch("/__studio/locales");+ if (!response.ok) throw new Error(`Could not load Studio languages (${response.status}).`);+ languages = (await response.json() as unknown[]).map(readLanguagePack);+ let saved: string | null = null;+ try { saved = localStorage.getItem(storageKey); } catch { /* Browser storage may be disabled. */ }+ language = chooseLanguage(languages, [...(saved ? [saved] : []), ...navigator.languages]);+ document.documentElement.lang = language.locale;+}++export function t(message: Message, values: MessageValues = {}): string {+ return formatMessage(language, message, values);+}+function escape(value: string): string {+ return value.replace(/[&<>"']/gu, char => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!);+}+export function uiLabel(message: Message): string {+ return `<span data-ui-text="${message}" dir="${language.direction}">${escape(t(message))}</span>`;+}+export function uiAttribute(attribute: Attribute, message: Message): string {+ return `${attribute}="${escape(t(message))}" data-ui-${attribute}="${message}"`;+}+export function uiText(node: Element, message: Message, values: MessageValues = {}): void {+ node.setAttribute("data-ui-text", message);+ node.setAttribute("data-ui-values", JSON.stringify(values));+ node.setAttribute("dir", language.direction);+ node.textContent = t(message, values);+}+/** Use when a node changes from UI text into a user-provided name or an empty value. */+export function userText(node: Element, value: string): void {+ node.removeAttribute("data-ui-text");+ node.removeAttribute("data-ui-values");+ node.setAttribute("dir", "auto");+ node.textContent = value;+}+export function uiAttr(node: Element, attribute: Attribute, message: Message, values: MessageValues = {}): void {+ node.setAttribute(`data-ui-${attribute}`, message);+ node.setAttribute(`data-ui-${attribute}-values`, JSON.stringify(values));+ node.setAttribute(attribute, t(message, values));+}+export function uiDate(node: Element, timestamp: number): void {+ node.setAttribute("data-ui-date", String(timestamp));+ node.textContent = new Intl.DateTimeFormat(language.locale, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }).format(timestamp);+}++function selectLanguage(pack: LanguagePack): void {+ language = pack;+ try { localStorage.setItem(storageKey, pack.locale); } catch { /* Tab-local choice still applies. */ }+ document.documentElement.lang = pack.locale;+ // Update explicitly marked chrome in place, without rebuilding editors or the player.+ for (const node of Array.from(document.querySelectorAll("[data-ui-text]"))) {+ uiText(node, node.getAttribute("data-ui-text") as Message, JSON.parse(node.getAttribute("data-ui-values") ?? "{}") as MessageValues);+ }+ for (const attribute of attributes) {+ for (const node of Array.from(document.querySelectorAll(`[data-ui-${attribute}]`))) {+ uiAttr(node, attribute, node.getAttribute(`data-ui-${attribute}`) as Message, JSON.parse(node.getAttribute(`data-ui-${attribute}-values`) ?? "{}") as MessageValues);+ }+ }+ for (const node of Array.from(document.querySelectorAll("[data-ui-date]"))) uiDate(node, Number(node.getAttribute("data-ui-date")));+}++export function languageMenu(): HTMLElement {+ const control = document.createElement("div");+ control.className = "parameter-select language-select";+ const trigger = document.createElement("button");+ trigger.type = "button"; trigger.className = "parameter-select-trigger language-toggle";+ trigger.dataset.language = "";+ trigger.innerHTML = icon("globe");+ uiAttr(trigger, "title", "app.language"); uiAttr(trigger, "aria-label", "app.language");+ trigger.setAttribute("aria-haspopup", "listbox"); trigger.setAttribute("aria-expanded", "false");+ const menu = document.createElement("div");+ menu.className = "parameter-select-menu"; menu.id = "studio-languages"; menu.hidden = true;+ menu.setAttribute("role", "listbox"); uiAttr(menu, "aria-label", "app.language");+ trigger.setAttribute("aria-controls", menu.id);+ const options = languages.map(pack => {+ const item = document.createElement("button");+ item.type = "button"; item.className = "parameter-select-option";+ item.lang = pack.locale; item.dir = pack.direction;+ item.textContent = pack.name;+ item.dataset.locale = pack.locale;+ item.setAttribute("role", "option");+ item.addEventListener("click", () => {+ selectLanguage(pack); renderSelection(); close(true);+ });+ return item;+ });+ const renderSelection = (): void => {+ for (const item of options) {+ const selected = item.dataset.locale === language.locale;+ item.classList.toggle("active", selected); item.setAttribute("aria-selected", String(selected));+ }+ };+ menu.append(...options); control.append(trigger, menu);+ const { close } = bindDropdown(control, trigger, menu, options);+ renderSelection();+ return control;+}diff --git a/packages/studio/src/ui/icons.ts b/packages/studio/src/ui/icons.tsindex 104a029e..63cd7f19 100644--- a/packages/studio/src/ui/icons.ts+++ b/packages/studio/src/ui/icons.ts@@ -1,5 +1,6 @@const paths: Readonly<Record<string, string>> = {brand: '<g transform="translate(0 1.282) scale(.091603) translate(-50 -180)"><path fill="currentColor" stroke="none" d="M303.78,277.82c-5.98-8.63-15.83-13.77-26.32-13.77h-93.41c-12.28,0-24.92,7.44-29.6,18.8l-28.26,75.82c-4.6,11.25-4.54,24.05,2.22,34.16,6.79,10.15,19.36,16.15,31.57,16.15h85.98c14.12,0,26.9-8.88,31.84-22.1l29.69-79.57c3.67-9.84,2.29-20.86-3.69-29.48v-.02h-.02ZM252.02,377.25c-.94,2.52-3.39,4.22-6.08,4.22h-83.45c-4.34,0-6.68-2.8-7.49-3.99s-2.5-4.43-.84-8.44l23.85-66.24c2.29-6.35,8.08-10.87,14.82-11.22.33-.02.67-.02,1.02-.02h75.41s12.51,1.42,9.29,14.61l-26.53,71.09h0ZM106.85,361.73s-22.36-11.59-17.66-32.66l29.67-82.23c4.78-13.25,17.36-22.09,31.45-22.09h95.02c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-112.97c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h0ZM73.3,323.27s-22.37-11.59-17.66-32.66l29.67-82.23c4.79-13.25,17.37-22.09,31.45-22.09h89.91c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-107.84c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h-.02Z"/></g>',+ globe: '<circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/>',code: '<path d="M9 7 4 12l5 5M15 7l5 5-5 5M13 4l-2 16"/>',edit: '<path d="m4 16-.8 4 4-.8L18.5 8.9 15.1 5.5 4 16Z"/><path d="m13.8 6.8 3.4 3.4"/>',studio: '<rect x="3" y="4" width="18" height="16" rx="1.5"/><path d="M3 14h18M8 4v10M15 14v6"/>',diff --git a/packages/studio/src/ui/library.ts b/packages/studio/src/ui/library.tsindex e4bc08b3..6de384b1 100644--- a/packages/studio/src/ui/library.ts+++ b/packages/studio/src/ui/library.ts@@ -1,3 +1,4 @@+import { t, uiDate, uiLabel, uiAttribute, uiText, uiAttr, type Message } from "./i18n.js";import type {StudioArtifactView,StudioLibraryView,@@ -38,19 +39,19 @@ function formatBytes(value: number): string {return `${(value / 1_000_000_000).toFixed(1)} GB`;}-const date = new Intl.DateTimeFormat(undefined, {- month: "short",- day: "numeric",- hour: "2-digit",- minute: "2-digit",-});+function localizedSidebarItem(input: { label: Message; icon: string; selected: boolean; select(): void }): HTMLButtonElement {+ const button = sidebarItem(input);+ uiAttr(button, "title", input.label);+ uiAttr(button, "aria-label", input.label);+ return button;+}-function emptyState(iconName: string, title: string, detail: string): HTMLElement {+function emptyState(iconName: string, title: Message, detail: Message): HTMLElement {const node = document.createElement("div");node.className = "library-empty";node.innerHTML = `<span class="library-empty-icon">${icon(iconName)}</span><strong></strong><p></p>`;- node.querySelector("strong")!.textContent = title;- node.querySelector("p")!.textContent = detail;+ uiText(node.querySelector("strong")!, title);+ uiText(node.querySelector("p")!, detail);return node;}@@ -77,9 +78,9 @@ function taskCard(task: StudioTaskView, selected: boolean, select: () => void, snode.dataset.taskId = task.id;const source = task.run ?? task.source;const title = task.title ?? stem(source);- const statuses: Record<StudioTaskView["status"], string> = {- queued: "Queued", running: "Running", waiting: "Waiting", complete: "Completed",- failed: "Failed", cancelled: "Cancelled", "saving-result": "Saving", attention: "Needs attention",+ const statuses: Record<StudioTaskView["status"], Message> = {+ queued: "common.queued", running: "common.running", waiting: "common.waiting", complete: "common.completed",+ failed: "common.failed", cancelled: "common.cancelled", "saving-result": "common.saving", attention: "common.needs-attention",};node.innerHTML = `<div class="task-state" aria-hidden="true">${icon(task.ongoing ? "when" : task.status === "complete" ? "check" : task.status === "failed" ? "alert" : "tasks")}</div>@@ -89,18 +90,24 @@ function taskCard(task: StudioTaskView, selected: boolean, select: () => void, s<div class="task-progress" data-progress></div><div class="task-detail" data-detail></div></div>- <button type="button" class="task-open" aria-label="View task media" title="View media">${icon("arrowRight")}</button>`;+ <button type="button" class="task-open" ${uiAttribute("aria-label", "library.view-task-media")} ${uiAttribute("title", "library.view-media")}>${icon("arrowRight")}</button>`;const name = node.querySelector<HTMLButtonElement>(".task-name")!;name.textContent = title;name.addEventListener("click", (event) => { event.stopPropagation(); select(); });- node.querySelector<HTMLElement>(".task-status")!.textContent = statuses[task.status];+ uiText(node.querySelector<HTMLElement>(".task-status")!, statuses[task.status]);const time = node.querySelector("time")!;time.dateTime = new Date(task.createdAt).toISOString();- time.textContent = date.format(task.createdAt);+ uiDate(time, task.createdAt);const progress = task.ongoing ? taskProgress(task) : undefined;const progressNode = node.querySelector<HTMLElement>("[data-progress]")!;if (progress === undefined) progressNode.remove();- else { progressNode.textContent = progress; progressNode.title = progress; }+ else {+ progressNode.textContent = progress; progressNode.title = progress;+ if (!task.operations.some(operation => operation.status === "pending" && operation.phase !== undefined) && task.requests !== undefined) {+ uiText(progressNode, "tasks.progress", task.requests);+ uiAttr(progressNode, "title", "tasks.progress", task.requests);+ }+ }const detailNode = node.querySelector<HTMLElement>("[data-detail]")!;if (task.detail === undefined) detailNode.remove();else {@@ -109,10 +116,10 @@ function taskCard(task: StudioTaskView, selected: boolean, select: () => void, smessage.textContent = task.detail;detailNode.append(message);const copy = document.createElement("button");- copy.type = "button"; copy.className = "task-copy-error"; copy.textContent = "Copy error";+ copy.type = "button"; copy.className = "task-copy-error"; uiText(copy, "tasks.copy-error");copy.addEventListener("click", (event) => {event.stopPropagation();- void navigator.clipboard.writeText(task.detail!).then(() => { copy.textContent = "Copied"; }, () => { copy.textContent = "Select the text to copy"; });+ void navigator.clipboard.writeText(task.detail!).then(() => { uiText(copy, "common.copied"); }, () => { uiText(copy, "tasks.copy-manually"); });});detailNode.append(copy);detailNode.addEventListener("click", (event) => { event.stopPropagation(); if (!node.classList.contains("selected")) select(); });@@ -122,11 +129,11 @@ function taskCard(task: StudioTaskView, selected: boolean, select: () => void, sreturn node;}-function artifactKind(mediaType: string): { readonly label: string; readonly icon: string } {- if (mediaType.startsWith("video/")) return { label: "Video", icon: "video" };- if (mediaType.startsWith("image/")) return { label: "Image", icon: "image" };- if (mediaType.startsWith("audio/")) return { label: "Audio", icon: "waveform" };- return { label: "Data", icon: "code" };+function artifactKind(mediaType: string): { readonly label: Message; readonly icon: string } {+ if (mediaType.startsWith("video/")) return { label: "library.video", icon: "video" };+ if (mediaType.startsWith("image/")) return { label: "library.image", icon: "image" };+ if (mediaType.startsWith("audio/")) return { label: "library.audio", icon: "waveform" };+ return { label: "library.data", icon: "code" };}function sizeThumbnail(media: HTMLElement, width: number, height: number): void {@@ -140,7 +147,7 @@ function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtifconst kind = artifactKind(artifact.mediaType);const link = document.createElement("div");link.tabIndex = 0;- link.className = `artifact-card artifact-${kind.label.toLowerCase()}${artifact.highlighted ? " artifact-highlighted" : ""}`;+ link.className = `artifact-card artifact-${artifact.mediaType.split("/")[0]}${artifact.highlighted ? " artifact-highlighted" : ""}`;const query = new URLSearchParams({build: artifact.build,output: artifact.output,@@ -158,10 +165,10 @@ function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtif<span class="artifact-glyph">${icon(kind.icon)}</span><span class="artifact-type"></span></div>`;- link.querySelector<HTMLElement>(".artifact-type")!.textContent = kind.label;+ uiText(link.querySelector<HTMLElement>(".artifact-type")!, kind.label);const preview = link.querySelector<HTMLElement>(".artifact-preview")!;preview.setAttribute("role", "button");- preview.setAttribute("aria-label", `Preview ${title}`);+ uiAttr(preview, "aria-label", "library.preview-name", { name: title });preview.addEventListener("click", () => open(artifact));const name = createArtifactName({name: title,@@ -173,11 +180,11 @@ function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtifbody: JSON.stringify({ build: artifact.build, output: artifact.output, displayName }),});const result = await response.json() as { displayName?: string; error?: string };- if (!response.ok || typeof result.displayName !== "string") throw new Error(result.error ?? "Could not save the name");+ if (!response.ok || typeof result.displayName !== "string") throw new Error(result.error ?? t("library.name-failed"));artifact = { ...artifact, displayName: result.displayName };link.dataset.displayName = result.displayName;renamed(artifact);- preview.setAttribute("aria-label", `Preview ${result.displayName}`);+ uiAttr(preview, "aria-label", "library.preview-name", { name: result.displayName });preview.title = [result.displayName, ...preview.title.split("\n").slice(1)].join("\n");return result.displayName;},@@ -191,7 +198,7 @@ function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtifif (artifact.mediaType.startsWith("image/")) {const image = document.createElement("img");image.addEventListener("load", () => sizeThumbnail(image, image.naturalWidth, image.naturalHeight));- image.addEventListener("error", () => { link.classList.add("preview-unavailable"); link.querySelector<HTMLElement>(".artifact-type")!.textContent = "Preview unavailable"; });+ image.addEventListener("error", () => { link.classList.add("preview-unavailable"); uiText(link.querySelector<HTMLElement>(".artifact-type")!, "library.preview-unavailable"); });image.src = href;image.alt = "";image.loading = "lazy";@@ -204,11 +211,11 @@ function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtifvideo.dataset.previewSource = href;video.setAttribute("aria-hidden", "true");const label = link.querySelector<HTMLElement>(".artifact-type")!;- label.textContent = "Video · Loading preview";+ uiText(label, "library.video-loading-preview");const ready = () => {if (video.readyState < 2 || video.seeking) return;video.classList.add("is-ready");- label.textContent = "Video";+ uiText(label, "library.video");};video.addEventListener("loadedmetadata", () => {sizeThumbnail(video, video.videoWidth, video.videoHeight);@@ -216,7 +223,7 @@ function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtif}, { once: true });video.addEventListener("loadeddata", ready);video.addEventListener("seeked", ready);- video.addEventListener("error", () => { label.textContent = "Preview unavailable"; link.classList.add("preview-unavailable"); });+ video.addEventListener("error", () => { uiText(label, "library.preview-unavailable"); link.classList.add("preview-unavailable"); });link.querySelector<HTMLElement>(".artifact-preview")!.prepend(video);} else if (artifact.mediaType.startsWith("audio/")) {const waveform = document.createElement("img");@@ -229,7 +236,7 @@ function artifactCard(artifact: StudioArtifactView, open: (artifact: StudioArtiftitle,artifact.mediaType,formatBytes(artifact.size),- date.format(artifact.createdAt),+ new Date(artifact.createdAt).toLocaleString(),artifact.ownerBuild === undefined ? artifact.filePath : `${artifact.ownerBuild}/${artifact.filePath}`,...artifact.origins.map((origin) => `${origin.run ?? origin.source} · ${origin.build} · ${origin.output}`),artifact.buildNote,@@ -241,15 +248,15 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studiconst element = document.createElement("section");element.className = "library";element.innerHTML = `- <div class="library-tabs" role="tablist" aria-label="Studio library">+ <div class="library-tabs" role="tablist" ${uiAttribute("aria-label", "library.studio-library")}><button type="button" class="library-tab active" data-library-tab="source" role="tab" aria-selected="true">- <span>${icon("code")}</span><strong>Source</strong>+ <span>${icon("code")}</span><strong>${uiLabel("library.source")}</strong></button><button type="button" class="library-tab" data-library-tab="tasks" role="tab" aria-selected="false">- <span>${icon("tasks")}</span><strong>Tasks</strong>+ <span>${icon("tasks")}</span><strong>${uiLabel("library.tasks")}</strong></button><button type="button" class="library-tab" data-library-tab="artifacts" role="tab" aria-selected="false">- <span>${icon("results")}</span><strong>Artifacts</strong>+ <span>${icon("results")}</span><strong>${uiLabel("library.artifacts")}</strong></button></div><section class="library-view active" data-library-view="source">@@ -258,19 +265,22 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studi<section class="library-view" data-library-view="artifacts"></section>`;- const sourcePanel = createSidebarPanel("panel", "Referenced source files");+ const sourcePanel = createSidebarPanel("panel", "library.referenced-source-files");+ uiAttr(sourcePanel.navigation, "aria-label", "library.referenced-source-files");sourcePanel.toolbar.append(code.toolbar);sourcePanel.content.classList.add("source-code");sourcePanel.content.append(code.element);element.querySelector('[data-library-view="source"]')!.append(sourcePanel.element);- const taskPanel = createSidebarPanel("panel", "Task categories");- taskPanel.toolbar.innerHTML = `<span class="code-location" data-task-heading>All tasks</span><div class="task-context" data-task-context hidden></div>- <button type="button" class="library-refresh" data-library-refresh aria-label="Refresh tasks" title="Refresh">${icon("refresh")}</button>`;+ const taskPanel = createSidebarPanel("panel", "library.task-categories");+ uiAttr(taskPanel.navigation, "aria-label", "library.task-categories");+ taskPanel.toolbar.innerHTML = `<span class="code-location" data-task-heading>${uiLabel("library.all-tasks")}</span><div class="task-context" data-task-context hidden></div>+ <button type="button" class="library-refresh" data-library-refresh ${uiAttribute("aria-label", "library.refresh-tasks")} ${uiAttribute("title", "common.refresh")}>${icon("refresh")}</button>`;taskPanel.content.innerHTML = `<div class="media-status" data-library-status="tasks" role="status" hidden></div><div class="task-list" data-task-list></div>`;element.querySelector('[data-library-view="tasks"]')!.append(taskPanel.element);- const mediaPanel = createSidebarPanel("panel", "Media categories");- mediaPanel.toolbar.innerHTML = `<span class="code-location" data-media-heading>All media</span><div class="task-context" data-task-context hidden></div>- <button type="button" class="library-refresh" data-library-refresh aria-label="Refresh media" title="Refresh">${icon("refresh")}</button>`;+ const mediaPanel = createSidebarPanel("panel", "library.media-categories");+ uiAttr(mediaPanel.navigation, "aria-label", "library.media-categories");+ mediaPanel.toolbar.innerHTML = `<span class="code-location" data-media-heading>${uiLabel("library.all-media")}</span><div class="task-context" data-task-context hidden></div>+ <button type="button" class="library-refresh" data-library-refresh ${uiAttribute("aria-label", "library.refresh-media")} ${uiAttribute("title", "common.refresh")}>${icon("refresh")}</button>`;mediaPanel.content.innerHTML = `<div class="media-status" data-library-status="artifacts" role="status" hidden></div><div class="artifact-grid" data-artifact-grid></div>`;element.querySelector('[data-library-view="artifacts"]')!.append(mediaPanel.element);const sourceList = sourcePanel.navigation;@@ -300,7 +310,7 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studinode.className = "library-continuation";node.dataset.moreSection = section;node.dataset.before = cursor;- node.textContent = "Loading more…";+ uiText(node, "library.loading-more");return node;};const selectArtifact = (id: string | undefined): void => {@@ -367,7 +377,7 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studiback.type = "button"; back.className = "task-context-name";back.innerHTML = "<span></span>";back.querySelector("span")!.textContent = task.title ?? stem(task.run ?? task.source);- back.title = `${task.title ?? stem(task.run ?? task.source)} · Return to task`;+ uiAttr(back, "title", "library.task-return", { name: task.title ?? stem(task.run ?? task.source) });back.addEventListener("click", () => {taskFilter = "all";switchTo("tasks", false);@@ -376,7 +386,7 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studi});const clear = document.createElement("button");clear.type = "button"; clear.className = "task-context-clear";- clear.innerHTML = icon("close"); clear.title = "Clear task filter"; clear.setAttribute("aria-label", clear.title);+ clear.innerHTML = icon("close"); uiAttr(clear, "title", "library.clear-task-filter"); uiAttr(clear, "aria-label", "library.clear-task-filter");clear.addEventListener("click", () => {selectedTask = undefined; delete libraries.artifacts; renderTaskContext(); renderTasks();if (active === "artifacts") { renderArtifacts(); void refresh("artifacts"); }@@ -389,11 +399,12 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studifor (const node of Array.from(taskList.querySelectorAll("[data-more-section]"))) morePages.unobserve(node);const library = libraries.tasks;const tasks = library?.tasks ?? [];- const filters = [["all", "All tasks", "component"], ["ongoing", "In progress", "when"], ["finished", "Finished", "check"]] as const;+ const filters = [["all", "library.all-tasks", "component"], ["ongoing", "library.in-progress", "when"], ["finished", "library.finished", "check"]] as const;const heading = taskPanel.toolbar.querySelector<HTMLElement>("[data-task-heading]")!;- heading.textContent = filters.find(([id]) => id === taskFilter)![1];- heading.title = library?.runtime === undefined ? "Saved project Results · no Runtime selected" : library.runtime;- taskPanel.navigation.replaceChildren(...filters.map(([id, label, mark]) => sidebarItem({+ uiText(heading, filters.find(([id]) => id === taskFilter)![1]);+ if (library?.runtime === undefined) uiAttr(heading, "title", "tasks.saved-only");+ else { heading.removeAttribute("data-ui-title"); heading.title = library.runtime; }+ taskPanel.navigation.replaceChildren(...filters.map(([id, label, mark]) => localizedSidebarItem({label, icon: mark, selected: id === taskFilter,select: () => { taskFilter = id; taskList.scrollTop = 0; renderTasks(); },})));@@ -413,10 +424,10 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studi() => selectTask(task), () => { selectTask(task); switchTo("artifacts"); }));renderTaskContext();if (tasksToShow.length === 0) entries.push(emptyState("tasks",- library === undefined && request !== undefined ? "Loading tasks…" : taskFilter === "ongoing" ? "No tasks in progress" : "No tasks here",+ library === undefined && request !== undefined ? "library.loading-tasks" : taskFilter === "ongoing" ? "library.no-tasks-in-progress" : "library.no-tasks-here",taskFilter === "ongoing" && library?.runtime === undefined- ? "No Runtime is selected. Saved tasks are available under Finished."- : "Refresh to read the latest task status."));+ ? "tasks.no-runtime"+ : "tasks.refresh-hint"));// Runtime activity is returned in full on the first page. Older pages contain Results only.if (taskFilter !== "ongoing" && library?.next !== undefined) entries.push(continuation("tasks", library.next));taskList.replaceChildren(...entries);@@ -429,12 +440,12 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studiconst cards = new Map(Array.from(artifactGrid.querySelectorAll<HTMLElement>("[data-artifact-id]"), (card) => [card.dataset.artifactId!, card]));const library = libraries.artifacts;const artifacts = library?.artifacts ?? [];- const filters = [["all", "All media", "component"], ["video", "Videos", "video"], ["image", "Images", "image"], ["audio", "Audio", "waveform"]] as const;+ const filters = [["all", "library.all-media", "component"], ["video", "library.videos", "video"], ["image", "library.images", "image"], ["audio", "library.audio", "waveform"]] as const;const heading = mediaPanel.toolbar.querySelector<HTMLElement>("[data-media-heading]")!;- heading.textContent = filters.find(([id]) => id === artifactFilter)?.[1] ?? "All media";- heading.title = "Media category";+ uiText(heading, filters.find(([id]) => id === artifactFilter)?.[1] ?? "library.all-media");+ uiAttr(heading, "title", "library.media-category");renderTaskContext();- artifactFilters.replaceChildren(...filters.map(([id, label, mark]) => sidebarItem({+ artifactFilters.replaceChildren(...filters.map(([id, label, mark]) => localizedSidebarItem({label, icon: mark, selected: id === artifactFilter,select: () => {artifactFilter = id;@@ -466,8 +477,8 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studiif (video !== null) { video.removeAttribute("src"); video.load(); }}if (shown.length === 0) entries.push(emptyState("results",- library === undefined && request !== undefined ? "Loading media…" : artifactFilter === "all" ? "No media" : `No ${artifactFilter} files`,- "Images, videos and audio published as file Outputs appear here, including those from ongoing Builds."));+ library === undefined && request !== undefined ? "library.loading-media" : artifactFilter === "all" ? "library.no-media" : "library.no-files-in-this-category",+ "library.media-hint"));if (library?.next !== undefined) entries.push(continuation("artifacts", library.next));artifactGrid.replaceChildren(...entries);selectArtifact(selectedArtifact);@@ -497,7 +508,7 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studiconst controller = new AbortController();request = controller;const status = element.querySelector<HTMLElement>(`[data-library-status="${section}"]`)!;- status.textContent = "Refreshing…";+ uiText(status, "library.refreshing");status.hidden = true;element.classList.add("is-refreshing");try {@@ -507,7 +518,7 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studiif (section === "artifacts" && selectedTask !== undefined) query.set("build", selectedTask.id);const response = await fetch(`/__studio/library?${query.toString()}`, { signal: controller.signal });const value = await response.json() as StudioLibraryView | { readonly error: string };- if (!response.ok || "error" in value) throw new Error("error" in value ? value.error : "Library unavailable");+ if (!response.ok || "error" in value) throw new Error("error" in value ? value.error : t("library.unavailable"));if (controller.signal.aborted) return;const previous = libraries[section];if (before === undefined || previous === undefined) libraries[section] = value;@@ -522,18 +533,18 @@ export function createLibraryPane(code: CodePane, openArtifact: (artifact: Studi}if (section === "tasks") renderTasks();else renderArtifacts();- status.textContent = `Updated ${new Date().toLocaleTimeString()}`;+ uiText(status, "library.updated", { time: new Date().toLocaleTimeString() });} catch (error) {if (!controller.signal.aborted) {const detail = error instanceof Error ? error.message : String(error);status.hidden = false;- status.textContent = `Refresh failed: ${detail}${libraries[section] === undefined ? "" : " · Previous view retained"}`;+ uiText(status, libraries[section] === undefined ? "library.refresh-failed" : "library.refresh-failed-retained", { detail });}} finally {if (request === controller) {request = undefined;element.classList.remove("is-refreshing");- if (controller.signal.aborted) status.textContent = "Refresh interrupted";+ if (controller.signal.aborted) uiText(status, "library.refresh-interrupted");}}};diff --git a/packages/studio/src/ui/main.ts b/packages/studio/src/ui/main.tsindex 348db49d..c971efa5 100644--- a/packages/studio/src/ui/main.ts+++ b/packages/studio/src/ui/main.ts@@ -1,3 +1,5 @@+import { bindDropdown } from "./dropdown.js";+import { uiLabel, uiAttribute, uiText, uiAttr, userText, languageMenu, initializeI18n, type Message } from "./i18n.js";import type { Clip, StudioFailure, StudioInspectorDomain, StudioSnapshot } from "../shared.js";import type { CanonicalValue, ValueSchema } from "@hypit/protocol";import { parameterAuthorValue, parameterControlForSchema, parameterNumber, parameterOption, parameterRecordSchema, parameterRecordVariants, validateParameterValue } from "../parameter-values.js";@@ -16,6 +18,8 @@ import { createTimeline } from "./timeline.js";import { createComments } from "./comments.js";import "../style.css";+await initializeI18n();+const app = document.querySelector<HTMLElement>("#app")!;app.innerHTML = `<header class="topbar">@@ -40,9 +44,10 @@ app.innerHTML = `<div class="topbar-right"><div class="meta" data-meta></div><div class="status" data-status></div>- <div class="view-tabs" role="tablist" aria-label="Studio view">- <button type="button" role="tab" data-view="studio" aria-selected="true">${icon("studio")}Studio</button>- <button type="button" role="tab" data-view="comments" aria-selected="false">${icon("comments")}Comments</button>+ <div data-language-menu></div>+ <div class="view-tabs" role="tablist" ${uiAttribute("aria-label", "app.studio-view")}>+ <button type="button" role="tab" data-view="studio" aria-selected="true">${icon("studio")}${uiLabel("app.studio")}</button>+ <button type="button" role="tab" data-view="comments" aria-selected="false">${icon("comments")}${uiLabel("app.comments")}</button></div></div></header>@@ -52,7 +57,7 @@ app.innerHTML = `<div class="preview-panel" data-stage></div><aside class="workspace-panel"><div class="pane-heading workspace-heading" data-workspace-heading>- <div class="pane-title">${icon("tune")}<h2>Properties</h2></div>+ <div class="pane-title">${icon("tune")}<h2>${uiLabel("inspector.properties")}</h2></div></div><div class="workspace-scroll"><section class="workspace-section">@@ -65,6 +70,8 @@ app.innerHTML = `</main><pre class="failure" data-failure></pre>`;+app.querySelector("[data-language-menu]")!.replaceWith(languageMenu());+const store = createStore();const code = createCodePane();const stage = createStage(store, (id) => library.selectArtifact(id));@@ -144,7 +151,7 @@ changeView();timeline.element.addEventListener("studio:write", (event) => {const state = (event as CustomEvent<{ readonly state?: string }>).detail.state;status.className = state === "error" ? "status error" : state === "saved" ? "status saved" : "status saving";- status.textContent = state === "error" ? "Save failed" : state === "saved" ? "Saved" : "Saving";+ uiText(status, state === "error" ? "common.save-failed" : state === "saved" ? "common.saved" : "common.saving");});// Program-level facts never change while a Source is being read, so they live in@@ -154,14 +161,14 @@ function renderMeta(snapshot: StudioSnapshot): void {project.title = snapshot.source.path;// Sequence facts belong to the project/inspector, not the application chrome.// The timeline transport is the single persistent time readout.- meta.textContent = "";+ userText(meta, "");}-function property(label: string, value: string, tone?: string): HTMLElement {+function property(label: Message, value: string, tone?: string): HTMLElement {const node = document.createElement("div");node.className = `property${tone === undefined ? "" : ` ${tone}`}`;node.innerHTML = "<span></span><strong></strong>";- node.querySelector("span")!.textContent = label;+ uiText(node.querySelector("span")!, label);node.querySelector("strong")!.textContent = value;node.querySelector("strong")!.title = value;return node;@@ -179,6 +186,12 @@ function group(label: string, items: readonly HTMLElement[], className = ""): HTreturn node;}+function uiGroup(label: Message, items: readonly HTMLElement[]): HTMLElement {+ const node = group(label, items);+ uiText(node.querySelector("h3")!, label);+ return node;+}+function aspectRatio(width: number, height: number): string {let a = width;let b = height;@@ -186,10 +199,10 @@ function aspectRatio(width: number, height: number): string {return `${width / a}:${height / a}`;}-const domainPresentation: Readonly<Record<StudioInspectorDomain, { readonly label: string; readonly icon: string }>> = {- where: { label: "Where", icon: "where" },- how: { label: "How", icon: "how" },- when: { label: "When", icon: "when" },+const domainPresentation: Readonly<Record<StudioInspectorDomain, { readonly label: Message; readonly icon: string }>> = {+ where: { label: "inspector.where", icon: "where" },+ how: { label: "inspector.how", icon: "how" },+ when: { label: "inspector.when", icon: "when" },};const domainOrder: readonly StudioInspectorDomain[] = ["where", "when", "how"];const inspectorDomainByEntity = new Map<string, StudioInspectorDomain>();@@ -197,7 +210,7 @@ const inspectorPageByEntity = new Map<string, string>();function defaultWorkspaceHeading(): void {workspaceHeading.className = "pane-heading workspace-heading";- workspaceHeading.innerHTML = `<div class="pane-title">${icon("tune")}<h2>Properties</h2></div>`;+ workspaceHeading.innerHTML = `<div class="pane-title">${icon("tune")}<h2>${uiLabel("inspector.properties")}</h2></div>`;}function inspectorHeading(@@ -213,7 +226,7 @@ function inspectorHeading(button.type = "button";button.className = `inspector-domain-tab${domain === active ? " active" : ""}`;button.dataset.domain = domain;- button.innerHTML = `${icon(presentation.icon)}<strong>${presentation.label}</strong>`;+ button.innerHTML = `${icon(presentation.icon)}<strong>${uiLabel(presentation.label)}</strong>`;button.setAttribute("aria-pressed", String(domain === active));button.addEventListener("click", () => {inspectorDomainByEntity.set(entityId, domain);@@ -244,7 +257,7 @@ function commitControl(entityId: string, parameter: Clip["inspector"][number], rvoid writeParameter(entityId, parameter, replacement);} catch (error) {restoreParameterControls(entityId);- status.textContent = "Invalid value"; status.className = "status error";+ uiText(status, "common.invalid-value"); status.className = "status error";status.title = error instanceof Error ? error.message : String(error);}}@@ -329,70 +342,7 @@ function selectControl(});menu.append(...options);- const close = (restoreFocus: boolean): void => {- control.classList.remove("open", "open-up");- trigger.setAttribute("aria-expanded", "false");- menu.hidden = true;- if (restoreFocus) trigger.focus();- };- const open = (focus: "selected" | "first" | "last" = "selected"): void => {- control.classList.add("open");- trigger.setAttribute("aria-expanded", "true");- menu.hidden = false;- control.classList.remove("open-up");- const scroll = control.closest<HTMLElement>(".workspace-scroll");- if (scroll !== null) {- const menuBox = menu.getBoundingClientRect();- const scrollBox = scroll.getBoundingClientRect();- if (menuBox.bottom > scrollBox.bottom && trigger.getBoundingClientRect().top - menuBox.height >= scrollBox.top) {- control.classList.add("open-up");- }- }- const target = focus === "first" ? options[0]- : focus === "last" ? options.at(-1)- : options.find((option) => option.classList.contains("active")) ?? options[0];- target?.focus();- };- const moveOptionFocus = (offset: number): void => {- const current = options.indexOf(document.activeElement as HTMLButtonElement);- const next = current < 0 ? 0 : (current + offset + options.length) % options.length;- options[next]?.focus();- };-- trigger.addEventListener("click", () => {- if (control.classList.contains("open")) close(false);- else open();- });- trigger.addEventListener("keydown", (event) => {- if (event.key === "ArrowDown" || event.key === "ArrowUp") {- event.preventDefault();- event.stopPropagation();- open(event.key === "ArrowDown" ? "first" : "last");- } else if (event.key === "Escape" && control.classList.contains("open")) {- event.preventDefault();- event.stopPropagation();- close(false);- }- });- menu.addEventListener("keydown", (event) => {- if (event.key === "ArrowDown" || event.key === "ArrowUp") {- event.preventDefault();- event.stopPropagation();- moveOptionFocus(event.key === "ArrowDown" ? 1 : -1);- } else if (event.key === "Home" || event.key === "End") {- event.preventDefault();- event.stopPropagation();- options[event.key === "Home" ? 0 : options.length - 1]?.focus();- } else if (event.key === "Escape") {- event.preventDefault();- event.stopPropagation();- close(true);- }- });- control.addEventListener("focusout", (event) => {- if (event.relatedTarget instanceof Node && control.contains(event.relatedTarget)) return;- close(false);- });+ const { close } = bindDropdown(control, trigger, menu, options);control.append(trigger, menu);return control;}@@ -413,7 +363,7 @@ function colorValueControl(const picker = document.createElement("input");picker.type = "color";picker.className = "parameter-color-native";- picker.setAttribute("aria-label", `${label} picker`);+ uiAttr(picker, "aria-label", "inspector.color-picker", { label });picker.title = label;const exact = /^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/iu.test(initial);picker.value = exact ? initial.slice(0, 7) : "#000000";@@ -530,7 +480,7 @@ function structuredControl(entityId: string, parameter: Clip["inspector"][numberconst save = (): void => {const changed = !sameValue(draft, parameter.value);notice.hidden = !changed || valid();- notice.textContent = "Complete the required fields with valid values to save.";+ uiText(notice, "inspector.invalid-fields");if (changed && valid()) change(draft);};@@ -563,9 +513,8 @@ function structuredControl(entityId: string, parameter: Clip["inspector"][numberconst summary = document.createElement("div");summary.className = "parameter-structured-summary";const count = document.createElement("span");- count.textContent = schema.kind === "array" && Array.isArray(draft)- ? `${draft.length} ${draft.length === 1 ? "item" : "items"}`- : "Structured value";+ if (schema.kind === "array" && Array.isArray(draft)) uiText(count, "inspector.item-count", { count: draft.length });+ else uiText(count, "inspector.structured-value");summary.append(count);if (schema.kind === "array") shell.append(summary);@@ -600,19 +549,19 @@ function structuredControl(entityId: string, parameter: Clip["inspector"][numberconst up = document.createElement("button");up.type = "button";up.textContent = "↑";- up.title = "Move up";+ uiAttr(up, "title", "inspector.move-up");up.disabled = index === 0;up.addEventListener("click", () => move(-1));const down = document.createElement("button");down.type = "button";down.textContent = "↓";- down.title = "Move down";+ uiAttr(down, "title", "inspector.move-down");down.disabled = index === list.length - 1;down.addEventListener("click", () => move(1));const remove = document.createElement("button");remove.type = "button";remove.innerHTML = icon("minus");- remove.title = "Remove item";+ uiAttr(remove, "title", "inspector.remove-item");remove.disabled = schema.minItems !== undefined && list.length <= schema.minItems;remove.addEventListener("click", () => {const current = Array.isArray(draft) ? draft : [];@@ -639,7 +588,7 @@ function structuredControl(entityId: string, parameter: Clip["inspector"][numberconst add = document.createElement("button");add.type = "button";add.className = "parameter-structured-add";- add.innerHTML = `${icon("plus")}<span>Add ${schema.items.kind === "string" && schema.items.format === "color" ? "color" : "item"}</span>`;+ add.innerHTML = `${icon("plus")}${uiLabel(schema.items.kind === "string" && schema.items.format === "color" ? "inspector.add-color" : "inspector.add-item")}`;add.disabled = schema.maxItems !== undefined && list.length >= schema.maxItems;add.addEventListener("click", () => {const current = Array.isArray(draft) ? draft : [];@@ -708,7 +657,7 @@ function parameterControl(const palette = document.createElement("span"); palette.className = "parameter-swatches";for (const color of parameter.swatches) {const swatch = document.createElement("button"); swatch.type = "button";- swatch.style.backgroundColor = color; swatch.title = color; swatch.setAttribute("aria-label", `Use ${color}`);+ swatch.style.backgroundColor = color; swatch.title = color; uiAttr(swatch, "aria-label", "inspector.use-color", { color });swatch.addEventListener("click", () => commit(color)); palette.append(swatch);}right.append(palette);@@ -784,13 +733,13 @@ function parameterGroups(entityId: string, fields: readonly Clip["inspector"][nu});}-let parameterWriteState: "" | "Saving" | "Saved" | "Failed" = "";+let parameterWriteState: "" | "common.saving" | "common.saved" | "common.failed" = "";async function writeParameter(entityId: string, parameter: Clip["inspector"][number], replacement: CanonicalValue): Promise<void> {const state = store.current();if (state === undefined) return;- parameterWriteState = "Saving";+ parameterWriteState = "common.saving";status.title = "";- status.textContent = parameterWriteState;+ uiText(status, parameterWriteState);status.className = "status saving";try {await applyStudioMutation({@@ -800,15 +749,15 @@ async function writeParameter(entityId: string, parameter: Clip["inspector"][numparameterId: parameter.id,value: replacement,});- parameterWriteState = "Saved";- status.textContent = parameterWriteState;+ parameterWriteState = "common.saved";+ uiText(status, parameterWriteState);status.className = "status saved";} catch (error) {// Validation and stale-revision rejections do not publish a new snapshot.// Restore the accepted value just as a rejected compilation does.restoreParameterControls(entityId);- parameterWriteState = "Failed";- status.textContent = error instanceof Error ? "Save failed" : parameterWriteState;+ parameterWriteState = "common.failed";+ uiText(status, error instanceof Error ? "common.save-failed" : parameterWriteState);status.className = "status error";status.title = error instanceof Error ? error.message : String(error);}@@ -826,26 +775,26 @@ function renderInspector(snapshot: StudioSnapshot, clipId: string | undefined):defaultWorkspaceHeading();const fps = snapshot.space.frameRate.numerator / snapshot.space.frameRate.denominator;inspector.replaceChildren(- group("Project", [- property("Author", snapshot.source.path, "property-code"),- property("Run", snapshot.run.path, "property-code"),- property("Sources", `${snapshot.source.files.length} referenced files`),- property("Tracks", String(snapshot.tracks.length), "property-number"),+ uiGroup("inspector.project", [+ property("inspector.author", snapshot.source.path, "property-code"),+ property("inspector.run", snapshot.run.path, "property-code"),+ property("inspector.sources", String(snapshot.source.files.length)),+ property("inspector.tracks", String(snapshot.tracks.length), "property-number"),]),- group("Canvas", [- property("Resolution", `${snapshot.space.canvasWidth} × ${snapshot.space.canvasHeight}`, "property-number"),- property("Aspect ratio", aspectRatio(snapshot.space.canvasWidth, snapshot.space.canvasHeight), "property-number"),+ uiGroup("inspector.canvas", [+ property("inspector.resolution", `${snapshot.space.canvasWidth} × ${snapshot.space.canvasHeight}`, "property-number"),+ property("inspector.aspect-ratio", aspectRatio(snapshot.space.canvasWidth, snapshot.space.canvasHeight), "property-number"),]),- group("Timeline", [- property("Duration", `${snapshot.space.durationSec.toFixed(2)} s`, "property-number"),- property("Frame rate", `${fps.toFixed(Number.isInteger(fps) ? 0 : 2)} fps`, "property-number"),- property("Frames", String(snapshot.space.frameCount), "property-number"),+ uiGroup("inspector.timeline", [+ property("inspector.duration", `${snapshot.space.durationSec.toFixed(2)} s`, "property-number"),+ property("inspector.frame-rate", `${fps.toFixed(Number.isInteger(fps) ? 0 : 2)} fps`, "property-number"),+ property("inspector.frames", String(snapshot.space.frameCount), "property-number"),]),- group("Build", [- property("Targets", snapshot.run.targets+ uiGroup("inspector.build", [+ property("inspector.targets", snapshot.run.targets.map((target) => target.split("::output::").at(-1) ?? target).join(", ") || "—", "property-code"),- property("Candidates", String(snapshot.run.satisfactions.length), "property-number"),+ property("inspector.candidates", String(snapshot.run.satisfactions.length), "property-number"),]),);return;@@ -855,7 +804,7 @@ function renderInspector(snapshot: StudioSnapshot, clipId: string | undefined):defaultWorkspaceHeading();const empty = document.createElement("div");empty.className = "inspector-empty";- empty.textContent = "No details for this selection";+ uiText(empty, "inspector.empty");inspector.replaceChildren(empty);return;}@@ -908,7 +857,7 @@ function renderSemanticInspector(snapshot: StudioSnapshot, segmentId: string): vdefaultWorkspaceHeading();const empty = document.createElement("div");empty.className = "inspector-empty";- empty.textContent = "No details for this selection";+ uiText(empty, "inspector.empty");inspector.replaceChildren(empty);}@@ -920,32 +869,36 @@ function semanticAnchorInspector(snapshot: StudioSnapshot, kind: "selection" | ".map((handle) => ({ clip, handle })));const current = kind === "selection" ? semantic?.selections.find((item) => item.id === id): semantic?.moments.find((item) => item.id === id);- if (!semantic || !current) return group("Timing", []);- const endpoints = "anchorId" in current ? [["Moment", current.anchorId]]- : [["Start", current.startAnchorId], ["End", current.endAnchorId]];- return group("Semantic anchors", endpoints.map(([label, anchorId]) => {+ if (!semantic || !current) return uiGroup("inspector.timing", []);+ const endpoints: readonly (readonly [Message, string])[] = "anchorId" in current ? [["inspector.moment", current.anchorId]]+ : [["inspector.start", current.startAnchorId], ["inspector.end", current.endAnchorId]];+ return uiGroup("inspector.semantic-anchors", endpoints.map(([label, anchorId]) => {const anchor = semantic.anchors.find((item) => item.id === anchorId)!;- const describe = (item: typeof anchor) => {+ const describe = (node: Element, item: typeof anchor) => {const word = semantic.tokens.find((token) => token.id === item.tokenId)?.text;- return `${item.kind.replaceAll("-", " ")}${word ? ` · ${word}` : ""}${item.segmentId ? ` · ${item.segmentId}` : ""}`;+ uiText(node, `inspector.anchor.${item.kind}`, { detail: `${word ? ` · ${word}` : ""}${item.segmentId ? ` · ${item.segmentId}` : ""}` });};const candidates = semantic.anchors.filter((item) => item.frame === anchor.frame).flatMap((item) => {const target: SemanticTarget = "anchorId" in current ? { kind: "moment", anchorId: item.id }- : { kind: "selection", startAnchorId: label === "Start" ? item.id : current.startAnchorId,- endAnchorId: label === "End" ? item.id : current.endAnchorId };+ : { kind: "selection", startAnchorId: label === "inspector.start" ? item.id : current.startAnchorId,+ endAnchorId: label === "inspector.end" ? item.id : current.endAnchorId };const owner = consumers.find(({ handle }) => semanticGestureSpan(semantic.anchors, handle, target) !== undefined);return owner ? [{ item, target, ...owner }] : [];});- if (candidates.length < 2) return property(label!, describe(anchor));+ if (candidates.length < 2) {+ const row = property(label!, "");+ describe(row.querySelector("strong")!, anchor);+ return row;+ }const row = document.createElement("label");row.className = "property";const name = document.createElement("span");- name.textContent = label!;+ uiText(name, label!);const control = document.createElement("select");control.className = "parameter-value";- control.setAttribute("aria-label", `${label} semantic anchor`);+ uiAttr(control, "aria-label", label === "inspector.start" ? "inspector.start-anchor" : label === "inspector.end" ? "inspector.end-anchor" : "inspector.moment-anchor");for (const { item } of candidates) {- const option = document.createElement("option"); option.value = item.id; option.textContent = describe(item);+ const option = document.createElement("option"); option.value = item.id; describe(option, item);control.append(option);}control.value = anchorId!;@@ -954,14 +907,14 @@ function semanticAnchorInspector(snapshot: StudioSnapshot, kind: "selection" | "const span = semanticGestureSpan(semantic.anchors, choice.handle, choice.target)!;const temporal = choice.handle.temporal!;control.disabled = true;- status.textContent = "Saving"; status.className = "status saving";+ uiText(status, "common.saving"); status.className = "status saving";void applyStudioMutation({ type: "timeline.adjust", revision: snapshot.revision,entityId: choice.clip.id, gesture: choice.handle.gesture,target: temporal.kind === "instant" ? { kind: "instant", frame: span.startFrame, semantic: choice.target }: { kind: "window", ...span, semantic: choice.target },- }).then(() => { status.textContent = "Saved"; status.className = "status saved"; })+ }).then(() => { uiText(status, "common.saved"); status.className = "status saved"; }).catch((error: unknown) => {- control.value = anchorId!; status.textContent = "Save failed"; status.className = "status error";+ control.value = anchorId!; uiText(status, "common.save-failed"); status.className = "status error";status.title = error instanceof Error ? error.message : String(error);}).finally(() => { control.disabled = false; });});@@ -1145,10 +1098,10 @@ window.addEventListener("keydown", (event) => {});function applySnapshot(snapshot: StudioSnapshot): void {- failureView.textContent = "";+ userText(failureView, "");status.className = "status";status.title = "";- status.textContent = "";+ userText(status, "");renderMeta(snapshot);library.show(snapshot);store.load(snapshot);@@ -1156,7 +1109,7 @@ function applySnapshot(snapshot: StudioSnapshot): void {function applyFailure(failure: StudioFailure): void {status.className = "status error";- status.textContent = "Compile failed";+ uiText(status, "common.compile-failed");failureView.textContent = failure.error;if (failure.range !== undefined) code.highlight([{ range: failure.range, tone: "element" }], true);// A parameter control changes immediately in the browser, but the sourcediff --git a/packages/studio/src/ui/scrub-preview.ts b/packages/studio/src/ui/scrub-preview.tsindex d40846b7..91f38f87 100644--- a/packages/studio/src/ui/scrub-preview.ts+++ b/packages/studio/src/ui/scrub-preview.ts@@ -1,3 +1,4 @@+import { uiAttr, uiText, t } from "./i18n.js";import type { StudioSnapshot } from "../shared.js";import { feedbackClock } from "../feedback.js";@@ -11,10 +12,11 @@ export function createScrubPreview(container: HTMLElement) {const element = document.createElement("div");element.className = "scrub-preview";element.hidden = true;- element.innerHTML = '<div class="scrub-preview-picture"><span>Loading frame…</span></div><div class="scrub-preview-time"></div>';+ element.innerHTML = '<div class="scrub-preview-picture"><span></span></div><div class="scrub-preview-time"></div>';element.setAttribute("aria-hidden", "true");const picture = element.querySelector<HTMLElement>(".scrub-preview-picture")!;const status = picture.querySelector<HTMLElement>("span")!;+ uiText(status, "player.frame-loading");const time = element.querySelector<HTMLElement>(".scrub-preview-time")!;container.append(element);let iframe: HTMLIFrameElement | undefined;@@ -34,7 +36,7 @@ export function createScrubPreview(container: HTMLElement) {const target = current.contentWindow as PreviewWindow | null;const placed = await target?.__hypitSeekFrame?.(frame);if (iframe !== current) return;- if (!placed) throw new Error("Frame unavailable");+ if (!placed) throw new Error(t("player.frame-unavailable"));displayed = frame;if (requested === frame) {current.style.visibility = "visible";@@ -43,7 +45,7 @@ export function createScrubPreview(container: HTMLElement) {}}} catch {- if (iframe === current) status.textContent = "Frame unavailable";+ if (iframe === current) uiText(status, "player.frame-unavailable");} finally {if (iframe === current) seeking = false;}@@ -65,7 +67,7 @@ export function createScrubPreview(container: HTMLElement) {picture.style.width = `${canvasWidth * scale}px`;picture.style.height = `${canvasHeight * scale}px`;const created = document.createElement("iframe");- created.title = "Hovered frame";+ uiAttr(created, "title", "player.hovered-frame");created.tabIndex = -1;created.setAttribute("sandbox", "allow-scripts allow-same-origin");created.setAttribute("allow", "autoplay 'none'");@@ -80,7 +82,7 @@ export function createScrubPreview(container: HTMLElement) {if (iframe !== created) return;ready = true;await seek();- })().catch(() => { if (iframe === created) status.textContent = "Frame unavailable"; });+ })().catch(() => { if (iframe === created) uiText(status, "player.frame-unavailable"); });});created.srcdoc = snapshot.preview.srcdoc;iframe = created;@@ -94,7 +96,7 @@ export function createScrubPreview(container: HTMLElement) {time.textContent = feedbackClock(frame * snapshot.space.frameRate.denominator / snapshot.space.frameRate.numerator);if (frame !== displayed) {iframe.style.visibility = "hidden";- status.textContent = "Loading frame…";+ uiText(status, "player.frame-loading");status.hidden = false;delete element.dataset.frame;} else {diff --git a/packages/studio/src/ui/stage.ts b/packages/studio/src/ui/stage.tsindex 71bb3cda..da393fa9 100644--- a/packages/studio/src/ui/stage.ts+++ b/packages/studio/src/ui/stage.ts@@ -1,3 +1,4 @@+import { uiLabel, uiAttribute, uiText, uiAttr, userText } from "./i18n.js";import { createArtifactPreview } from "./artifact-preview.js";import type { StudioArtifactView, StudioSnapshot } from "../shared.js";import { createOverlay } from "./overlay.js";@@ -31,31 +32,31 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefielement.className = "stage";element.innerHTML = `<div class="stage-heading">- <div class="stage-title">${icon("preview")}<strong>Preview</strong></div>- <button type="button" class="stage-return" hidden>Back to composition</button>+ <div class="stage-title">${icon("preview")}<strong>${uiLabel("player.preview")}</strong></div>+ <button type="button" class="stage-return" hidden>${uiLabel("player.back-to-composition")}</button></div><div class="stage-viewport"><div class="stage-scaler">- <iframe title="Preview" sandbox="allow-scripts allow-same-origin" allow="autoplay"></iframe>+ <iframe ${uiAttribute("title", "player.preview")} sandbox="allow-scripts allow-same-origin" allow="autoplay"></iframe></div></div><div class="stage-progress" hidden>- <input class="stage-scrubber" type="range" min="0" max="0" value="0" step="0.01" aria-label="Media time" hidden>+ <input class="stage-scrubber" type="range" min="0" max="0" value="0" step="0.01" ${uiAttribute("aria-label", "player.media-time")} hidden></div><div class="stage-bar"><span class="stage-time" hidden></span><div class="stage-transport">- <button type="button" data-previous aria-label="Previous frame" title="Previous frame">+ <button type="button" data-previous ${uiAttribute("aria-label", "player.previous-frame")} ${uiAttribute("title", "player.previous-frame")}>${icon("previous")}</button>- <button type="button" data-play aria-label="Play">+ <button type="button" data-play ${uiAttribute("aria-label", "player.play")}><span data-icon>${icon("play")}</span></button>- <button type="button" data-next aria-label="Next frame" title="Next frame">+ <button type="button" data-next ${uiAttribute("aria-label", "player.next-frame")} ${uiAttribute("title", "player.next-frame")}>${icon("next")}</button></div>- <button type="button" data-mute aria-label="Mute" class="stage-mute">+ <button type="button" data-mute ${uiAttribute("aria-label", "player.mute")} class="stage-mute"><span data-mute-icon>${icon("volume")}</span></button></div>`;@@ -124,7 +125,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefievent.preventDefault(); stop(); closeSelectionMenu();const menu = document.createElement("div");menu.className = "selection-menu";- menu.setAttribute("role", "menu"); menu.setAttribute("aria-label", "Elements at this point");+ menu.setAttribute("role", "menu"); uiAttr(menu, "aria-label", "player.elements-at-this-point");for (const hit of hits) {const option = document.createElement("button"); option.type = "button";option.setAttribute("role", "menuitem"); option.textContent = hit.display.title;@@ -204,7 +205,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undeficonst wasPlaying = playing;playing = false;setIcon(playIcon, "play");- play.setAttribute("aria-label", "Play");+ uiAttr(play, "aria-label", "player.play");if (raf !== 0) cancelAnimationFrame(raf);raf = 0;// Settle the picture on the frame the transport stopped at.@@ -219,7 +220,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefiif (playing) { stop(); return; }playing = true;setIcon(playIcon, "pause");- play.setAttribute("aria-label", "Pause");+ uiAttr(play, "aria-label", "player.pause");const total = state.snapshot.space.frameCount;const rate = fps(state.snapshot);fromFrame = state.playhead.frame >= total - 1 ? 0 : state.playhead.frame;@@ -245,7 +246,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undeficonst applyMuted = (): void => {setIcon(muteIcon, muted ? "muted" : "volume");- mute.setAttribute("aria-label", muted ? "Unmute" : "Mute");+ uiAttr(mute, "aria-label", muted ? "player.unmute" : "player.mute");if (artifactPreview.media !== undefined) artifactPreview.media.muted = muted;(iframe.contentWindow as SeekWindow | null)?.__hypitSetMuted?.(muted);};@@ -286,12 +287,12 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefiprevious.disabled = next.disabled = play.disabled;scrubber.disabled = duration <= 0;scrubber.step = "0.01";- scrubber.setAttribute("aria-label", "Media time");+ uiAttr(scrubber, "aria-label", "player.media-time");scrubber.max = String(duration);scrubber.value = String(media?.currentTime ?? 0);time.textContent = `${clock(media?.currentTime ?? 0)} / ${clock(duration)}`;setIcon(playIcon, media !== undefined && !media.paused ? "pause" : "play");- play.setAttribute("aria-label", media !== undefined && !media.paused ? "Pause" : "Play");+ uiAttr(play, "aria-label", media !== undefined && !media.paused ? "player.pause" : "player.play");});viewport.append(artifactPreview.element);const compositionTime = (): void => {@@ -302,7 +303,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefiscrubber.step = String(1 / rate);scrubber.max = String(Math.max(0, state.snapshot.space.frameCount - 1) / rate);scrubber.value = String(state.playhead.frame / rate);- scrubber.setAttribute("aria-label", "Composition time");+ uiAttr(scrubber, "aria-label", "player.composition-time");time.textContent = `${clock(state.playhead.frame / rate)} / ${clock(state.snapshot.space.frameCount / rate)}`;};scrubber.addEventListener("input", () => {@@ -318,14 +319,14 @@ export function createStage(store: Store, selectedArtifact: (id: string | undeficompositionTime();transport.hidden = mute.hidden = false;play.disabled = previous.disabled = next.disabled = false;- previous.title = "Previous frame";- previous.setAttribute("aria-label", previous.title);- next.title = "Next frame";- next.setAttribute("aria-label", next.title);- title.textContent = "Preview";+ uiAttr(previous, "title", "player.previous-frame");+ uiAttr(previous, "aria-label", "player.previous-frame");+ uiAttr(next, "title", "player.next-frame");+ uiAttr(next, "aria-label", "player.next-frame");+ uiText(title, "player.preview");title.removeAttribute("title");setIcon(playIcon, "play");- play.setAttribute("aria-label", "Play");+ uiAttr(play, "aria-label", "player.play");fit();if (state !== undefined && ready) seekPicture(state.playhead.frame);};@@ -335,12 +336,12 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefistop();scaler.hidden = true;back.hidden = false;- title.textContent = artifact.displayName ?? artifact.output;+ userText(title, artifact.displayName ?? artifact.output);title.title = artifact.output;- previous.title = "Back 5 seconds";- next.title = "Forward 5 seconds";- previous.setAttribute("aria-label", previous.title);- next.setAttribute("aria-label", next.title);+ uiAttr(previous, "title", "player.back-5-seconds");+ uiAttr(next, "title", "player.forward-5-seconds");+ uiAttr(previous, "aria-label", "player.back-5-seconds");+ uiAttr(next, "aria-label", "player.forward-5-seconds");artifactPreview.open(artifact, muted);selectedArtifact(artifact.id);};@@ -404,7 +405,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefishowComposition() { if (artifactPreview.selected !== undefined) returnToComposition(); },renameArtifact(artifact) {const selected = artifactPreview.selected;- if (selected?.build === artifact.build && selected.output === artifact.output) title.textContent = artifact.displayName ?? artifact.output;+ if (selected?.build === artifact.build && selected.output === artifact.output) userText(title, artifact.displayName ?? artifact.output);},};}diff --git a/packages/studio/src/ui/timeline.ts b/packages/studio/src/ui/timeline.tsindex 4095662e..fa02ac34 100644--- a/packages/studio/src/ui/timeline.ts+++ b/packages/studio/src/ui/timeline.ts@@ -1,3 +1,4 @@+import { userText, uiAttribute, uiText, uiAttr } from "./i18n.js";import type {SemanticToken,StudioSnapshot,@@ -89,13 +90,13 @@ export function createTimeline(store: Store): Timeline {element.innerHTML = `<div class="timeline-toolbar"><div class="timeline-tools">- <button type="button" class="tool-button active" aria-label="Select" title="Select">${icon("select")}</button>+ <button type="button" class="tool-button active" ${uiAttribute("aria-label", "timeline.select")} ${uiAttribute("title", "timeline.select")}>${icon("select")}</button></div><div class="timeline-time" data-timeline-time>00:00:00</div><div class="timeline-view-actions">- <button type="button" class="icon-button" data-zoom-out aria-label="Zoom out" title="Zoom out">${icon("minus")}</button>- <button type="button" class="icon-button" data-zoom-fit aria-label="Fit timeline" title="Fit timeline">${icon("fit")}</button>- <button type="button" class="icon-button" data-zoom-in aria-label="Zoom in" title="Zoom in">${icon("plus")}</button>+ <button type="button" class="icon-button" data-zoom-out ${uiAttribute("aria-label", "timeline.zoom-out")} ${uiAttribute("title", "timeline.zoom-out")}>${icon("minus")}</button>+ <button type="button" class="icon-button" data-zoom-fit ${uiAttribute("aria-label", "timeline.fit-timeline")} ${uiAttribute("title", "timeline.fit-timeline")}>${icon("fit")}</button>+ <button type="button" class="icon-button" data-zoom-in ${uiAttribute("aria-label", "timeline.zoom-in")} ${uiAttribute("title", "timeline.zoom-in")}>${icon("plus")}</button></div></div><div class="timeline-body" data-timeline-body>@@ -138,8 +139,8 @@ export function createTimeline(store: Store): Timeline {remember: "hypit-studio.v4.timeline-label-width",});labelHandle.classList.add("timeline-label-handle");- labelHandle.setAttribute("aria-label", "Resize timeline track labels");- labelHandle.title = "Resize track labels";+ uiAttr(labelHandle, "aria-label", "timeline.resize-timeline-track-labels");+ uiAttr(labelHandle, "title", "timeline.resize-track-labels");body.insertBefore(labelHandle, lanes);let state: State | undefined;@@ -501,12 +502,14 @@ export function createTimeline(store: Store): Timeline {];const laneHeight = bands.reduce((height, band) => height + band.height, itemMetrics.insetYPx * 2);const label = createTrackLabel(- presentation.label ?? "Timeline",+ presentation.label ?? "",presentation.tone,presentation.icon,- `${snapshot.semantic.segments.length} segment${snapshot.semantic.segments.length === 1 ? "" : "s"}`,+ "",laneHeight,);+ if (presentation.label === undefined) uiText(label.querySelector("strong")!, "inspector.timeline");+ uiAttr(label, "title", "timeline.segment-count", { count: snapshot.semantic.segments.length });label.classList.add("track-label-semantic");label.style.height = `calc(var(--timeline-ruler-height) + ${laneHeight}px)`;labels.append(label);@@ -529,7 +532,7 @@ export function createTimeline(store: Store): Timeline {band.className = `semantic-band semantic-band-${kind}`;band.style.top = `${bandTop}px`;band.style.setProperty("--semantic-band-height", `${height}px`);- band.setAttribute("aria-label", kind === "intent" ? "Selections and Moments" : kind === "word" ? "Words" : "Segments");+ uiAttr(band, "aria-label", kind === "intent" ? "timeline.selections-and-moments" : kind === "word" ? "timeline.words" : "timeline.segments");lane.append(band);bandTop += height;}@@ -546,7 +549,7 @@ export function createTimeline(store: Store): Timeline {node.className = "semantic-cell semantic-segment";node.tabIndex = 0;node.setAttribute("role", "button");- node.setAttribute("aria-label", `Segment ${segment.id}`);+ uiAttr(node, "aria-label", "timeline.segment-name", { name: segment.id });node.dataset.semanticSegment = segment.id;node.style.left = `${from * 100}%`;const segmentWidth = Math.max(0, to - from) * 100;@@ -626,7 +629,7 @@ export function createTimeline(store: Store): Timeline {node.type = "button";node.className = "semantic-cell semantic-selection";node.tabIndex = 0;- node.setAttribute("aria-label", `Selection ${selection.id}`);+ uiAttr(node, "aria-label", "timeline.selection-name", { name: selection.id });node.style.left = `${from * 100}%`;node.style.width = `max(2px, ${Math.max(0, to - from) * 100}%)`;node.title = selection.id;@@ -652,7 +655,7 @@ export function createTimeline(store: Store): Timeline {node.type = "button";node.className = "semantic-moment";node.tabIndex = 0;- node.setAttribute("aria-label", `Moment ${moment.id}`);+ uiAttr(node, "aria-label", "timeline.moment-name", { name: moment.id });node.style.left = `${at * 100}%`;node.title = moment.id;node.addEventListener("click", (event) => {@@ -674,7 +677,7 @@ export function createTimeline(store: Store): Timeline {const menu = document.createElement("div");menu.className = "timeline-overlap-menu";menu.setAttribute("role", "menu");- menu.setAttribute("aria-label", "Overlapping timeline objects");+ uiAttr(menu, "aria-label", "timeline.overlapping-timeline-objects");for (const hit of [...hits].reverse()) {const option = document.createElement("button");option.type = "button";@@ -835,7 +838,7 @@ export function createTimeline(store: Store): Timeline {semanticNodes = [];const corner = document.createElement("div");corner.className = "label-corner";- corner.textContent = "";+ userText(corner, "");if (snapshot.semantic === undefined || snapshot.semantic.segments.length === 0) labels.append(corner);buildSemanticLane(snapshot);const nextClipNodes: { node: HTMLElement; start: number; end: number; id: string; selectionGroup?: string }[] = [];diff --git a/packages/studio/start.ts b/packages/studio/start.tsindex 5b41bb37..81739f4b 100644--- a/packages/studio/start.ts+++ b/packages/studio/start.ts@@ -10,6 +10,14 @@ Open a Run in the browser to inspect its composition, Sources and Results.hypit studio --run <build.svrun> [--runtime <hypit.runtime.json>][--port <number>] [--workspace <directory>] [--package-root <directory>]+ [--locale-pack <./language.json | installed-package/language.json>]...++ hypit studio --check-locale <./language.json | installed-package/language.json>+ [--package-root <directory>]++Language packs are explicit JSON data. Relative files use the current directory;+package exports resolve from --package-root (the project by default).+--check-locale lists missing translations and unknown IDs without opening a Run.Relative command-line paths start at the current directory; --workspace selectsthe project, without rebasing those paths. Otherwise the nearest package.json@@ -24,9 +32,9 @@ function invalidArguments(message: string): never {throw new Error(`${message}. See hypit studio --help.`);}-function argumentsByName(argv: readonly string[]): ReadonlyMap<string, string> {- const accepted = new Set(["run", "runtime", "port", "workspace", "package-root"]);- const result = new Map<string, string>();+function argumentsByName(argv: readonly string[]): ReadonlyMap<string, readonly string[]> {+ const accepted = new Set(["run", "runtime", "port", "workspace", "package-root", "locale-pack", "check-locale"]);+ const result = new Map<string, string[]>();for (let index = 0; index < argv.length; index += 2) {const flag = argv[index];const value = argv[index + 1];@@ -35,7 +43,7 @@ function argumentsByName(argv: readonly string[]): ReadonlyMap<string, string> {}const name = flag.slice(2);if (!accepted.has(name)) invalidArguments(`Unknown option --${name}`);- result.set(name, value);+ result.set(name, [...result.get(name) ?? [], value]);}return result;}@@ -47,22 +55,12 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"}const values = argumentsByName(argv[0] === "--" ? argv.slice(1) : argv);const invokedFrom = process.env.INIT_CWD ?? process.cwd();- const runArgument = values.get("run");- if (runArgument === undefined || runArgument.trim().length === 0) invalidArguments("Missing --run");- const { createServer } = await import("vite");+ const runArgument = values.get("run")?.at(-1);+const { findRuntimeProfile, resolveProjectRoot } = await import("@hypit/project-context-node");- const { resolveDistributionPackageImport } = await import("@hypit/package-loader-node");- const { videoCliDistribution, videoStudioCompanionPackages } = await import("@hypit/video-cli");- const { openStudioBuildLibrary } = await import("./src/build-library.js");- const { loadStudioCompanionRegistry } = await import("./src/companion-assembly.js");- const { loadStudioDomain } = await import("./src/domain.js");- const { loadStudioRun } = await import("./src/run.js");- const { studioPlugin } = await import("./src/server.js");- const { studioFeedbackPlugin } = await import("./src/feedback-server.js");- const { inspectStudioRun } = await import("./src/studio-preflight.js");- const runPath = resolve(invokedFrom, runArgument);- const packageRootArgument = values.get("package-root");- const workspaceArgument = values.get("workspace");++ const packageRootArgument = values.get("package-root")?.at(-1);+ const workspaceArgument = values.get("workspace")?.at(-1);const requestedWorkspaceRoot = workspaceArgument === undefined? undefined: resolve(invokedFrom, workspaceArgument);@@ -73,7 +71,26 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"const packageRoot = packageRootArgument === undefined? workspaceRoot: resolve(invokedFrom, packageRootArgument);- const runtimeArgument = values.get("runtime");+ const { describeLanguagePack, loadLanguagePack, studioLanguages, studioLocalizationPlugin } = await import("./src/localization-node.js");+ const checkLocale = values.get("check-locale")?.at(-1);+ if (checkLocale !== undefined) {+ io.write(describeLanguagePack(await loadLanguagePack(checkLocale, invokedFrom, packageRoot)) + "\n");+ return;+ }+ if (runArgument === undefined || runArgument.trim().length === 0) invalidArguments("Missing --run");+ const runPath = resolve(invokedFrom, runArgument);+ const { createServer } = await import("vite");+ const { resolveDistributionPackageImport } = await import("@hypit/package-loader-node");+ const { videoCliDistribution, videoStudioCompanionPackages } = await import("@hypit/video-cli");+ const { openStudioBuildLibrary } = await import("./src/build-library.js");+ const { loadStudioCompanionRegistry } = await import("./src/companion-assembly.js");+ const { loadStudioDomain } = await import("./src/domain.js");+ const { loadStudioRun } = await import("./src/run.js");+ const { studioPlugin } = await import("./src/server.js");+ const { studioFeedbackPlugin } = await import("./src/feedback-server.js");+ const { inspectStudioRun } = await import("./src/studio-preflight.js");+ const languages = await studioLanguages(values.get("locale-pack") ?? [], invokedFrom, packageRoot);+ const runtimeArgument = values.get("runtime")?.at(-1);const selectedRuntime = runtimeArgument === undefined? await findRuntimeProfile(workspaceRoot): undefined;@@ -89,7 +106,7 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"...(packageRoot === workspaceRoot ? [] : [` Package root ${packageRoot}`]),"",].join("\n"));- const port = Number(values.get("port") ?? "5179");+ const port = Number(values.get("port")?.at(-1) ?? "5179");if (!Number.isSafeInteger(port) || port <= 0) invalidArguments("--port must be a positive integer");const distributionPackageRoot = videoCliDistribution.packageRoot ?? resolve(here, "../..");@@ -137,7 +154,7 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"// available for Source and material previews.fs: { allow: [workspaceRoot, packageRoot, distributionPackageRoot, here] },},- plugins: [distributionImports, studioFeedbackPlugin(workspaceRoot, runPath), studioPlugin({+ plugins: [distributionImports, studioLocalizationPlugin(languages), studioFeedbackPlugin(workspaceRoot, runPath), studioPlugin({source,runPath,workspaceRoot,diff --git a/packages/studio/test/localization.test.ts b/packages/studio/test/localization.test.tsnew file mode 100644index 00000000..837c7582--- /dev/null+++ b/packages/studio/test/localization.test.ts@@ -0,0 +1,55 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { builtinLanguages, chooseLanguage, defaultLanguage, formatMessage, languageCoverage, readLanguagePack } from "../src/localization.js";+import { loadLanguagePack, studioLanguages } from "../src/localization-node.js";++const japanese = { locale: "ja", name: "日本語", direction: "ltr", messages: { "app.studio": "スタジオ", "comments.placeholder": "どこを変更しますか?" } };++test("shipped languages use the same data format and cover every Studio message", () => {+ for (const pack of builtinLanguages) {+ assert.deepEqual(languageCoverage(readLanguagePack(pack)), { missing: [], unknown: [] });+ }+});+test("language choice handles regional variants and any explicitly loaded language", () => {+ const ja = readLanguagePack(japanese);+ const packs = [...builtinLanguages, ja];+ assert.equal(chooseLanguage(packs, ["ja-JP"]).locale, "ja");+ assert.equal(chooseLanguage(packs, ["zh"]).locale, "zh-CN");+ assert.equal(chooseLanguage(packs, ["de", "ja"]).locale, "ja");+ assert.equal(chooseLanguage(packs, ["de"]).locale, "en");+});+test("partial translations retain English wording and its plural rules", () => {+ const ja = readLanguagePack(japanese);+ assert.equal(formatMessage(ja, "app.studio"), "スタジオ");+ assert.equal(formatMessage(ja, "inspector.item-count", { count: 1 }), "1 item");+ assert.equal(formatMessage(ja, "inspector.item-count", { count: 2 }), "2 items");+ const ru = readLanguagePack({ locale: "ru", name: "Русский", direction: "ltr", messages: {+ "inspector.item-count": { one: "{count} элемент", few: "{count} элемента", many: "{count} элементов", other: "{count} элемента" },+ } });+ assert.equal(formatMessage(ru, "inspector.item-count", { count: 2 }), "2 элемента");+ assert.equal(formatMessage(ru, "inspector.item-count", { count: 5 }), "5 элементов");+ assert(languageCoverage(ja).missing.includes("player.play"));+});+test("a translated sentence may reorder variables but cannot silently rename them", () => {+ const valid = readLanguagePack({ ...japanese, messages: { "tasks.progress": "全 {total} 件のうち {completed} 件完了" } });+ assert.equal(formatMessage(valid, "tasks.progress", { total: 8, completed: 3 }), "全 8 件のうち 3 件完了");+ assert.throws(() => readLanguagePack({ ...japanese, messages: { "tasks.progress": "{done}/{total}" } }), /named variables/);+ assert.throws(() => readLanguagePack({ ...japanese, messages: { "inspector.item-count": { one: "{count}" } } }), /other/);+});+test("JSON files and installed package exports load without executing package code", async (t) => {+ const root = await mkdtemp(join(tmpdir(), "hypit-locales-"));+ t.after(() => rm(root, { recursive: true, force: true }));+ await writeFile(join(root, "ja.json"), JSON.stringify(japanese));+ const pkg = join(root, "node_modules", "studio-ja");+ await mkdir(pkg, { recursive: true });+ await writeFile(join(pkg, "package.json"), JSON.stringify({ name: "studio-ja", exports: { "./locale.json": "./ja.json" }, main: "./never-execute.cjs" }));+ await writeFile(join(pkg, "never-execute.cjs"), 'throw new Error("Translation packages must not execute code");');+ await writeFile(join(pkg, "ja.json"), JSON.stringify(japanese));+ assert.deepEqual(await loadLanguagePack("./ja.json", root, root), await loadLanguagePack("studio-ja/locale.json", root, root));+ const packs = await studioLanguages(["studio-ja/locale.json"], root, root);+ assert.equal(packs.length, builtinLanguages.length + 1);+ assert.equal(packs[0]?.locale, defaultLanguage.locale);+});diff --git a/skills/hypit/references/production/studio.md b/skills/hypit/references/production/studio.mdindex db06cb7c..dd011657 100644--- a/skills/hypit/references/production/studio.md+++ b/skills/hypit/references/production/studio.md@@ -1,6 +1,6 @@# Work in Studio-Read this when opening a Run, using its timeline and Inspector, or giving a project component a+Read this when opening a Run, choosing its interface language, using its timeline and Inspector, or giving a project component auseful Studio presentation. For component implementation, read [Companion authoring](studio-companions.md).[Review](review.md) owns the judgment made from the visible work;[Track authoring](track-authoring.md) owns the component's production behavior.@@ -36,6 +36,32 @@ Runtime or Result repository requires restarting that Studio session: those implselections are loaded at startup. A browser refresh alone does not reload the server-side modules.Stop only the relevant Studio process; stopping Studio does not cancel a submitted Build.+## Choose the interface language++The globe menu to the left of **Studio / Comments** changes the interface language. English and+Simplified Chinese are included. The first visit follows browser language preferences; later visits+remember the user's choice. Switching preserves the playhead, selection and comment draft. When+introducing the review, point out this menu if it helps the user work in their preferred language.+This choice affects Studio's interface, not the video's Script, captions or user comments;+component-owned names and Companion labels retain their authored text.++Additional languages are ordinary JSON data, loaded explicitly when opening Studio:++```bash+hypit studio --check-locale ./studio-ja.json+hypit studio --run build.svrun --locale-pack ./studio-ja.json+```++For a new translation, copy `packages/studio/locales/en.json` from the installed Distribution.+Set `locale`, the native language `name`, and `direction` (`ltr` or `rtl`); translate `messages`+while keeping their IDs and named variables such as `{count}`. Missing entries use English.+The check command reports missing entries, unknown IDs and invalid variables without opening a Run.+Relative file paths start at the command's working directory. Repeat `--locale-pack` for several+languages, or pass an installed package's JSON export instead, such as+`--locale-pack @your-scope/studio-ja/locale.json`. A local file is enough; sharing it as a package+is optional. Restart Studio to load changed language files. The installed+`packages/studio/LOCALIZATION.md` covers plural forms and JSON package exports.+## Discuss the work while composingWhen the user is collaborating locally, open the actual composition once a meaningful passage isdiff --git a/tsconfig.json b/tsconfig.jsonindex 57a069fa..f49219dc 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -11,6 +11,7 @@"noUncheckedIndexedAccess": true,"exactOptionalPropertyTypes": true,"verbatimModuleSyntax": true,+ "resolveJsonModule": true,"declaration": true,"sourceMap": true,"rootDir": ".",