collavre_translation 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/README.md +83 -0
- data/app/controllers/collavre_translation/creative_translations_controller.rb +48 -0
- data/app/controllers/collavre_translation/translations_controller.rb +52 -0
- data/app/controllers/concerns/collavre_translation/translation_locale.rb +9 -0
- data/app/javascript/collavre_translation.js +1 -0
- data/app/javascript/controllers/__tests__/comment_translation_controller.test.js +377 -0
- data/app/javascript/controllers/__tests__/comment_translation_reader_controller.test.js +106 -0
- data/app/javascript/controllers/__tests__/creative_translations_controller.test.js +667 -0
- data/app/javascript/controllers/__tests__/translation_locale.test.js +14 -0
- data/app/javascript/controllers/__tests__/translation_preference_controller.test.js +29 -0
- data/app/javascript/controllers/__tests__/translation_rendering.test.js +34 -0
- data/app/javascript/controllers/comment_translation_controller.js +163 -0
- data/app/javascript/controllers/comment_translation_reader_controller.js +28 -0
- data/app/javascript/controllers/creative_translations_controller.js +178 -0
- data/app/javascript/controllers/index.js +12 -0
- data/app/javascript/controllers/translation_locale.js +8 -0
- data/app/javascript/controllers/translation_preference_controller.js +13 -0
- data/app/javascript/controllers/workspace_translation.js +46 -0
- data/app/jobs/collavre_translation/translate_job.rb +66 -0
- data/app/models/collavre_translation/translation.rb +54 -0
- data/app/services/collavre_translation/content_translation_policy.rb +18 -0
- data/app/services/collavre_translation/creative_translation_policy.rb +10 -0
- data/app/services/collavre_translation/html_translator.rb +39 -0
- data/app/services/collavre_translation/language_detector.rb +24 -0
- data/app/services/collavre_translation/protected_content.rb +31 -0
- data/app/services/collavre_translation/translator.rb +25 -0
- data/app/views/collavre_translation/comments/_reader.html.erb +5 -0
- data/app/views/collavre_translation/comments/_translation.html.erb +20 -0
- data/app/views/collavre_translation/creatives/_translation.html.erb +7 -0
- data/app/views/collavre_translation/preferences/_settings.html.erb +5 -0
- data/config/locales/en.yml +11 -0
- data/config/locales/ko.yml +11 -0
- data/config/locales/preferences.en.yml +5 -0
- data/config/locales/preferences.ko.yml +5 -0
- data/config/routes.rb +8 -0
- data/db/migrate/20261001000000_create_collavre_translation_translations.rb +18 -0
- data/db/migrate/20261001001000_add_auto_translation_enabled_to_users.rb +5 -0
- data/lib/collavre_translation/engine.rb +39 -0
- data/lib/collavre_translation/version.rb +3 -0
- data/lib/collavre_translation.rb +26 -0
- metadata +118 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 12f7454e466ff5b359d25cd698990b67a8142085b545fd81406a0762429e9e14
|
|
4
|
+
data.tar.gz: 39f5ea7ebfa52a35c34e75ff5a76797d3779afb67e44b47181df6e4b40c132ff
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: e9c8d5774cbbf2ee25f09e5ff4625a7a9e486267892f7606e53b8b288da027a13d534f89ce602d98071d4fedb5717a65700f5b4ad436f0b9d4e603b9672cff3c
|
|
7
|
+
data.tar.gz: d9512d2385a3eaac147eb32dd189c117d41ce6d86b547362281d3b46ff36cd947684dac1dc4d37d132058efcfb243d11ed36d887e72724ed5f0d9f1b159df72f
|
data/README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Collavre Translation
|
|
2
|
+
|
|
3
|
+
Optional comment and creative translation engine. Core content and agent context always retain
|
|
4
|
+
original text. Authorized readers, including anonymous visitors to public creatives, trigger translation when a
|
|
5
|
+
comment enters the viewport. Responses are fetched per viewer, never broadcast
|
|
6
|
+
on the shared comment stream.
|
|
7
|
+
|
|
8
|
+
Translation uses `COLLAVRE_DEFAULT_LLM_VENDOR` and `COLLAVRE_DEFAULT_LLM_MODEL`
|
|
9
|
+
by default (Gemini / `gemini-3.5-flash-lite` when unset). Override the model in **Admin → Integrations → Comment translation**
|
|
10
|
+
(`translation_llm_vendor`, `translation_llm_model`). The corresponding deployment
|
|
11
|
+
variables are `TRANSLATION_LLM_VENDOR` and `TRANSLATION_LLM_MODEL`. Alternatively,
|
|
12
|
+
override with a host initializer:
|
|
13
|
+
|
|
14
|
+
```ruby
|
|
15
|
+
CollavreTranslation.vendor = "google" # google, gemini, openai, anthropic
|
|
16
|
+
CollavreTranslation.model = "YOUR_CONFIGURED_MODEL"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Uses the existing provider API keys from Collavre integration settings. Blank integration settings fall back to the application defaults. Setting
|
|
20
|
+
`CollavreTranslation.model = ""` in a host initializer disables translation. Removing the engine and its host JS
|
|
21
|
+
registration disables the feature. This engine owns its tables and the user
|
|
22
|
+
preference column; core registers no translation-specific settings.
|
|
23
|
+
|
|
24
|
+
Targets English and Korean from the reader's `User#locale`, or browser language for anonymous readers.
|
|
25
|
+
The page's `?lang=en` or `?lang=ko` overrides the translation target without changing a saved preference;
|
|
26
|
+
cache lookups, enqueue requests and polling retain this override. Unsupported targets return 422. CLD3 detects source
|
|
27
|
+
language locally on first read. Hangul-only prose is recognized even in short
|
|
28
|
+
comments; other short or unreliable text stays in its original language. Code, URLs, mentions, HTML tags and Markdown links are masked and
|
|
29
|
+
restored locally. Missing or duplicate placeholders fail closed.
|
|
30
|
+
|
|
31
|
+
Translations are shared by source record, target locale and SHA-256 of the source.
|
|
32
|
+
Concurrent requests claim one job atomically. Source edits select a new cache
|
|
33
|
+
entry; jobs discard results if the source changes during translation. Deleting
|
|
34
|
+
a comment deletes its cached translations. Failed translations retain the
|
|
35
|
+
original. Failed comments show a Translate button for an explicit retry. Failed
|
|
36
|
+
creatives retry when their row is loaded again after a one-minute server cooldown; polling does not repeatedly retry
|
|
37
|
+
provider failures. An interrupted worker leaves a processing
|
|
38
|
+
row; operators can reset it to pending to retry. Old source revisions are
|
|
39
|
+
retained until the comment is deleted.
|
|
40
|
+
|
|
41
|
+
Creative titles and bodies use the same cache, job claims and translation queue.
|
|
42
|
+
Only prose text nodes are translated; HTML attributes, links, media, code blocks
|
|
43
|
+
and mention subtrees stay local. The viewer changes text nodes in place and can
|
|
44
|
+
toggle back to the original. Editing, exports and agent context retain the source.
|
|
45
|
+
Short creative titles are sent to the translator even when local detection is
|
|
46
|
+
uncertain. Linked creatives share their origin cache; both link and origin read
|
|
47
|
+
permissions are checked. Requests and polling stop when rows disappear or their
|
|
48
|
+
source changes. Provider failures preserve the original display.
|
|
49
|
+
|
|
50
|
+
For publicly readable creatives, translation availability follows the effective origin author’s
|
|
51
|
+
`auto_translation_enabled` setting. Public comments follow their own author’s setting.
|
|
52
|
+
Private content retains the reader preference gate; private comments remain inaccessible
|
|
53
|
+
to anonymous readers. Read permissions, linked-origin permissions and explicit denials
|
|
54
|
+
are checked before cache reads or enqueueing. Reader pages mount translation controllers whenever the engine is enabled,
|
|
55
|
+
including root and search lists, regardless of the visitor preference or parent
|
|
56
|
+
visibility. Individual endpoints enforce each source policy.
|
|
57
|
+
|
|
58
|
+
The creative controller mounts once on the reader index page, never in shared
|
|
59
|
+
row broadcasts. Its observer translates live appended/replaced rows using the
|
|
60
|
+
reader request. Shared live comment broadcasts contain inert templates;
|
|
61
|
+
the request-rendered `comment-translation-reader` hydrates initial, appended and
|
|
62
|
+
replaced templates. Endpoint policy is checked per source, before cache reads or
|
|
63
|
+
job requests, so a public page containing private content does not bypass its
|
|
64
|
+
reader preference. To avoid one refused lookup per visible comment, shared markup
|
|
65
|
+
omits the template for public comments whose author disabled translation and marks
|
|
66
|
+
the rest `data-comment-translation-reader-gated`; the reader page passes its own
|
|
67
|
+
preference to the reader controller, which leaves gated templates inert when it is off. Disabled engines return 503 and disabled content policies
|
|
68
|
+
return 403. Original content and AI context remain unchanged.
|
|
69
|
+
|
|
70
|
+
User preferences are owned and migrated by this engine on the shared user table as
|
|
71
|
+
`Collavre::User#auto_translation_enabled?` (default true, including existing users),
|
|
72
|
+
saved through the authorized profile update using the generic
|
|
73
|
+
`Collavre::ProfilePreferences` parameter registry and `profile_preferences` view slot.
|
|
74
|
+
Its preference controller clears Turbo snapshots when that form submits, so Back
|
|
75
|
+
re-renders the saved gate. `ContentTranslationPolicy` selects the author or reader
|
|
76
|
+
preference; `CollavreTranslation.enabled_for?(user)` combines that preference with
|
|
77
|
+
engine availability.
|
|
78
|
+
|
|
79
|
+
Per-user quotas and dedicated usage reporting are separate follow-ups.
|
|
80
|
+
|
|
81
|
+
The host runs the `translations` queue with a dedicated two-thread, one-process
|
|
82
|
+
worker in every environment. Slow provider calls do not occupy default or AI
|
|
83
|
+
agent worker threads. Other hosts must configure a worker for this queue.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
module CollavreTranslation
|
|
2
|
+
class CreativeTranslationsController < Collavre::ApplicationController
|
|
3
|
+
include TranslationLocale
|
|
4
|
+
allow_unauthenticated_access
|
|
5
|
+
before_action :require_authentication, if: -> { Collavre::SystemSetting.creatives_login_required? }
|
|
6
|
+
before_action :load_creative
|
|
7
|
+
|
|
8
|
+
def show
|
|
9
|
+
render_translation(Translation.for_creative(@creative, target_locale))
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def create
|
|
13
|
+
render_translation(Translation.request!(@creative.effective_origin, target_locale))
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
private
|
|
17
|
+
|
|
18
|
+
def load_creative
|
|
19
|
+
@creative = Collavre::Creative.find(params[:creative_id])
|
|
20
|
+
return head(Current.user ? :forbidden : :unauthorized) unless @creative.has_permission?(Current.user, :read)
|
|
21
|
+
return head :forbidden unless @creative.effective_origin.has_permission?(Current.user, :read)
|
|
22
|
+
|
|
23
|
+
return head :service_unavailable unless CollavreTranslation.enabled?
|
|
24
|
+
return head :forbidden unless manual_request? || ContentTranslationPolicy.enabled?(@creative.effective_origin, Current.user)
|
|
25
|
+
|
|
26
|
+
head :unprocessable_entity unless %w[en ko].include?(target_locale)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Readers who turned automatic translation off can still ask for one explicitly.
|
|
30
|
+
def manual_request?
|
|
31
|
+
Current.user.present? && params[:manual] == "1"
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def render_translation(record)
|
|
35
|
+
response.headers["Cache-Control"] = "no-store"
|
|
36
|
+
render json: { status: record&.status || "missing", content: record&.content,
|
|
37
|
+
source_digest: Translation.digest(Translation.source(@creative)),
|
|
38
|
+
original_html: original_html }
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# Workspace tree labels are built from the stored description, so they need
|
|
42
|
+
# the source before YouTube anchors (and their text) become empty iframes.
|
|
43
|
+
def original_html
|
|
44
|
+
source = Translation.source(@creative)
|
|
45
|
+
params[:embed] == "0" ? source : helpers.embed_youtube_iframe(source)
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
module CollavreTranslation
|
|
2
|
+
class TranslationsController < Collavre::ApplicationController
|
|
3
|
+
include Collavre::Comments::CommentScoping
|
|
4
|
+
include TranslationLocale
|
|
5
|
+
allow_unauthenticated_access
|
|
6
|
+
before_action :require_authentication, if: -> { Collavre::SystemSetting.creatives_login_required? }
|
|
7
|
+
before_action :load_comment
|
|
8
|
+
before_action :require_auto_translation
|
|
9
|
+
before_action :validate_locale
|
|
10
|
+
|
|
11
|
+
def show
|
|
12
|
+
render_translation(Translation.for_comment(@comment, target_locale))
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def create
|
|
16
|
+
return head :conflict if @comment.task&.status.in?(%w[running pending queued])
|
|
17
|
+
|
|
18
|
+
render_translation(Translation.request!(@comment, target_locale))
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
private
|
|
22
|
+
|
|
23
|
+
def require_auto_translation
|
|
24
|
+
return head :service_unavailable unless CollavreTranslation.enabled?
|
|
25
|
+
|
|
26
|
+
head :forbidden unless ContentTranslationPolicy.enabled?(@comment, Current.user)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def load_comment
|
|
30
|
+
scope = Current.user ? Collavre::Comment.visible_to(Current.user) : Collavre::Comment.public_only
|
|
31
|
+
comment = scope.find(params[:comment_id])
|
|
32
|
+
if !Current.user && !comment.creative.has_permission?(nil, :read)
|
|
33
|
+
return head :unauthorized
|
|
34
|
+
end
|
|
35
|
+
params[:creative_id] = comment.creative_id
|
|
36
|
+
set_creative
|
|
37
|
+
return if performed?
|
|
38
|
+
|
|
39
|
+
@comment = comment
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def validate_locale
|
|
43
|
+
head :unprocessable_entity unless %w[en ko].include?(target_locale)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def render_translation(record)
|
|
47
|
+
response.headers["Cache-Control"] = "no-store"
|
|
48
|
+
render json: { status: record&.status || "missing", content: record&.content,
|
|
49
|
+
source_digest: Translation.digest(@comment.content) }
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { registerControllers } from "./controllers"
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/** @jest-environment jsdom */
|
|
2
|
+
import { jest } from '@jest/globals'
|
|
3
|
+
import { Application } from '@hotwired/stimulus'
|
|
4
|
+
|
|
5
|
+
const fetchMock = jest.fn()
|
|
6
|
+
const mermaidMock = jest.fn()
|
|
7
|
+
const renderMock = jest.fn(text => `<p>${text}</p>`)
|
|
8
|
+
jest.unstable_mockModule('collavre/lib/api/csrf_fetch', () => ({ default: fetchMock }))
|
|
9
|
+
jest.unstable_mockModule('collavre/lib/utils/markdown', () => ({ renderCommentMarkdown: renderMock, renderMermaidDiagrams: mermaidMock }))
|
|
10
|
+
const { default: Controller } = await import('../comment_translation_controller')
|
|
11
|
+
const { registerControllers } = await import('../index')
|
|
12
|
+
await import('../../collavre_translation')
|
|
13
|
+
const tick = () => new Promise(resolve => setTimeout(resolve, 0))
|
|
14
|
+
const result = (status, content = null, digest = 'source') => ({ ok: true,
|
|
15
|
+
json: async () => ({ status, content, source_digest: digest }) })
|
|
16
|
+
|
|
17
|
+
let app, controller, intersection
|
|
18
|
+
beforeEach(async () => {
|
|
19
|
+
global.IntersectionObserver = class {
|
|
20
|
+
constructor(callback) { intersection = callback }
|
|
21
|
+
observe = jest.fn()
|
|
22
|
+
disconnect = jest.fn()
|
|
23
|
+
}
|
|
24
|
+
document.body.innerHTML = `<div class="comment-item"><div data-comment-target="content">Original</div>
|
|
25
|
+
<div data-controller="comment-translation" data-comment-translation-url-value="/translation/comments/1/translation"
|
|
26
|
+
data-comment-translation-digest-value="source" data-comment-translation-loading-value="Translating"
|
|
27
|
+
data-comment-translation-original-value="Show original"
|
|
28
|
+
data-comment-translation-translate-value="Translate" data-comment-translation-show-translation-value="Show translation">
|
|
29
|
+
<div class="comment-content-action-controls"><button data-comment-translation-target="toggle" data-action="comment-translation#toggle" hidden></button></div>
|
|
30
|
+
<div data-comment-translation-target="content" hidden></div>
|
|
31
|
+
</div></div>`
|
|
32
|
+
app = Application.start()
|
|
33
|
+
registerControllers(app)
|
|
34
|
+
await tick()
|
|
35
|
+
controller = app.getControllerForElementAndIdentifier(document.querySelector('[data-controller]'), 'comment-translation')
|
|
36
|
+
fetchMock.mockReset()
|
|
37
|
+
mermaidMock.mockReset()
|
|
38
|
+
})
|
|
39
|
+
afterEach(async () => {
|
|
40
|
+
controller.disconnect()
|
|
41
|
+
app.stop()
|
|
42
|
+
document.body.innerHTML = ''
|
|
43
|
+
jest.useRealTimers()
|
|
44
|
+
jest.restoreAllMocks()
|
|
45
|
+
await tick()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
test('waits for viewport then requests missing translation and polls to completion', async () => {
|
|
49
|
+
expect(fetchMock).not.toHaveBeenCalled()
|
|
50
|
+
intersection([{ isIntersecting: false }])
|
|
51
|
+
expect(fetchMock).not.toHaveBeenCalled()
|
|
52
|
+
fetchMock.mockResolvedValueOnce(result('missing')).mockResolvedValueOnce(result('processing'))
|
|
53
|
+
intersection([{ isIntersecting: true }])
|
|
54
|
+
await tick()
|
|
55
|
+
expect(fetchMock.mock.calls.map(call => call[1].method)).toEqual(['GET', 'POST'])
|
|
56
|
+
expect(controller.toggleTarget.textContent).toBe('Translating')
|
|
57
|
+
expect(controller.toggleTarget.title).toBe('Translating')
|
|
58
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Translating')
|
|
59
|
+
expect(controller.toggleTarget.disabled).toBe(true)
|
|
60
|
+
expect(controller.toggleTarget.hasAttribute('role')).toBe(false)
|
|
61
|
+
expect(controller.original.hidden).toBe(false)
|
|
62
|
+
clearTimeout(controller.timer)
|
|
63
|
+
fetchMock.mockResolvedValueOnce(result('completed', '번역 결과'))
|
|
64
|
+
await controller.load()
|
|
65
|
+
expect(controller.original.hidden).toBe(true)
|
|
66
|
+
expect(controller.toggleTarget.hasAttribute('role')).toBe(false)
|
|
67
|
+
expect(controller.contentTarget.innerHTML).toBe('<p>번역 결과</p>')
|
|
68
|
+
controller.toggle()
|
|
69
|
+
expect(controller.original.hidden).toBe(false)
|
|
70
|
+
expect(controller.toggleTarget.textContent).toBe('Show translation')
|
|
71
|
+
expect(controller.toggleTarget.title).toBe('Show translation')
|
|
72
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Show translation')
|
|
73
|
+
controller.toggle()
|
|
74
|
+
expect(controller.contentTarget.hidden).toBe(false)
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('cached translation does not issue POST', async () => {
|
|
78
|
+
fetchMock.mockResolvedValue(result('completed', 'Cached'))
|
|
79
|
+
await controller.load()
|
|
80
|
+
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
81
|
+
expect(fetchMock.mock.calls[0][1].method).toBe('GET')
|
|
82
|
+
expect(controller.toggleTarget.getAttribute('aria-pressed')).toBe('true')
|
|
83
|
+
expect(controller.toggleTarget.textContent).toBe('Show original')
|
|
84
|
+
expect(controller.toggleTarget.title).toBe('Show original')
|
|
85
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Show original')
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test.each(['skipped'])('%s preserves original', async status => {
|
|
89
|
+
fetchMock.mockResolvedValue(result(status))
|
|
90
|
+
await controller.load()
|
|
91
|
+
expect(controller.original.hidden).toBe(false)
|
|
92
|
+
expect(controller.toggleTarget.hidden).toBe(true)
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('HTTP failure and thrown network errors preserve original', async () => {
|
|
96
|
+
fetchMock.mockResolvedValueOnce({ ok: false })
|
|
97
|
+
await controller.load()
|
|
98
|
+
expect(controller.original.hidden).toBe(false)
|
|
99
|
+
fetchMock.mockRejectedValueOnce(new Error('offline'))
|
|
100
|
+
await controller.load()
|
|
101
|
+
expect(controller.toggleTarget.closest('.comment-content-action-controls')).not.toBeNull()
|
|
102
|
+
expect(controller.toggleTarget.textContent).toBe('Translate')
|
|
103
|
+
expect(controller.toggleTarget.title).toBe('Translate')
|
|
104
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Translate')
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
test('stale digest, empty content and aborted requests do not display a translation', async () => {
|
|
108
|
+
fetchMock.mockResolvedValueOnce(result('completed', 'Stale', 'different'))
|
|
109
|
+
await controller.load()
|
|
110
|
+
expect(controller.original.hidden).toBe(false)
|
|
111
|
+
fetchMock.mockResolvedValueOnce(result('completed', ''))
|
|
112
|
+
await controller.load()
|
|
113
|
+
expect(controller.original.hidden).toBe(false)
|
|
114
|
+
controller.abort.abort()
|
|
115
|
+
controller.handleResponse({ status: 'completed', content: 'Stale', source_digest: 'source' })
|
|
116
|
+
expect(controller.original.hidden).toBe(false)
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
test('editing or browsing versions invalidates translation even while request is pending', async () => {
|
|
120
|
+
fetchMock.mockResolvedValueOnce(result('processing'))
|
|
121
|
+
await controller.load()
|
|
122
|
+
controller.original.textContent = 'Changed version'
|
|
123
|
+
await tick()
|
|
124
|
+
expect(controller.abort.signal.aborted).toBe(true)
|
|
125
|
+
expect(controller.toggleTarget.hidden).toBe(true)
|
|
126
|
+
expect(controller.original.hidden).toBe(false)
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
test('queued translations keep polling beyond two minutes with capped backoff until completion', async () => {
|
|
130
|
+
jest.useFakeTimers()
|
|
131
|
+
const initialTime = Date.now()
|
|
132
|
+
fetchMock.mockResolvedValueOnce(result('processing'))
|
|
133
|
+
await controller.load()
|
|
134
|
+
expect(controller.pollDelay).toBe(2000)
|
|
135
|
+
fetchMock.mockResolvedValueOnce(result('processing'))
|
|
136
|
+
await jest.advanceTimersByTimeAsync(2000)
|
|
137
|
+
expect(controller.pollDelay).toBe(4000)
|
|
138
|
+
fetchMock.mockResolvedValueOnce(result('translating'))
|
|
139
|
+
await jest.advanceTimersByTimeAsync(4000)
|
|
140
|
+
expect(controller.pollDelay).toBe(8000)
|
|
141
|
+
fetchMock.mockResolvedValueOnce(result('processing'))
|
|
142
|
+
await jest.advanceTimersByTimeAsync(8000)
|
|
143
|
+
expect(controller.pollDelay).toBe(10000)
|
|
144
|
+
jest.setSystemTime(initialTime + 600000)
|
|
145
|
+
fetchMock.mockResolvedValueOnce(result('translating'))
|
|
146
|
+
await jest.advanceTimersByTimeAsync(10000)
|
|
147
|
+
expect(controller.toggleTarget.hidden).toBe(false)
|
|
148
|
+
expect(controller.toggleTarget.disabled).toBe(true)
|
|
149
|
+
expect(controller.pollDelay).toBe(10000)
|
|
150
|
+
fetchMock.mockResolvedValueOnce(result('completed', 'Delayed translation'))
|
|
151
|
+
await jest.advanceTimersByTimeAsync(10000)
|
|
152
|
+
expect(controller.contentTarget.textContent).toBe('Delayed translation')
|
|
153
|
+
expect(controller.original.hidden).toBe(true)
|
|
154
|
+
expect(controller.toggleTarget.disabled).toBe(false)
|
|
155
|
+
const requestCount = fetchMock.mock.calls.length
|
|
156
|
+
await jest.advanceTimersByTimeAsync(20000)
|
|
157
|
+
expect(fetchMock).toHaveBeenCalledTimes(requestCount)
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
test('disconnect restores original and aborts pending work', async () => {
|
|
161
|
+
fetchMock.mockResolvedValueOnce(result('completed', 'Cached'))
|
|
162
|
+
await controller.load()
|
|
163
|
+
controller.disconnect()
|
|
164
|
+
expect(controller.original.hidden).toBe(false)
|
|
165
|
+
expect(controller.abort.signal.aborted).toBe(true)
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
test('missing original content does not observe or request', () => {
|
|
169
|
+
controller.original.remove()
|
|
170
|
+
controller.connect()
|
|
171
|
+
expect(controller.original).toBeNull()
|
|
172
|
+
expect(fetchMock).not.toHaveBeenCalled()
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
test('pending states poll again and stop cleanly on failure', async () => {
|
|
176
|
+
jest.useFakeTimers()
|
|
177
|
+
fetchMock.mockResolvedValueOnce(result('pending')).mockResolvedValueOnce(result('processing')).mockResolvedValueOnce(result('failed'))
|
|
178
|
+
await controller.load()
|
|
179
|
+
expect(controller.toggleTarget.disabled).toBe(true)
|
|
180
|
+
await jest.advanceTimersByTimeAsync(2000)
|
|
181
|
+
expect(fetchMock.mock.calls.map(call => call[1].method)).toEqual(['GET', 'POST', 'GET'])
|
|
182
|
+
expect(controller.toggleTarget.closest('.comment-content-action-controls')).not.toBeNull()
|
|
183
|
+
expect(controller.toggleTarget.textContent).toBe('Translate')
|
|
184
|
+
expect(controller.toggleTarget.title).toBe('Translate')
|
|
185
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Translate')
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
test('disconnect is safe before content is connected', () => {
|
|
189
|
+
controller.original = null
|
|
190
|
+
controller.restoreOriginal()
|
|
191
|
+
controller.abort = null
|
|
192
|
+
controller.observer = null
|
|
193
|
+
controller.mutations = null
|
|
194
|
+
expect(() => controller.disconnect()).not.toThrow()
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
test('renders Mermaid after translated content becomes visible and preserves it across toggles', async () => {
|
|
198
|
+
const content = 'Diagram\n```mermaid\ngraph TD; A-->B\n```'
|
|
199
|
+
renderMock.mockReturnValueOnce('<div class="mermaid-chart">graph TD; A-->B</div>')
|
|
200
|
+
mermaidMock.mockImplementationOnce(container => {
|
|
201
|
+
expect(container.hidden).toBe(false)
|
|
202
|
+
expect(controller.original.hidden).toBe(true)
|
|
203
|
+
expect(container.querySelector('.mermaid-chart').textContent).toBe('graph TD; A-->B')
|
|
204
|
+
container.querySelector('.mermaid-chart').innerHTML = '<svg></svg>'
|
|
205
|
+
})
|
|
206
|
+
fetchMock.mockResolvedValueOnce(result('completed', content))
|
|
207
|
+
await controller.load()
|
|
208
|
+
expect(renderMock).toHaveBeenLastCalledWith(content)
|
|
209
|
+
expect(mermaidMock).toHaveBeenCalledTimes(1)
|
|
210
|
+
expect(mermaidMock).toHaveBeenCalledWith(controller.contentTarget)
|
|
211
|
+
controller.toggle()
|
|
212
|
+
controller.toggle()
|
|
213
|
+
expect(controller.contentTarget.querySelector('svg')).not.toBeNull()
|
|
214
|
+
expect(mermaidMock).toHaveBeenCalledTimes(1)
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
test('adds working table download controls to translated content and preserves them across toggles', async () => {
|
|
219
|
+
renderMock.mockReturnValueOnce('<table><tr><th>Name</th></tr><tr><td>Translated</td></tr></table>')
|
|
220
|
+
fetchMock.mockResolvedValueOnce(result('completed', '| Name |\n| --- |\n| Translated |'))
|
|
221
|
+
URL.createObjectURL = jest.fn(() => 'blob:table')
|
|
222
|
+
URL.revokeObjectURL = jest.fn()
|
|
223
|
+
const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
|
224
|
+
await controller.load()
|
|
225
|
+
const buttons = controller.contentTarget.querySelectorAll('.table-download-btn')
|
|
226
|
+
expect([...buttons].map(button => button.textContent)).toEqual(['⤓ CSV', '⤓ Excel'])
|
|
227
|
+
expect(controller.contentTarget.querySelector('.table-download-wrapper table').textContent).toBe('NameTranslated')
|
|
228
|
+
buttons.forEach(button => button.click())
|
|
229
|
+
expect(click.mock.instances.map(anchor => anchor.download)).toEqual(['table_Name.csv', 'table_Name.xls'])
|
|
230
|
+
expect(URL.createObjectURL).toHaveBeenCalledTimes(2)
|
|
231
|
+
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(2)
|
|
232
|
+
controller.toggle()
|
|
233
|
+
expect(controller.contentTarget.hidden).toBe(true)
|
|
234
|
+
controller.toggle()
|
|
235
|
+
expect(controller.contentTarget.hidden).toBe(false)
|
|
236
|
+
expect(controller.contentTarget.querySelectorAll('.table-download-toolbar')).toHaveLength(1)
|
|
237
|
+
expect(controller.contentTarget.querySelectorAll('.table-download-btn')[0]).toBe(buttons[0])
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
test('Mermaid decoration during an in-flight request does not invalidate translation', async () => {
|
|
241
|
+
controller.original.innerHTML = '<div class="mermaid-chart"><span>graph TD; A-->B</span></div>'
|
|
242
|
+
let resolveRequest
|
|
243
|
+
fetchMock.mockImplementationOnce(() => new Promise(resolve => { resolveRequest = resolve }))
|
|
244
|
+
const loading = controller.load()
|
|
245
|
+
const chart = controller.original.querySelector('.mermaid-chart')
|
|
246
|
+
chart.firstChild.firstChild.textContent = 'decorating'
|
|
247
|
+
await tick()
|
|
248
|
+
expect(controller.abort.signal.aborted).toBe(false)
|
|
249
|
+
chart.innerHTML = '<svg><g></g></svg>'
|
|
250
|
+
await tick()
|
|
251
|
+
expect(controller.abort.signal.aborted).toBe(false)
|
|
252
|
+
resolveRequest(result('completed', 'Translated diagram'))
|
|
253
|
+
await loading
|
|
254
|
+
expect(controller.original.hidden).toBe(true)
|
|
255
|
+
expect(controller.toggleTarget.hidden).toBe(false)
|
|
256
|
+
controller.original.append('Edited source')
|
|
257
|
+
await tick()
|
|
258
|
+
expect(controller.abort.signal.aborted).toBe(true)
|
|
259
|
+
expect(controller.original.hidden).toBe(false)
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
test('failed translation waits for a click and retries with POST, then can toggle translation', async () => {
|
|
263
|
+
fetchMock.mockResolvedValueOnce(result('failed'))
|
|
264
|
+
await controller.load()
|
|
265
|
+
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
266
|
+
expect(controller.toggleTarget.hidden).toBe(false)
|
|
267
|
+
expect(controller.toggleTarget.disabled).toBe(false)
|
|
268
|
+
expect(controller.toggleTarget.closest('.comment-content-action-controls')).not.toBeNull()
|
|
269
|
+
expect(controller.toggleTarget.textContent).toBe('Translate')
|
|
270
|
+
expect(controller.toggleTarget.title).toBe('Translate')
|
|
271
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Translate')
|
|
272
|
+
expect(controller.original.hidden).toBe(false)
|
|
273
|
+
fetchMock.mockResolvedValueOnce(result('processing'))
|
|
274
|
+
await controller.toggle()
|
|
275
|
+
expect(fetchMock.mock.calls[1][1].method).toBe('POST')
|
|
276
|
+
expect(controller.toggleTarget.disabled).toBe(true)
|
|
277
|
+
expect(controller.toggleTarget.title).toBe('Translating')
|
|
278
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Translating')
|
|
279
|
+
clearTimeout(controller.timer)
|
|
280
|
+
fetchMock.mockResolvedValueOnce(result('completed', 'Recovered'))
|
|
281
|
+
await controller.load()
|
|
282
|
+
controller.toggle()
|
|
283
|
+
expect(controller.toggleTarget.textContent).toBe('Show translation')
|
|
284
|
+
expect(controller.original.hidden).toBe(false)
|
|
285
|
+
})
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
test.each([401, 403, 404, 409, 422, 503])('HTTP %s hides retry', async status => {
|
|
289
|
+
fetchMock.mockResolvedValueOnce({ ok: false, status })
|
|
290
|
+
await controller.load()
|
|
291
|
+
expect(controller.original.hidden).toBe(false)
|
|
292
|
+
expect(controller.toggleTarget.hidden).toBe(true)
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
test.each([500, 502, 504])('HTTP %s allows retry', async status => {
|
|
296
|
+
fetchMock.mockResolvedValueOnce({ ok: false, status })
|
|
297
|
+
await controller.load()
|
|
298
|
+
expect(controller.toggleTarget.closest('.comment-content-action-controls')).not.toBeNull()
|
|
299
|
+
expect(controller.toggleTarget.textContent).toBe('Translate')
|
|
300
|
+
expect(controller.toggleTarget.title).toBe('Translate')
|
|
301
|
+
expect(controller.toggleTarget.getAttribute('aria-label')).toBe('Translate')
|
|
302
|
+
expect(controller.toggleTarget.hidden).toBe(false)
|
|
303
|
+
})
|
|
304
|
+
|
|
305
|
+
test('rendering errors do not offer another provider request', async () => {
|
|
306
|
+
fetchMock.mockResolvedValueOnce(result('completed', 'Cached'))
|
|
307
|
+
renderMock.mockImplementationOnce(() => { throw new Error('render failed') })
|
|
308
|
+
await controller.load()
|
|
309
|
+
expect(controller.toggleTarget.hidden).toBe(true)
|
|
310
|
+
expect(controller.original.hidden).toBe(false)
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
test('explicit retry resets the polling backoff', async () => {
|
|
314
|
+
fetchMock.mockResolvedValueOnce(result('failed')).mockResolvedValueOnce(result('processing'))
|
|
315
|
+
await controller.load()
|
|
316
|
+
controller.pollDelay = 10000
|
|
317
|
+
await controller.toggle()
|
|
318
|
+
expect(controller.pollDelay).toBe(2000)
|
|
319
|
+
})
|
|
320
|
+
|
|
321
|
+
test.each(['failed', 'network', 'http'])('source changes invalidate the %s retry control', async failure => {
|
|
322
|
+
if (failure === 'network') fetchMock.mockRejectedValueOnce(new Error('offline'))
|
|
323
|
+
else if (failure === 'http') fetchMock.mockResolvedValueOnce({ ok: false, status: 502 })
|
|
324
|
+
else fetchMock.mockResolvedValueOnce(result('failed'))
|
|
325
|
+
await controller.load()
|
|
326
|
+
expect(controller.retryAvailable).toBe(true)
|
|
327
|
+
controller.original.textContent = 'Different comment version'
|
|
328
|
+
await tick()
|
|
329
|
+
expect(controller.abort.signal.aborted).toBe(true)
|
|
330
|
+
expect(controller.retryAvailable).toBe(false)
|
|
331
|
+
expect(controller.toggleTarget.hidden).toBe(true)
|
|
332
|
+
expect(controller.original.hidden).toBe(false)
|
|
333
|
+
expect(controller.mutations).toBeNull()
|
|
334
|
+
controller.handleResponse({ status: 'completed', source_digest: 'source', content: 'Stale translation' })
|
|
335
|
+
expect(controller.contentTarget.hidden).toBe(true)
|
|
336
|
+
expect(controller.contentTarget.textContent).toBe('')
|
|
337
|
+
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
338
|
+
})
|
|
339
|
+
|
|
340
|
+
test('source changes during explicit retry discard its late response', async () => {
|
|
341
|
+
fetchMock.mockResolvedValueOnce(result('failed'))
|
|
342
|
+
await controller.load()
|
|
343
|
+
let resolveRequest
|
|
344
|
+
fetchMock.mockImplementationOnce(() => new Promise(resolve => { resolveRequest = resolve }))
|
|
345
|
+
const retry = controller.toggle()
|
|
346
|
+
controller.original.textContent = 'Different comment version'
|
|
347
|
+
await tick()
|
|
348
|
+
expect(controller.abort.signal.aborted).toBe(true)
|
|
349
|
+
resolveRequest(result('completed', 'Stale translation'))
|
|
350
|
+
await retry
|
|
351
|
+
expect(controller.original.hidden).toBe(false)
|
|
352
|
+
expect(controller.toggleTarget.hidden).toBe(true)
|
|
353
|
+
expect(controller.contentTarget.textContent).toBe('')
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
test('reserves action width without adding flow space and disconnects resize observer', () => {
|
|
357
|
+
const actions = document.createElement('div')
|
|
358
|
+
actions.className = 'comment-action-container'
|
|
359
|
+
actions.getBoundingClientRect = () => ({ width: 100 })
|
|
360
|
+
controller.element.closest('.comment-item').append(actions)
|
|
361
|
+
let resize
|
|
362
|
+
const observe = jest.fn()
|
|
363
|
+
const disconnect = jest.fn()
|
|
364
|
+
global.ResizeObserver = class {
|
|
365
|
+
constructor(callback) { resize = callback }
|
|
366
|
+
observe = observe
|
|
367
|
+
disconnect = disconnect
|
|
368
|
+
}
|
|
369
|
+
controller.disconnect()
|
|
370
|
+
controller.connect()
|
|
371
|
+
resize()
|
|
372
|
+
expect(observe).toHaveBeenCalledWith(actions)
|
|
373
|
+
expect(controller.toggleTarget.parentElement.style.right).toBe('108px')
|
|
374
|
+
controller.disconnect()
|
|
375
|
+
expect(disconnect).toHaveBeenCalled()
|
|
376
|
+
delete global.ResizeObserver
|
|
377
|
+
})
|