diff --git a/.changeset/fine-jeans-beam.md b/.changeset/fine-jeans-beam.md new file mode 100644 index 000000000..e1c59f733 --- /dev/null +++ b/.changeset/fine-jeans-beam.md @@ -0,0 +1,5 @@ +--- +"globalonboard": patch +--- + +Harden onboarding pack export and task editing by escaping user content, converting edited template tasks to custom, and tightening UI defaults. diff --git a/community/global-onboard/README.md b/community/global-onboard/README.md new file mode 100644 index 000000000..82f42aa7c --- /dev/null +++ b/community/global-onboard/README.md @@ -0,0 +1,160 @@ +# GlobalOnboard · LingoHack25 ✨ + + + **One onboarding checklist. Any language. Fully Configurable** + HR writes once in English, and GlobalOnboard turns it into a polished, localized employee experience by combining **Lingo CLI**, **Lingo JavaScript SDK**, and **Lingo CI**. + + +## 🧠 The MAIN Pillars of GlobalOnboard + +- **Real personas:** HR Workspace (authoring) + Employee Experience (preview) wired together in real time. +- **Full Lingo toolchain:** Static JSON via CLI, runtime personalization via SDK, and CI automation so translations stay fresh. +- **Enterprise-ready touches:** Translation QA mode, localization health warnings, onboarding pack export, and translation spinners that prove we’re production aware. + +### 🏅 Lingo Product Scorecard + +| Lingo product | How GlobalOnboard uses it | Why it matters | + | --- | --- | --- | + | **Lingo CLI** | Generates `data/ui.{locale}.json` and `data/onboarding_template.{locale}.json` from English sources via `npx lingo.dev@latest run`. | Demonstrates the official static localization workflow. | + | **Lingo JavaScript SDK** | Translates the welcome note and every custom task at runtime with caching, spinners, and graceful fallbacks. | Shows dynamic personalization for each employee preview. | + | **Lingo CI** | `.github/workflows/i18n.yml` runs `npx lingo.dev@latest ci --pull-request` whenever English JSON or `i18n.json` changes. | Proves translation automation and GitHub integration end-to-end. | + +--- + +## 🔑 Feature Highlights + +| Area | What it unlocks | Lingo capability | +| --- | --- | --- | +| HR Workspace | Edit company, role, welcome note, and a fully dynamic checklist (add/delete/modify tasks). | Authoring surface for English source | +| Employee Experience | Switch between `en`, `es`, `fr`, `hi` previews with live updates + translation loading overlay. | CLI JSON + SDK runtime translations | +| Preview Modes | `Employee view` or `Translation QA` (side-by-side EN vs target locale) with Machine → Edited → Approved overrides. | Human-in-the-loop QA | +| Localization Health | Warns when translated copy is >1.5× English length, per task + summary. | QA signal | +| Onboarding Pack Export | One click generates a `.doc` bundle for the current locale (company, role, tasks, welcome note). | HR enablement | +| Lingo CI Workflow | GitHub Action auto-runs `lingo.dev ci` whenever English JSON changes. | Translation automation | + +--- + +## 🧩 Architecture At-a-Glance + +```text +HR inputs ──▶ English JSON templates ──▶ Lingo CLI generates data/ui.{locale}.json + │ │ + │ └─▶ Lingo CI keeps translations up to date + │ + ├─▶ React state + localStorage overrides + │ + └─▶ Lingo JS SDK + ├─ Welcome note runtime translation + └─ Custom task translations (per locale) + caching +``` + +--- + +## 🧪 Getting Started (Local Dev) + +```bash +git clone https://github.com/lingodotdev/lingo.dev.git +cd lingo.dev/community/global-onboard +npm install + +# Provide your API key so CLI + SDK can translate +export LINGO_DOT_DEV_API_KEY="your-key" +# Optional alias used by some shells/CLIs +export LINGODOTDEV_API_KEY="$LINGO_DOT_DEV_API_KEY" + +npm run dev +``` + +Visit **** — left panel is HR Workspace, right panel is the localized Employee preview. + +--- + +## 🌐 Localization Workflow Cheat Sheet + +### 1. Static JSON (Lingo CLI) +- Source files: `data/ui.en.json`, `data/onboarding_template.en.json` +- Configure targets in `i18n.json` +- Generate translations: + ```bash + export LINGO_DOT_DEV_API_KEY="your-key" + npx lingo.dev@latest run + ``` +- CI automation: `.github/workflows/i18n.yml` runs `npx lingo.dev@latest ci --pull-request` on every push to `main` touching English JSON or `i18n.json`. + +### 2. Runtime Personalization (Lingo JS SDK) +- Welcome note + any **custom tasks** run through `lib/lingo-client.ts`. +- We cache translations per locale, show a loading spinner overlay, and gracefully fall back to English if the SDK errors. + +### 3. Translation QA Mode +- Side-by-side English vs target locale. +- Inline editing with Machine → Edited → Approved chips. +- Reset/Unlock controls to manage overrides. +- Length-based warnings + summary so HR spots risky strings fast. +- Overrides feed every other view (single preview + export). + +--- + +## 📦 Onboarding Pack Export + +1. Choose a locale via the Employee panel dropdown. +2. Ensure QA overrides are final (Approved if needed). +3. Click **Download Onboarding Pack** → generates `onboarding-pack-.doc` with: + - Locale code + - Localized company + role + - Welcome note (SDK translation if non-English) + - Full task list using effective text (overrides or machine) + +Perfect for HRIS uploads, emails, or sharing with managers. + +--- + +## 🛠 Tech Stack + +- **Next.js 16** (App Router, TypeScript) +- **Tailwind CSS 4** (custom gradient + glassmorphism theme) +- **Lingo.dev CLI, JS SDK, CI** +- **next-themes** + custom design tokens for dark-first UI +- **GitHub Actions** for automated localization runs + +--- + +## 📁 Project Structure + +```text +app/ + layout.tsx # Root metadata + ThemeProvider + page.tsx # HR + Employee panels, QA, overrides, spinner + globals.css # Tailwind layers + design tokens +components/ + mode-toggle.tsx # Shadcn-style theme toggle (hidden by default) +data/ + ui.*.json # Static UI translations (CLI managed) + onboarding_template.*.json +lib/ + i18n.ts # Typed loaders for JSON bundles + lingo-client.ts # SDK setup + runtime translation helpers +.github/workflows/ + i18n.yml # CI job running `lingo.dev ci` +i18n.json # Bucket + locale configuration +``` + +--- + +## 🧾 Useful Scripts + +- `npm run dev` – Next.js dev server +- `npm run build` – Production build +- `npm run lint` – ESLint via `eslint-config-next` + +--- + +## ✅ Hackathon Compliance & Notes + +- All code, UI, and assets created fresh during **LingoHack25**. +- API keys are required only for translation features; none are checked into the repo. +- Want more locales? Add them to `SUPPORTED_LOCALES` + `i18n.json`, re-run the CLI, and you’re done. + +--- + +### 💬 Questions for Judges? +Open an issue or ping me — I'd love to show how GlobalOnboard can become the multilingual onboarding cockpit for any global company. diff --git a/community/global-onboard/app/api/translate/route.ts b/community/global-onboard/app/api/translate/route.ts new file mode 100644 index 000000000..3cbd8f430 --- /dev/null +++ b/community/global-onboard/app/api/translate/route.ts @@ -0,0 +1,47 @@ +import { NextResponse } from "next/server"; + +import { translateWithLingo } from "@/lib/lingo"; +import { SUPPORTED_LOCALES, type Locale } from "@/lib/i18n"; + +type TranslationPayload = { + text?: string; + targetLocale?: Locale; +}; + +const MAX_TEXT_LENGTH = 2000; + +export async function POST(request: Request) { + let payload: TranslationPayload; + + try { + payload = (await request.json()) as TranslationPayload; + } catch (error) { + console.error("Invalid translation payload", error); + return NextResponse.json({ error: "Invalid request body" }, { status: 400 }); + } + + const { text, targetLocale } = payload; + + if (!text || typeof text !== "string") { + return NextResponse.json({ error: "Missing welcome note" }, { status: 400 }); + } + + if (text.length > MAX_TEXT_LENGTH) { + return NextResponse.json({ error: "Welcome note is too long" }, { status: 413 }); + } + + if (!targetLocale || !SUPPORTED_LOCALES.includes(targetLocale)) { + return NextResponse.json({ error: "Unsupported locale" }, { status: 400 }); + } + + try { + const translated = await translateWithLingo(text, targetLocale); + return NextResponse.json({ translated }); + } catch (error) { + console.error("Lingo translation failed", error); + return NextResponse.json( + { error: "Unable to translate welcome note" }, + { status: 500 }, + ); + } +} diff --git a/community/global-onboard/app/favicon.ico b/community/global-onboard/app/favicon.ico new file mode 100644 index 000000000..718d6fea4 Binary files /dev/null and b/community/global-onboard/app/favicon.ico differ diff --git a/community/global-onboard/app/globals.css b/community/global-onboard/app/globals.css new file mode 100644 index 000000000..db2cd0738 --- /dev/null +++ b/community/global-onboard/app/globals.css @@ -0,0 +1,43 @@ +@import "tailwindcss"; + +@source "../app/**/*.{js,ts,jsx,tsx}"; +@source "../components/**/*.{js,ts,jsx,tsx}"; +@source "../lib/**/*.{js,ts,jsx,tsx}"; + +@custom-variant dark (&:where(.dark, .dark *)); + +:root { + --background: linear-gradient(135deg, #e3f2ff, #f9f1ff); + --foreground: #0f172a; + --muted: rgba(255, 255, 255, 0.8); + --muted-foreground: #475569; + --panel-start: #eef2ff; + --panel-end: #fdf2f8; +} + +.dark { + --background: linear-gradient(145deg, #05010c, #0f172a 55%, #1f2937); + --foreground: #f8fafc; + --muted: rgba(15, 23, 42, 0.85); + --muted-foreground: #94a3b8; + --panel-start: rgba(15, 23, 42, 0.9); + --panel-end: rgba(79, 70, 229, 0.35); +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --font-sans: "Inter", "Sohne", system-ui, -apple-system, blinkmacsystemfont, + "Segoe UI", sans-serif; + --font-mono: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, monospace; +} + +body { + background: var(--background); + color: var(--foreground); + font-family: var(--font-sans); + transition: color 0.3s ease; + background-attachment: fixed; +} diff --git a/community/global-onboard/app/icon.svg b/community/global-onboard/app/icon.svg new file mode 100644 index 000000000..514e579ed --- /dev/null +++ b/community/global-onboard/app/icon.svg @@ -0,0 +1,29 @@ + + GlobalOnboard logo + + + + + + + + + + + diff --git a/community/global-onboard/app/layout.tsx b/community/global-onboard/app/layout.tsx new file mode 100644 index 000000000..94aa12e64 --- /dev/null +++ b/community/global-onboard/app/layout.tsx @@ -0,0 +1,42 @@ +import type { Metadata } from "next"; +import "./globals.css"; +import { ThemeProvider } from "@/components/theme-provider"; +import { cn } from "@/lib/utils"; + +export const metadata: Metadata = { + title: "GlobalOnboard", + description: + "GlobalOnboard lets HR teams create one onboarding checklist and preview it in multiple languages via Lingo.dev.", + icons: { + icon: [ + { url: "/favicon.svg", type: "image/svg+xml" }, + { url: "/favicon.svg", rel: "alternate icon", type: "image/svg+xml" }, + ], + }, +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + + {children} + + + + ); +} diff --git a/community/global-onboard/app/page.tsx b/community/global-onboard/app/page.tsx new file mode 100644 index 000000000..b4f180f96 --- /dev/null +++ b/community/global-onboard/app/page.tsx @@ -0,0 +1,1376 @@ +"use client"; + +import { useEffect, useMemo, useRef, useState } from "react"; +import { + getTemplate, + getUi, + getLocaleLabel, + SUPPORTED_LOCALES, + type Locale, + type Task, +} from "@/lib/i18n"; +import { translateWelcomeNote } from "@/lib/lingo-client"; + +const DEFAULT_WELCOME = + "Welcome to the team! Use this space to celebrate new hires and explain how their work matters."; + +const HERO_HIGHLIGHTS = [ + "HR writes onboarding once in English.", + "Lingo CLI + CI auto-sync localized JSON.", + "Lingo SDK personalizes welcome notes live.", + "Download polished onboarding packs per locale instantly.", +]; +const LENGTH_ALERT_RATIO = 1.5; +const STATUS_LABELS: Record = { + machine: "Machine", + edited: "Edited", + approved: "Approved", +}; +const STATUS_STYLES: Record = { + machine: "bg-white/10 text-slate-200 dark:bg-slate-800 dark:text-slate-200", + edited: "bg-blue-500/20 text-blue-100 dark:bg-blue-500/30 dark:text-blue-100", + approved: "bg-emerald-500/20 text-emerald-100 dark:bg-emerald-500/30 dark:text-emerald-100", +}; +const LOGO_GRADIENT_ID = "globalonboard-logo-orbit"; + +const GlobalOnboardWordmark = () => ( +
+ + GlobalOnboard logo + + + + + + + + + + + +
+ Global + + Onboard + +
+
+); + +type WelcomeCacheEntry = { + source: string; + value: string; +}; + +type ViewMode = "single" | "qa"; + +type TranslationStatus = "machine" | "edited" | "approved"; + +type TranslatableFieldId = + | { type: "companyName" } + | { type: "role" } + | { type: "taskTitle"; taskId: string } + | { type: "taskDescription"; taskId: string }; + +type PrimaryField = "companyName" | "role"; + +type TranslationOverride = { + text: string; + status: TranslationStatus; +}; + +type OverridesState = Partial>>; + +const storageKey = "globalonboard_overrides_v1"; +const LOCALE_BADGE_LABELS: Record = { + en: "English (en)", + es: "Spanish (es)", + fr: "French (fr)", + hi: "Hindi (hi)", +}; +type TaskSource = "template" | "custom"; +type HrTask = Task & { source: TaskSource }; +type CustomTranslationCache = Partial< + Record< + Locale, + Record< + string, + { + title?: string; + description?: string; + titleSource?: string; + descriptionSource?: string; + } + > + > +>; + +function buildFieldKey(field: TranslatableFieldId) { + switch (field.type) { + case "companyName": + return "companyName"; + case "role": + return "role"; + case "taskTitle": + return `task:${field.taskId}:title`; + case "taskDescription": + return `task:${field.taskId}:description`; + default: + return ""; + } +} + +export default function Home() { + const hrStrings = getUi("en"); + const englishTemplate = getTemplate("en"); + const defaultCompanyName = englishTemplate.companyName; + const defaultRole = englishTemplate.role; + + const [companyName, setCompanyName] = useState(defaultCompanyName); + const [role, setRole] = useState(defaultRole); + const [tasks, setTasks] = useState( + () => + englishTemplate.tasks.map((task) => ({ + ...task, + source: "template" as const, + })) as HrTask[], + ); + const [welcomeNote, setWelcomeNote] = useState(DEFAULT_WELCOME); + const [selectedLocale, setSelectedLocale] = useState("en"); + const [translatedWelcome, setTranslatedWelcome] = useState(DEFAULT_WELCOME); + const [isTranslating, setIsTranslating] = useState(false); + const [translationError, setTranslationError] = useState(false); + const [viewMode, setViewMode] = useState("single"); + const [overrides, setOverrides] = useState(() => { + if (typeof window === "undefined") { + return {}; + } + try { + const saved = window.localStorage.getItem(storageKey); + if (saved) { + return JSON.parse(saved) as OverridesState; + } + } catch (error) { + console.warn("Failed to load overrides", error); + } + return {}; + }); + const welcomeCache = useRef>>({}); + const [customTranslations, setCustomTranslations] = useState({}); + const pendingCustomTranslations = useRef>(new Set()); + const [fieldTranslations, setFieldTranslations] = useState< + Partial>>> + >({}); + const pendingFieldTranslations = useRef>(new Set()); + const [translationCount, setTranslationCount] = useState(0); + + useEffect(() => { + if (typeof window === "undefined") return; + try { + window.localStorage.setItem(storageKey, JSON.stringify(overrides)); + } catch (error) { + console.warn("Failed to persist overrides", error); + } + }, [overrides]); + + const updateOverride = (locale: Locale, fieldKey: string, override: TranslationOverride | null) => { + setOverrides((prev) => { + const next = { ...prev }; + const localeOverrides = { ...(next[locale] ?? {}) }; + + if (!override) { + delete localeOverrides[fieldKey]; + } else { + localeOverrides[fieldKey] = override; + } + + if (Object.keys(localeOverrides).length === 0) { + delete next[locale]; + } else { + next[locale] = localeOverrides; + } + + return next; + }); + }; + + const getOverrideForField = (locale: Locale, fieldKey: string) => { + return overrides[locale]?.[fieldKey]; + }; + + const getStatusForField = (locale: Locale, fieldKey: string): TranslationStatus => { + return getOverrideForField(locale, fieldKey)?.status ?? "machine"; + }; + + const clearCustomTranslationsForTask = (taskId: string) => { + setCustomTranslations((prev) => { + const next = { ...prev }; + SUPPORTED_LOCALES.forEach((locale) => { + const localeMap = next[locale]; + if (!localeMap) return; + if (localeMap[taskId]) { + const updated = { ...localeMap }; + delete updated[taskId]; + next[locale] = updated; + } + }); + return next; + }); + }; + + const removeTaskOverrides = (taskId: string) => { + setOverrides((prev) => { + const next = { ...prev }; + SUPPORTED_LOCALES.forEach((locale) => { + const localeOverrides = next[locale]; + if (!localeOverrides) return; + const updated = { ...localeOverrides }; + delete updated[buildFieldKey({ type: "taskTitle", taskId })]; + delete updated[buildFieldKey({ type: "taskDescription", taskId })]; + if (Object.keys(updated).length === 0) { + delete next[locale]; + } else { + next[locale] = updated; + } + }); + return next; + }); + }; + + const startTranslationJob = () => { + setTranslationCount((count) => count + 1); + }; + + const finishTranslationJob = () => { + setTranslationCount((count) => Math.max(0, count - 1)); + }; + + const previewStrings = useMemo(() => getUi(selectedLocale), [selectedLocale]); + const previewTemplate = useMemo(() => { + if (selectedLocale === "en") { + return { companyName, role, tasks }; + } + + const localizedTemplate = getTemplate(selectedLocale); + const templateTasksById = localizedTemplate.tasks.reduce>((acc, task) => { + acc[task.id] = task; + return acc; + }, {}); + const localeCustomTranslations = customTranslations[selectedLocale] ?? {}; + const localeFieldCache = fieldTranslations[selectedLocale] ?? {}; + const resolveField = ( + field: PrimaryField, + englishValue: string, + localizedValue: string, + ) => { + const trimmedValue = englishValue.trim(); + if (!trimmedValue) { + return ""; + } + + const defaultValue = field === "companyName" ? defaultCompanyName : defaultRole; + if (trimmedValue === defaultValue.trim()) { + return localizedValue; + } + + const cached = localeFieldCache[field]; + if (cached?.source === englishValue) { + return cached.value; + } + + return englishValue; + }; + + return { + companyName: resolveField("companyName", companyName, localizedTemplate.companyName), + role: resolveField("role", role, localizedTemplate.role), + tasks: tasks.map((task) => { + if (task.source === "template") { + return ( + templateTasksById[task.id] ?? { + id: task.id, + title: task.title, + description: task.description, + } + ); + } + + const cache = localeCustomTranslations[task.id]; + const cachedTitle = cache?.titleSource === task.title ? cache.title : undefined; + const cachedDescription = + cache?.descriptionSource === task.description ? cache.description : undefined; + return { + id: task.id, + title: cachedTitle ?? task.title, + description: cachedDescription ?? task.description, + }; + }), + }; + }, [ + companyName, + customTranslations, + defaultCompanyName, + defaultRole, + fieldTranslations, + role, + selectedLocale, + tasks, + ]); + const effectiveTemplate = useMemo(() => { + if (selectedLocale === "en") { + return previewTemplate; + } + + const localeOverrides = overrides[selectedLocale] ?? {}; + const getText = (fieldKey: string, fallback: string) => + localeOverrides[fieldKey]?.text ?? fallback; + + return { + companyName: getText(buildFieldKey({ type: "companyName" }), previewTemplate.companyName), + role: getText(buildFieldKey({ type: "role" }), previewTemplate.role), + tasks: previewTemplate.tasks.map((task) => ({ + ...task, + title: getText(buildFieldKey({ type: "taskTitle", taskId: task.id }), task.title), + description: getText( + buildFieldKey({ type: "taskDescription", taskId: task.id }), + task.description, + ), + })), + }; + }, [overrides, previewTemplate, selectedLocale]); + + useEffect(() => { + if (selectedLocale === "en") return; + tasks.forEach((task) => { + if (task.source === "template") return; + const trimmedTitle = task.title.trim(); + const trimmedDescription = task.description.trim(); + if (!trimmedTitle && !trimmedDescription) return; + + const localeCache = customTranslations[selectedLocale] ?? {}; + const cached = localeCache[task.id]; + const cachedTitle = cached?.titleSource === task.title ? cached.title : undefined; + const cachedDescription = + cached?.descriptionSource === task.description ? cached.description : undefined; + const needsTitle = trimmedTitle.length > 0 && !cachedTitle; + const needsDescription = trimmedDescription.length > 0 && !cachedDescription; + if (!needsTitle && !needsDescription) return; + + const key = `${selectedLocale}-${task.id}`; + if (pendingCustomTranslations.current.has(key)) return; + pendingCustomTranslations.current.add(key); + + startTranslationJob(); + (async () => { + try { + const [titleTranslation, descriptionTranslation] = await Promise.all([ + needsTitle + ? translateWelcomeNote(task.title, selectedLocale) + : Promise.resolve(cachedTitle ?? ""), + needsDescription + ? translateWelcomeNote(task.description, selectedLocale) + : Promise.resolve(cachedDescription ?? ""), + ]); + setCustomTranslations((prev) => { + const localeMap = { ...(prev[selectedLocale] ?? {}) }; + const existing = localeMap[task.id] ?? {}; + const nextTitle = + needsTitle + ? titleTranslation + : existing.titleSource === task.title + ? existing.title + : undefined; + const nextDescription = + needsDescription + ? descriptionTranslation + : existing.descriptionSource === task.description + ? existing.description + : undefined; + const nextEntry = { + ...(nextTitle ? { title: nextTitle, titleSource: task.title } : {}), + ...(nextDescription + ? { description: nextDescription, descriptionSource: task.description } + : {}), + }; + + if (Object.keys(nextEntry).length === 0) { + delete localeMap[task.id]; + } else { + localeMap[task.id] = { + ...existing, + ...nextEntry, + }; + } + return { ...prev, [selectedLocale]: localeMap }; + }); + } catch (error) { + console.error("Failed to translate custom task", error); + } finally { + pendingCustomTranslations.current.delete(key); + finishTranslationJob(); + } + })(); + }); + }, [customTranslations, selectedLocale, tasks]); + + useEffect(() => { + if (selectedLocale === "en") return; + + const locale = selectedLocale; + const localeCache = fieldTranslations[locale] ?? {}; + ( ["companyName", "role"] as PrimaryField[] ).forEach((field) => { + const value = field === "companyName" ? companyName : role; + const trimmedValue = value.trim(); + if (!trimmedValue) { + return; + } + + const defaultValue = field === "companyName" ? defaultCompanyName : defaultRole; + if (trimmedValue === defaultValue.trim()) { + return; + } + + const cached = localeCache[field]; + if (cached?.source === value) { + return; + } + + const key = `${locale}-${field}`; + if (pendingFieldTranslations.current.has(key)) { + return; + } + pendingFieldTranslations.current.add(key); + + startTranslationJob(); + translateWelcomeNote(value, locale) + .then((result) => { + setFieldTranslations((prev) => { + const localeEntries = { ...(prev[locale] ?? {}) }; + localeEntries[field] = { + source: value, + value: result, + }; + return { ...prev, [locale]: localeEntries }; + }); + }) + .catch((error) => { + console.error(`Failed to translate ${field}`, error); + }) + .finally(() => { + pendingFieldTranslations.current.delete(key); + finishTranslationJob(); + }); + }); + }, [companyName, defaultCompanyName, defaultRole, fieldTranslations, role, selectedLocale]); + + const shouldTranslate = + selectedLocale !== "en" && welcomeNote.trim().length > 0; + + useEffect(() => { + if (!shouldTranslate) { + setIsTranslating(false); + return; + } + + let cancelled = false; + const cached = welcomeCache.current[selectedLocale]; + if (cached && cached.source === welcomeNote) { + setTranslatedWelcome(cached.value); + setIsTranslating(false); + return; + } + + setIsTranslating(true); + setTranslationError(false); + startTranslationJob(); + translateWelcomeNote(welcomeNote, selectedLocale) + .then((result) => { + if (cancelled) return; + + welcomeCache.current[selectedLocale] = { + source: welcomeNote, + value: result, + }; + setTranslatedWelcome(result); + }) + .catch(() => { + if (cancelled) return; + setTranslationError(true); + setTranslatedWelcome(welcomeNote); + }) + .finally(() => { + if (!cancelled) { + setIsTranslating(false); + } + finishTranslationJob(); + }); + + return () => { + cancelled = true; + }; + }, [selectedLocale, shouldTranslate, welcomeNote]); + + const previewWelcome = + shouldTranslate && !translationError ? translatedWelcome : welcomeNote; + + const qaComparisons = useMemo(() => { + if (selectedLocale === "en") { + return []; + } + + const localeOverrides = overrides[selectedLocale] ?? {}; + const machineTaskMap = new Map(previewTemplate.tasks.map((task) => [task.id, task])); + + return tasks.map((task) => { + const machineTask = + machineTaskMap.get(task.id) ?? { + id: task.id, + title: task.title, + description: task.description, + }; + const effectiveTask = + effectiveTemplate.tasks.find((t) => t.id === task.id) ?? machineTask; + + const titleKey = buildFieldKey({ type: "taskTitle", taskId: task.id }); + const descriptionKey = buildFieldKey({ type: "taskDescription", taskId: task.id }); + const titleStatus = localeOverrides[titleKey]?.status ?? "machine"; + const descriptionStatus = localeOverrides[descriptionKey]?.status ?? "machine"; + + const titleRatio = + task.title.length > 0 + ? effectiveTask.title.length / task.title.length + : 1; + const descriptionRatio = + task.description.length > 0 + ? effectiveTask.description.length / task.description.length + : 1; + + const titleNeedsReview = titleRatio > LENGTH_ALERT_RATIO; + const descriptionNeedsReview = descriptionRatio > LENGTH_ALERT_RATIO; + + return { + id: task.id, + english: task, + machine: machineTask, + target: effectiveTask, + titleStatus, + descriptionStatus, + titleNeedsReview, + descriptionNeedsReview, + titleKey, + descriptionKey, + }; + }); + }, [effectiveTemplate, overrides, previewTemplate, selectedLocale, tasks]); + + const qaIssues = qaComparisons.filter( + (comparison) => comparison.titleNeedsReview || comparison.descriptionNeedsReview, + ).length; + const localeLabel = getLocaleLabel(selectedLocale); + const isQaMode = viewMode === "qa"; + const companyFieldKey = buildFieldKey({ type: "companyName" }); + const roleFieldKey = buildFieldKey({ type: "role" }); + const companyStatus = getStatusForField(selectedLocale, companyFieldKey); + const roleStatus = getStatusForField(selectedLocale, roleFieldKey); + const statusBadgeClass = (status: TranslationStatus) => + `inline-flex items-center rounded-full border border-white/10 px-2 py-0.5 text-xs font-semibold ${STATUS_STYLES[status]} dark:border-slate-700`; + const warningBadgeClass = + "inline-flex items-center gap-1 rounded-full border border-amber-400/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-100"; + const hasTranslationsInFlight = translationCount > 0; + const readableLocaleName = LOCALE_BADGE_LABELS[selectedLocale] ?? selectedLocale; + + const handleTaskChange = (index: number, field: "title" | "description", value: string) => { + const currentTask = tasks[index]; + setTasks((prev) => { + const next = [...prev]; + next[index] = { + ...next[index], + [field]: value, + ...(currentTask?.source === "template" ? { source: "custom" } : {}), + }; + return next; + }); + if (currentTask && currentTask[field] !== value) { + clearCustomTranslationsForTask(currentTask.id); + removeTaskOverrides(currentTask.id); + } + }; + + const handleAddTask = () => { + const newId = + typeof crypto !== "undefined" && crypto.randomUUID + ? crypto.randomUUID() + : `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`; + setTasks((prev) => [ + ...prev, + { + id: `custom-${newId}`, + title: "", + description: "", + source: "custom", + }, + ]); + }; + + const handleDeleteTask = (taskId: string) => { + setTasks((prev) => prev.filter((task) => task.id !== taskId)); + clearCustomTranslationsForTask(taskId); + removeTaskOverrides(taskId); + }; + + const handleTargetFieldChange = (fieldKey: string, machineText: string, value: string) => { + if (selectedLocale === "en") return; + const current = getOverrideForField(selectedLocale, fieldKey); + if (current?.status === "approved") { + return; + } + + if (value === machineText) { + updateOverride(selectedLocale, fieldKey, null); + return; + } + + updateOverride(selectedLocale, fieldKey, { + text: value, + status: "edited", + }); + }; + + const handleResetField = (fieldKey: string) => { + if (selectedLocale === "en") return; + const current = getOverrideForField(selectedLocale, fieldKey); + if (current?.status === "approved") return; + updateOverride(selectedLocale, fieldKey, null); + }; + + const handleApproveField = (fieldKey: string, effectiveText: string) => { + if (selectedLocale === "en") return; + updateOverride(selectedLocale, fieldKey, { + text: effectiveText, + status: "approved", + }); + }; + + const handleUnlockField = (fieldKey: string) => { + if (selectedLocale === "en") return; + const current = getOverrideForField(selectedLocale, fieldKey); + if (!current) return; + updateOverride(selectedLocale, fieldKey, { + text: current.text, + status: "edited", + }); + }; + + const escapeHtml = (value: string) => + value.replace(/[&<>"']/g, (char) => { + switch (char) { + case "&": + return "&"; + case "<": + return "<"; + case ">": + return ">"; + case '"': + return """; + case "'": + return "'"; + default: + return char; + } + }); + + const handleDownloadPack = () => { + const docWelcome = escapeHtml(selectedLocale === "en" ? welcomeNote : previewWelcome); + const docLocaleLabel = escapeHtml(localeLabel); + const docLocaleCode = escapeHtml(selectedLocale); + const docCompanyName = escapeHtml(effectiveTemplate.companyName); + const docRole = escapeHtml(effectiveTemplate.role); + const docTasks = effectiveTemplate.tasks + .map((task, index) => { + const taskTitle = escapeHtml(task.title); + const taskDescription = escapeHtml(task.description); + return `

Task ${index + 1}: ${taskTitle}
${taskDescription}

`; + }) + .join(""); + + const docHtml = ` + + + + Onboarding Pack - ${docLocaleLabel} + + + +

Onboarding Pack – ${docLocaleLabel}

+

Locale: ${docLocaleCode}

+

Company: ${docCompanyName}

+

Role: ${docRole}

+

Welcome Note

+

${docWelcome}

+

Onboarding Checklist

+ ${docTasks} + + `; + + const blob = new Blob([docHtml], { + type: "application/msword", + }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = `onboarding-pack-${selectedLocale}.doc`; + link.click(); + setTimeout(() => URL.revokeObjectURL(url), 0); + }; + + return ( +
+
+
+
+
+
+ +
+
+
+
+
+ +
+

{hrStrings["app.title"]}

+

+ LingoHack25 showcase +

+

+ {hrStrings["app.subtitle"]} +

+

+ GlobalOnboard combines Lingo CLI, SDK, and CI so HR can design one onboarding flow + and preview it for employees in any language. +

+
+
+
    + {HERO_HIGHLIGHTS.map((item) => ( +
  • + + {item} +
  • + ))} +
+
+ +
+
+
+
+
+

+ HR Workspace +

+

+ Configure the onboarding journey for this role. +

+
+ + 👤 HR / People Ops + +
+
+

{hrStrings["field.base_language"]}

+

+ {hrStrings["field.base_language_value"]} +

+
+
+ +
+
+ + setCompanyName(event.target.value)} + /> +
+ +
+ + setRole(event.target.value)} + /> +
+ +
+
+ +

+ {hrStrings["section.template"]} +

+
+

+ These are the steps your new hire will see. Add, edit, or remove items to fit this role. +

+ +
+ {tasks.map((task, index) => ( +
+
+ {task.source === "template" ? "Template task" : "Custom task"} + +
+
+ + handleTaskChange(index, "title", event.target.value) + } + /> +