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