Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 嵌入 網頁版
語言: 客家話

網站小工具

這頁係對英文翻譯過來个。若係兩片無共樣,以英文頁為準。 看英文頁

在網站頂高,Lingara 係用一隻自訂元素 <lingara-embed> 來行。這隻元素在一隻由 Lingara 提供个框架肚畫出 Lingara 个練習,所以你个網頁永遠看毋到學習者个資料,Lingara 个網頁也永遠看毋到你个。

掛上元素

從 npm 安裝 @lingara/embed,抑係你个網站若係無打包工具,就從 CDN 載入佢个模組版本。過後將 <lingara-embed> 放在網頁頂高,再將佢定義。這隻元素接受:

  • plan-id,愛練習个課程計畫,愛係玩家擁有个;
  • surface,愛顯示麼个:practice,係預設值,也係唯一个畫面;
  • theme,light、dark 抑係 auto 其中一隻;
  • locale,框架自家个文字个語言,若係無設定就跈學習者;
  • title,框架个無障礙名稱。

樣式淨到主題為止。你个網頁無辦法伸入框架肚,主題就係佢提供个唯一設定。

分佢權杖

將元素个 tokenProvider 設做一隻函式,這隻函式會去問你自家个伺服器討權杖。你个伺服器用一隻伺服器套件,配網頁个來源簽發權杖,再用權杖摎佢个到期時間來回應。元素透過訊息將權杖交分框架,權杖永遠毋會經過 URL。

在為小工具行个每隻來源簽發權杖以前,先在控制台你用戶端个設定肚將佢兜註冊。伺服器套件頁面有講仰般做。API 會拒絕為其他來源簽發个權杖,框架就會顯示錯誤,毋係練習。

伺服器套件也做得同你寫出歸段程式碼,元素摎權杖提供者共下,若係你个內容安全政策需要,也會帶你網頁个指令碼 nonce。下背最尾个範例有展示。

聽框架講麼个

框架透過一隻有版本个訊息協定摎元素溝通,元素會將你个網頁需要个東西轉做 DOM 事件:

  • lingara:practice-completed,學習者完成一組个時節,帶佢个 planId、setNumber、correct 摎 total;
  • lingara:error,框架停下來个時節,帶一隻 code 摎 retryable。做得重試个錯誤表示重新掛一擺可能會成功;麼个時節再試,由你決定。

練習个結果也會到你个伺服器,照練習結果个說明。

npm install @lingara/embed@0.1.0-alpha.6
# No bundler? One module script instead:
# <script type="module" src="https://cdn.jsdelivr.net/npm/@lingara/embed@0.1.0-alpha.6/dist/lingara-embed.min.js"></script>
<!-- plan-id is a lesson plan your server made for this player. -->
<lingara-embed surface="practice" plan-id="0b9d4f2e-3c1a-4e8b-9f6d-2a7c5e1b8d40" theme="auto" title="Practice"></lingara-embed>
<script type="module">
  import { defineLingaraEmbed } from '@lingara/embed'
  defineLingaraEmbed()
</script>
// Your own endpoint, on your own server. It mints with this page's origin and
// returns exactly { token, expires_at }: the token (lgr_et_…) never touches a URL.
widget.tokenProvider = async () => {
  const response = await fetch('/lingara/token', { method: 'POST', credentials: 'same-origin' })
  if (!response.ok) throw new Error(`token endpoint answered ${response.status}`)
  return response.json()
}
widget.addEventListener('lingara:practice-completed', (event) => {
  const { planId, setNumber, correct, total } = (event as CustomEvent).detail
  console.log(`set ${setNumber} of ${planId}: ${correct}/${total}`)
})
widget.addEventListener('lingara:error', (event) => {
  const { code, retryable } = (event as CustomEvent).detail
  // `retryable` means a remount may succeed; when to try is yours to decide.
  if (retryable) setTimeout(() => widget.reload(), 30_000)
  else console.warn('Lingara practice stopped:', code)
})
程式碼範例个語言

TypeScript

// The page that mounts the widget: the token never appears in it.
export function practicePage(planId: string, cspNonce: string): string {
  const widget = widgetSnippet({ planId, tokenEndpoint: '/lingara/token', theme: 'auto', locale: 'fr', title: 'Pratique', nonce: cspNonce })
  return `<!doctype html><title>Practice</title>${widget}`
}

Rust

// The element, its script build and a token provider that POSTs to your
// token route. The token never appears in the markup.
let html = widget_snippet(&SnippetOptions {
    locale: Some("fr".into()),
    nonce: Some(csp_nonce.into()), // your page's CSP nonce, for a strict script-src
    ..SnippetOptions::new(plan_id, "/lingara/token")
})?;

Go

// The plan your server made for this player, and the token route above.
// Pass the request's CSP nonce when your script-src allows no inline
// script; the token itself never appears in the markup.
theme := "auto"
html, err := lingaraembed.WidgetSnippet(lingaraembed.SnippetOptions{
	PlanID:        planID,
	TokenEndpoint: "/lingara/token",
	Theme:         &theme,
	Nonce:         &cspNonce,
})
if err != nil {
	return "", err // a *lingaraembed.SnippetError names the refused option
}
return template.HTML(html), nil // already escaped by the kit

Java

// planId is the lesson plan your server made for this player. The element
// POSTs to tokenEndpoint with same-origin cookies: the token never appears
// in the markup. Pass this request's CSP nonce if your page sets one.
String html =
    WidgetSnippet.render(
        SnippetOptions.builder(planId, "/lingara/token").locale("fr").nonce(cspNonce).build());

Kotlin

// planId is the lesson plan your server made for this player. The element
// POSTs to tokenEndpoint with same-origin cookies: the token never appears
// in the markup. Pass this request's CSP nonce if your page sets one.
val html =
    widgetSnippet(
        SnippetOptions(planId, tokenEndpoint = "/lingara/token").apply {
            locale = "fr"
            nonce = cspNonce
        },
    )

Ruby

# The plan your server made for this player, rendered into your page.
# nonce: your page's CSP nonce, when its script-src allows no inline script.
def self.widget(plan_id, csp_nonce)
  Lingara::Embed.widget_snippet(plan_id: plan_id, token_endpoint: "/lingara/token", locale: "fr", nonce: csp_nonce)
end

PHP

use Lingara\Embed\SnippetOptions;
use Lingara\Embed\WidgetSnippet;

// In your page's template: the plan your server made for this player, and
// your token route. Pass the request's CSP nonce if your script-src allows
// no inline script. A bad option throws SnippetException naming its field.
function practiceWidget(string $planId, string $cspNonce): string
{
    return WidgetSnippet::render(new SnippetOptions(
        planId: $planId,
        tokenEndpoint: '/lingara/token',
        theme: 'auto',
        nonce: $cspNonce,
    ));
}

C#

app.MapGet("/practice/{planId}", (string planId, HttpContext http) =>
{
    var widget = WidgetSnippet.Render(new SnippetOptions
    {
        PlanId = planId,                              // the plan your server made for this player
        TokenEndpoint = "/lingara/token",             // same origin: the element sends this page's cookies
        Nonce = http.Items["csp-nonce"] as string,     // your CSP's nonce, if script-src has one
    });
    return Results.Content($"<!doctype html><title>Practice</title>\n{widget}", "text/html");
}).RequireAuthorization();