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();