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.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +83 -0
  3. data/app/controllers/collavre_translation/creative_translations_controller.rb +48 -0
  4. data/app/controllers/collavre_translation/translations_controller.rb +52 -0
  5. data/app/controllers/concerns/collavre_translation/translation_locale.rb +9 -0
  6. data/app/javascript/collavre_translation.js +1 -0
  7. data/app/javascript/controllers/__tests__/comment_translation_controller.test.js +377 -0
  8. data/app/javascript/controllers/__tests__/comment_translation_reader_controller.test.js +106 -0
  9. data/app/javascript/controllers/__tests__/creative_translations_controller.test.js +667 -0
  10. data/app/javascript/controllers/__tests__/translation_locale.test.js +14 -0
  11. data/app/javascript/controllers/__tests__/translation_preference_controller.test.js +29 -0
  12. data/app/javascript/controllers/__tests__/translation_rendering.test.js +34 -0
  13. data/app/javascript/controllers/comment_translation_controller.js +163 -0
  14. data/app/javascript/controllers/comment_translation_reader_controller.js +28 -0
  15. data/app/javascript/controllers/creative_translations_controller.js +178 -0
  16. data/app/javascript/controllers/index.js +12 -0
  17. data/app/javascript/controllers/translation_locale.js +8 -0
  18. data/app/javascript/controllers/translation_preference_controller.js +13 -0
  19. data/app/javascript/controllers/workspace_translation.js +46 -0
  20. data/app/jobs/collavre_translation/translate_job.rb +66 -0
  21. data/app/models/collavre_translation/translation.rb +54 -0
  22. data/app/services/collavre_translation/content_translation_policy.rb +18 -0
  23. data/app/services/collavre_translation/creative_translation_policy.rb +10 -0
  24. data/app/services/collavre_translation/html_translator.rb +39 -0
  25. data/app/services/collavre_translation/language_detector.rb +24 -0
  26. data/app/services/collavre_translation/protected_content.rb +31 -0
  27. data/app/services/collavre_translation/translator.rb +25 -0
  28. data/app/views/collavre_translation/comments/_reader.html.erb +5 -0
  29. data/app/views/collavre_translation/comments/_translation.html.erb +20 -0
  30. data/app/views/collavre_translation/creatives/_translation.html.erb +7 -0
  31. data/app/views/collavre_translation/preferences/_settings.html.erb +5 -0
  32. data/config/locales/en.yml +11 -0
  33. data/config/locales/ko.yml +11 -0
  34. data/config/locales/preferences.en.yml +5 -0
  35. data/config/locales/preferences.ko.yml +5 -0
  36. data/config/routes.rb +8 -0
  37. data/db/migrate/20261001000000_create_collavre_translation_translations.rb +18 -0
  38. data/db/migrate/20261001001000_add_auto_translation_enabled_to_users.rb +5 -0
  39. data/lib/collavre_translation/engine.rb +39 -0
  40. data/lib/collavre_translation/version.rb +3 -0
  41. data/lib/collavre_translation.rb +26 -0
  42. metadata +118 -0
@@ -0,0 +1,14 @@
1
+ /** @jest-environment jsdom */
2
+ import { translationLocaleUrl } from '../translation_locale'
3
+
4
+ beforeEach(() => window.history.replaceState({}, '', '/creatives?id=42'))
5
+
6
+ test('preserves requests without an override', () => {
7
+ expect(translationLocaleUrl('/translation/creatives/42/translation?embed=0')).toBe('/translation/creatives/42/translation?embed=0')
8
+ })
9
+
10
+ test('propagates lang and preserves existing query parameters', () => {
11
+ window.history.replaceState({}, '', '/creatives?id=42&lang=ko-KR')
12
+ expect(translationLocaleUrl('/translation/creatives/42/translation?embed=0')).toBe('/translation/creatives/42/translation?embed=0&lang=ko-KR')
13
+ expect(translationLocaleUrl('/translation/comments/1/translation')).toBe('/translation/comments/1/translation?lang=ko-KR')
14
+ })
@@ -0,0 +1,29 @@
1
+ /** @jest-environment jsdom */
2
+ import { jest } from '@jest/globals'
3
+ import { Application } from '@hotwired/stimulus'
4
+ import TranslationPreferenceController from '../translation_preference_controller'
5
+
6
+ test('profile submission discards snapshots with stale reader preferences', async () => {
7
+ const snapshots = new Map([
8
+ ['/on-reader', '<span data-controller="comment-translation"></span>'],
9
+ ['/off-reader', '<template></template>'],
10
+ ])
11
+ window.Turbo = { cache: { clear: jest.fn(() => snapshots.clear()) } }
12
+ document.body.innerHTML = '<form><div data-controller="translation-preference"></div></form>'
13
+ const application = Application.start()
14
+ application.register('translation-preference', TranslationPreferenceController)
15
+ await new Promise(resolve => setTimeout(resolve, 0))
16
+
17
+ expect(snapshots.size).toBe(2)
18
+ document.querySelector('form').dispatchEvent(new CustomEvent('turbo:submit-start', { bubbles: true }))
19
+ expect(window.Turbo.cache.clear).toHaveBeenCalledTimes(1)
20
+ expect(snapshots.size).toBe(0)
21
+
22
+ const form = document.querySelector('form')
23
+ document.body.innerHTML = ''
24
+ await new Promise(resolve => setTimeout(resolve, 0))
25
+ form.dispatchEvent(new CustomEvent('turbo:submit-start', { bubbles: true }))
26
+ expect(window.Turbo.cache.clear).toHaveBeenCalledTimes(1)
27
+ application.stop()
28
+ delete window.Turbo
29
+ })
@@ -0,0 +1,34 @@
1
+ /** @jest-environment jsdom */
2
+ import { Application } from '@hotwired/stimulus'
3
+ import { renderMarkdownInContainer } from 'collavre/lib/utils/markdown'
4
+ import Controller from '../comment_translation_controller'
5
+
6
+ test('list rendering preserves translated links and decorated tables', async () => {
7
+ global.IntersectionObserver = class {
8
+ observe() {}
9
+ disconnect() {}
10
+ }
11
+ document.body.innerHTML = `<div class="comment-item"><div data-comment-target="content">Original</div>
12
+ <div data-controller="comment-translation">
13
+ <button data-comment-translation-target="toggle"></button>
14
+ <div data-comment-translation-target="content"></div>
15
+ </div></div>`
16
+ const app = Application.start()
17
+ app.register('comment-translation', Controller)
18
+ await new Promise(resolve => setTimeout(resolve, 0))
19
+ const controller = app.getControllerForElementAndIdentifier(document.querySelector('[data-controller]'), 'comment-translation')
20
+ try {
21
+ controller.show('[Translated link](https://example.com/destination)\n\n| Name |\n| --- |\n| Translated |')
22
+ const content = controller.contentTarget
23
+ const markup = content.innerHTML
24
+ expect(content.dataset.rendered).toBe('true')
25
+ renderMarkdownInContainer(document.body)
26
+ expect(content.innerHTML).toBe(markup)
27
+ expect(content.querySelector('a').href).toBe('https://example.com/destination')
28
+ expect(content.querySelectorAll('.table-download-btn')).toHaveLength(2)
29
+ } finally {
30
+ controller.disconnect()
31
+ app.stop()
32
+ document.body.innerHTML = ''
33
+ }
34
+ })
@@ -0,0 +1,163 @@
1
+ import { translationLocaleUrl } from "./translation_locale"
2
+ import { Controller } from "@hotwired/stimulus"
3
+ import { addTableDownloadButtons } from "collavre/lib/utils/table_download"
4
+ import csrfFetch from "collavre/lib/api/csrf_fetch"
5
+ import { renderCommentMarkdown, renderMermaidDiagrams } from "collavre/lib/utils/markdown"
6
+
7
+ export default class extends Controller {
8
+ static targets = ["toggle", "content"]
9
+ static values = { url: String, digest: String, loading: String,
10
+ original: String, showTranslation: String, translate: String }
11
+
12
+ connect() {
13
+ this.abort = new AbortController()
14
+ this.original = this.element.closest('.comment-item')?.querySelector('[data-comment-target="content"]')
15
+ if (!this.original) return
16
+ const actions = this.element.closest('.comment-item').querySelector('.comment-action-container')
17
+ const controls = this.toggleTarget.parentElement
18
+ if (actions && typeof ResizeObserver !== 'undefined') {
19
+ this.actionResize = new ResizeObserver(() => {
20
+ controls.style.right = `${actions.getBoundingClientRect().width + 8}px`
21
+ })
22
+ this.actionResize.observe(actions)
23
+ }
24
+ this.observer = new IntersectionObserver(entries => {
25
+ if (entries.some(entry => entry.isIntersecting)) {
26
+ this.observer.disconnect()
27
+ this.load()
28
+ }
29
+ })
30
+ this.observer.observe(this.element)
31
+ }
32
+
33
+ disconnect() {
34
+ this.abort?.abort()
35
+ this.observer?.disconnect()
36
+ this.mutations?.disconnect()
37
+ this.actionResize?.disconnect()
38
+ clearTimeout(this.timer)
39
+ if (this.original) this.original.hidden = false
40
+ }
41
+
42
+ async load(retry = false) {
43
+ let response
44
+ try {
45
+ if (!this.mutations) {
46
+ this.mutations = new MutationObserver(records => {
47
+ if (records.every(record => {
48
+ const target = record.target.nodeType === Node.ELEMENT_NODE ? record.target : record.target.parentElement
49
+ return target?.closest('.mermaid-chart')
50
+ })) return
51
+ this.abort.abort()
52
+ clearTimeout(this.timer)
53
+ this.restoreOriginal()
54
+ })
55
+ this.mutations.observe(this.original, { childList: true, subtree: true, characterData: true })
56
+ }
57
+ response = await this.request(retry ? 'POST' : 'GET')
58
+ if (['missing', 'pending'].includes(response.status)) response = await this.request('POST')
59
+ } catch (error) {
60
+ return error.retryable ? this.showRetry() : this.restoreOriginal()
61
+ }
62
+ try {
63
+ this.handleResponse(response)
64
+ } catch {
65
+ this.restoreOriginal()
66
+ }
67
+ }
68
+
69
+ async request(method) {
70
+ let response
71
+ try {
72
+ response = await csrfFetch(translationLocaleUrl(this.urlValue), { method, signal: this.abort.signal,
73
+ headers: { Accept: 'application/json' } })
74
+ } catch (error) {
75
+ error.retryable = error.name !== 'AbortError'
76
+ throw error
77
+ }
78
+ if (!response.ok) {
79
+ const error = new Error('Translation unavailable')
80
+ error.retryable = response.status >= 500 && response.status !== 503
81
+ throw error
82
+ }
83
+ return response.json()
84
+ }
85
+
86
+ handleResponse(response) {
87
+ if (this.abort.signal.aborted || response.source_digest !== this.digestValue) return this.restoreOriginal()
88
+ this.retryAvailable = false
89
+ if (response.status === 'failed') return this.showRetry()
90
+ if (response.status === 'completed') return this.show(response.content)
91
+ if (['pending', 'processing', 'translating'].includes(response.status)) {
92
+ this.toggleTarget.hidden = false
93
+ this.toggleTarget.disabled = true
94
+ this.setToggleLabel(this.loadingValue)
95
+ this.pollDelay = Math.min((this.pollDelay || 1000) * 2, 10000)
96
+ this.timer = setTimeout(() => this.load(), this.pollDelay)
97
+ } else {
98
+ this.restoreOriginal()
99
+ }
100
+ }
101
+
102
+ show(content) {
103
+ if (!content) return this.restoreOriginal()
104
+ this.contentTarget.innerHTML = renderCommentMarkdown(content)
105
+ this.contentTarget.dataset.rendered = 'true'
106
+ this.contentTarget.classList.add('comment-content', 'comment-translation-content')
107
+ this.showingTranslation = true
108
+ this.toggleTarget.hidden = false
109
+ this.toggleTarget.disabled = false
110
+ this.updateVisibility()
111
+ addTableDownloadButtons(this.contentTarget)
112
+ renderMermaidDiagrams(this.contentTarget)
113
+ }
114
+
115
+ toggle() {
116
+ if (this.retryAvailable) {
117
+ this.retryAvailable = false
118
+ this.pollDelay = 0
119
+ this.toggleTarget.disabled = true
120
+ this.setToggleLabel(this.loadingValue)
121
+ return this.load(true)
122
+ }
123
+ this.showingTranslation = !this.showingTranslation
124
+ this.updateVisibility()
125
+ }
126
+
127
+ updateVisibility() {
128
+ this.original.hidden = this.showingTranslation
129
+ this.contentTarget.hidden = !this.showingTranslation
130
+ this.setToggleLabel(this.showingTranslation ? this.originalValue : this.showTranslationValue)
131
+ this.toggleTarget.setAttribute('aria-pressed', String(this.showingTranslation))
132
+ }
133
+
134
+ showRetry() {
135
+ if (this.abort.signal.aborted) return this.restoreOriginal()
136
+ this.restoreOriginal(true)
137
+ this.retryAvailable = true
138
+ this.toggleTarget.hidden = false
139
+ this.toggleTarget.disabled = false
140
+ this.setToggleLabel(this.translateValue)
141
+ this.toggleTarget.setAttribute('aria-pressed', 'false')
142
+ }
143
+
144
+ setToggleLabel(label) {
145
+ this.toggleTarget.textContent = label
146
+ this.toggleTarget.title = label
147
+ this.toggleTarget.setAttribute('aria-label', label)
148
+ }
149
+
150
+ restoreOriginal(keepSourceObserver = false) {
151
+ this.retryAvailable = false
152
+ if (!keepSourceObserver) {
153
+ this.mutations?.disconnect()
154
+ this.mutations = null
155
+ }
156
+ if (this.original) this.original.hidden = false
157
+ this.contentTarget.hidden = true
158
+ this.contentTarget.replaceChildren()
159
+ this.toggleTarget.hidden = true
160
+ this.toggleTarget.disabled = false
161
+ this.toggleTarget.removeAttribute('aria-pressed')
162
+ }
163
+ }
@@ -0,0 +1,28 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+
3
+ // Shared broadcasts carry inert templates. Only this request-rendered reader
4
+ // controller can mount them, so the author/background user never sets the policy.
5
+ // Reader-gated templates follow this reader's preference; when it is off they stay
6
+ // inert, because the endpoint would only answer 403 for each visible comment.
7
+ export default class extends Controller {
8
+ static values = { enabled: { type: Boolean, default: true } }
9
+
10
+ connect() {
11
+ this.observer = new MutationObserver(() => this.hydrate())
12
+ this.observer.observe(document.body, { childList: true, subtree: true })
13
+ this.hydrate()
14
+ }
15
+
16
+ disconnect() {
17
+ this.observer.disconnect()
18
+ }
19
+
20
+ hydrate() {
21
+ const gated = this.enabledValue ? '' : ':not([data-comment-translation-reader-gated])'
22
+ document.querySelectorAll(`template[data-comment-translation-template]${gated}`).forEach(template => {
23
+ const fragment = template.content.cloneNode(true)
24
+ fragment.firstElementChild.setAttribute('data-controller', 'comment-translation')
25
+ template.replaceWith(fragment)
26
+ })
27
+ }
28
+ }
@@ -0,0 +1,178 @@
1
+ import { translationLocaleUrl } from "./translation_locale"
2
+ import { Controller } from "@hotwired/stimulus"
3
+ import { sanitizeDescriptionHtml } from "collavre/lib/utils/sanitize_description"
4
+ import csrfFetch from "collavre/lib/api/csrf_fetch"
5
+ import { LABEL, ROWS, PROTECTED, translationSource, translationContent, translationUrl, treeTranslation } from "./workspace_translation"
6
+
7
+
8
+ export default class extends Controller {
9
+ static values = { base: String, original: String, translated: String, auto: { type: Boolean, default: true } }
10
+
11
+ connect() {
12
+ this.rows = new Map()
13
+ // With automatic translation off, rows load only after the reader asks for it.
14
+ this.showTranslated = this.autoValue
15
+ this.manual = false
16
+ this.observer = new MutationObserver(() => this.scan())
17
+ this.observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-creative-id', 'data-original-label'] })
18
+ this.visibility = new IntersectionObserver(entries => {
19
+ entries.filter(entry => entry.isIntersecting).forEach(entry => {
20
+ this.visibility.unobserve(entry.target)
21
+ const state = this.rows.get(entry.target)
22
+ if (state) state.visible = true
23
+ if (this.showTranslated) this.load(entry.target)
24
+ })
25
+ })
26
+ this.scan()
27
+ }
28
+
29
+ scan() {
30
+ this.mountMenu()
31
+ this.rows.forEach((state, row) => {
32
+ if (!row.isConnected || row.dataset.creativeId !== state.id || translationSource(row) !== state.source ||
33
+ (state.content && state.content !== translationContent(row))) this.cleanup(row, state)
34
+ })
35
+ document.querySelectorAll(ROWS).forEach(row => {
36
+ if (this.rows.has(row) || !translationSource(row)) return
37
+ this.rows.set(row, { source: translationSource(row), id: row.dataset.creativeId, abort: new AbortController() })
38
+ this.visibility.observe(row)
39
+ })
40
+ }
41
+
42
+ async load(row, retryFailed = true) {
43
+ const state = this.rows.get(row)
44
+ if (!state) return
45
+ state.timer = undefined
46
+ state.loading = true
47
+ state.blocked = false
48
+ state.denied = false
49
+ // A reader request made while this row was busy also retries failed results.
50
+ retryFailed ||= state.retry
51
+ state.retry = false
52
+ try {
53
+ const url = this.requestUrl(translationLocaleUrl(translationUrl(this.baseValue, row)))
54
+ const request = async method => {
55
+ const response = await csrfFetch(url, { method, signal: state.abort.signal,
56
+ headers: { Accept: 'application/json' } })
57
+ if (response.status === 403 && new URL(url, window.location.origin).searchParams.has('manual')) state.denied = true
58
+ if (!response.ok) throw new Error('Translation unavailable')
59
+ return response.json()
60
+ }
61
+ let result = await request('GET')
62
+ if (['missing', 'pending'].includes(result.status) || (retryFailed && result.status === 'failed')) result = await request('POST')
63
+ if (state.abort.signal.aborted || translationSource(row) !== state.source) return
64
+ if (row.matches(LABEL)) {
65
+ result = treeTranslation(result, state.source, row)
66
+ if (!result) return
67
+ } else if (sanitizeDescriptionHtml(result.original_html) !== state.source) return
68
+ if (state.digest && state.digest !== result.source_digest) return
69
+ state.digest = result.source_digest
70
+ state.blocked = result.status === 'failed'
71
+ if (result.status === 'completed') this.show(row, state, JSON.parse(result.content))
72
+ else if (['pending', 'processing', 'translating'].includes(result.status)) {
73
+ state.delay = Math.min((state.delay || 500) * 2, 10000)
74
+ state.timer = setTimeout(() => this.load(row, false), state.delay)
75
+ }
76
+ } catch {
77
+ // Explicit policy denials cannot be retried by anonymous readers.
78
+ state.blocked = !state.denied
79
+ }
80
+ finally {
81
+ state.loading = false
82
+ this.updateMenu()
83
+ // Retry a reader request that arrived mid-flight if that request ended without a result.
84
+ if (state.retry && this.showTranslated && !state.nodes && !state.timer && !state.abort.signal.aborted) this.load(row)
85
+ }
86
+ }
87
+
88
+ // A reader's explicit request translates even when their automatic translation is off.
89
+ requestUrl(path) {
90
+ if (!this.manual) return path
91
+ const url = new URL(path, window.location.origin)
92
+ url.searchParams.set('manual', '1')
93
+ return url.pathname + url.search
94
+ }
95
+
96
+ show(row, state, replacements) {
97
+ const content = translationContent(row)
98
+ if (!content || state.nodes) return
99
+ state.content = content
100
+ const translations = new Map(replacements.map(pair => [pair.original, pair.translated]))
101
+ state.nodes = []
102
+ const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT)
103
+ while (walker.nextNode()) {
104
+ const node = walker.currentNode
105
+ if (!node.parentElement.closest(PROTECTED) && translations.has(node.textContent)) {
106
+ state.nodes.push({ node, original: node.textContent, translated: translations.get(node.textContent) })
107
+ }
108
+ }
109
+ if (!state.nodes.length) return
110
+ state.exportHandler = event => {
111
+ if (!state.translated || !event.target.closest('.table-download-btn')) return
112
+ this.toggle(state)
113
+ setTimeout(() => {
114
+ if (!state.abort.signal.aborted && !state.translated) this.toggle(state)
115
+ }, 0)
116
+ }
117
+ row.addEventListener('click', state.exportHandler, true)
118
+ this.toggle(state, this.showTranslated)
119
+ }
120
+
121
+ toggle(state, translated = !state.translated) {
122
+ state.translated = translated
123
+ state.nodes.forEach(({ node, original, translated }) => { node.textContent = state.translated ? translated : original })
124
+
125
+ }
126
+
127
+ mountMenu() {
128
+ const menu = document.getElementById('creative-overflow-menu')
129
+ if (!menu || this.menuButton?.parentElement === menu) return
130
+ this.menuButton?.remove()
131
+ this.menuButton = document.createElement('button')
132
+ this.menuButton.type = 'button'
133
+ this.menuButton.className = 'popup-menu-item creative-translation-toggle'
134
+ this.menuButton.addEventListener('click', () => {
135
+ this.showTranslated = this.translationActionAvailable
136
+ if (this.showTranslated) this.manual = true
137
+ this.rows.forEach((state, row) => {
138
+ if (state.nodes) this.toggle(state, this.showTranslated)
139
+ else if (!this.showTranslated || !state.visible) return
140
+ else if (state.loading || state.timer) state.retry = true
141
+ else this.load(row)
142
+ })
143
+ this.updateMenu()
144
+ })
145
+ this.updateMenu()
146
+ menu.append(this.menuButton)
147
+ }
148
+
149
+ get translationActionAvailable() {
150
+ // Unavailable translations offer retry unless an explicit request was denied.
151
+ return !this.showTranslated || [...this.rows.values()].some(state => state.visible && state.blocked)
152
+ }
153
+
154
+ updateMenu() {
155
+ if (!this.menuButton) return
156
+ this.menuButton.textContent = this.translationActionAvailable ? this.translatedValue : this.originalValue
157
+ this.menuButton.setAttribute('aria-pressed', String(!this.translationActionAvailable))
158
+ }
159
+
160
+ cleanup(row, state) {
161
+ state.abort.abort()
162
+ clearTimeout(state.timer)
163
+ this.visibility.unobserve(row)
164
+ state.nodes?.forEach(({ node, original, translated }) => {
165
+ if (node.isConnected && node.textContent === translated) node.textContent = original
166
+ })
167
+ if (state.exportHandler) row.removeEventListener("click", state.exportHandler, true)
168
+ this.rows.delete(row)
169
+ this.updateMenu()
170
+ }
171
+
172
+ disconnect() {
173
+ this.menuButton?.remove()
174
+ this.observer.disconnect()
175
+ this.visibility.disconnect()
176
+ this.rows.forEach((state, row) => this.cleanup(row, state))
177
+ }
178
+ }
@@ -0,0 +1,12 @@
1
+ import CreativeTranslationsController from "./creative_translations_controller"
2
+ import TranslationPreferenceController from "./translation_preference_controller"
3
+ import CommentTranslationController from "./comment_translation_controller"
4
+
5
+ import CommentTranslationReaderController from "./comment_translation_reader_controller"
6
+
7
+ export function registerControllers(application) {
8
+ application.register("creative-translations", CreativeTranslationsController)
9
+ application.register("translation-preference", TranslationPreferenceController)
10
+ application.register("comment-translation-reader", CommentTranslationReaderController)
11
+ application.register("comment-translation", CommentTranslationController)
12
+ }
@@ -0,0 +1,8 @@
1
+ // Keep a page's testing override on every cache lookup, enqueue and poll.
2
+ export function translationLocaleUrl(path) {
3
+ const lang = new URLSearchParams(window.location.search).get('lang')
4
+ if (!lang) return path
5
+ const url = new URL(path, window.location.origin)
6
+ url.searchParams.set('lang', lang)
7
+ return url.pathname + url.search
8
+ }
@@ -0,0 +1,13 @@
1
+ import { Controller } from '@hotwired/stimulus'
2
+
3
+ export default class extends Controller {
4
+ connect() {
5
+ this.form = this.element.closest('form')
6
+ this.clearCache = () => window.Turbo.cache.clear()
7
+ this.form.addEventListener('turbo:submit-start', this.clearCache)
8
+ }
9
+
10
+ disconnect() {
11
+ this.form.removeEventListener('turbo:submit-start', this.clearCache)
12
+ }
13
+ }
@@ -0,0 +1,46 @@
1
+ import { sanitizeDescriptionHtml } from "collavre/lib/utils/sanitize_description"
2
+
3
+ export const LABEL = '.creative-workspace-tree-link, [data-translation-label]'
4
+ export const ROWS = `creative-tree-row[creative-id], ${LABEL}`
5
+ export const PROTECTED = 'pre, code, script, style, textarea, .mention, [data-mention], [data-lexical-mention], [contenteditable], [data-ppt-slide]'
6
+
7
+ export function translationSource(row) {
8
+ return row.matches(LABEL) ? row.dataset.originalLabel : row.descriptionHtml
9
+ }
10
+
11
+ export function translationContent(row) {
12
+ return row.matches(LABEL) ? row : row.querySelector('.creative-content, .creative-title-content')
13
+ }
14
+
15
+ // Tree labels come from the stored description, so ask for it unembedded.
16
+ export function translationUrl(base, row) {
17
+ const url = base.replace('__ID__', row.getAttribute('creative-id') || row.dataset.creativeId)
18
+ return row.matches(LABEL) ? `${url}?embed=0` : url
19
+ }
20
+
21
+ function label(content) {
22
+ return content.textContent.replace(/\s+/gu, ' ').trim()
23
+ }
24
+
25
+ export function treeTranslation(result, source, row) {
26
+ const content = document.createElement('div')
27
+ content.innerHTML = sanitizeDescriptionHtml(result.original_html)
28
+ const original = truncateLabel(label(content), row)
29
+ if (original !== source) return null
30
+ if (result.status !== 'completed') return result
31
+ const replacements = new Map(JSON.parse(result.content).map(pair => [pair.original, pair.translated]))
32
+ const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT)
33
+ while (walker.nextNode()) {
34
+ const node = walker.currentNode
35
+ if (!node.parentElement.closest(PROTECTED) && replacements.has(node.textContent)) {
36
+ node.textContent = replacements.get(node.textContent)
37
+ }
38
+ }
39
+ return { ...result, content: JSON.stringify([{ original, translated: truncateLabel(label(content), row) }]) }
40
+ }
41
+
42
+ function truncateLabel(text, row) {
43
+ const length = Number(row?.dataset.translationLength)
44
+ const chars = Array.from(text)
45
+ return length > 0 && chars.length > length ? chars.slice(0, length - 3).join('') + '...' : text
46
+ }
@@ -0,0 +1,66 @@
1
+ module CollavreTranslation
2
+ class TranslateJob < ::ApplicationJob
3
+ queue_as :translations
4
+
5
+ def perform(id)
6
+ record = Translation.find_by(id: id)
7
+ return unless record && claim(record)
8
+ return update_claim(record, status: "pending") unless CollavreTranslation.enabled?
9
+
10
+ translate(record)
11
+ rescue ActiveRecord::RecordNotFound
12
+ owned_claim(record).destroy_all if record && @claimed_at
13
+ rescue StandardError => error
14
+ Rails.logger.warn("Comment translation failed: #{error.class}")
15
+ update_claim(record, status: "failed", content: nil, updated_at: Time.current) if record && @claimed_at
16
+ end
17
+
18
+ private
19
+
20
+ def claim(record)
21
+ @claimed_at = Time.current
22
+ candidates = Translation.where(id: record.id, status: "processing")
23
+ .or(Translation.where(id: record.id, status: "translating")
24
+ .where("updated_at < ?", Translation::CLAIM_TIMEOUT.ago))
25
+ candidates.update_all(status: "translating", updated_at: @claimed_at) == 1
26
+ end
27
+
28
+ # updated_at is the lease token; intermediate writes must keep it unchanged.
29
+ # A recovered worker cannot publish or fail a replacement worker's claim.
30
+ def owned_claim(record)
31
+ Translation.where(id: record.id, status: "translating", updated_at: @claimed_at)
32
+ end
33
+
34
+ def update_claim(record, **attributes)
35
+ owned_claim(record).update_all(attributes)
36
+ end
37
+
38
+ def translate(record)
39
+ comment = record.translatable
40
+ return owned_claim(record).destroy_all unless comment
41
+ return update_claim(record, status: "skipped") unless current_source?(record, comment)
42
+
43
+ source = Translation.source(comment)
44
+ prose = comment.is_a?(Collavre::Creative) ? HtmlTranslator.texts(source).join(" ") : source
45
+ return update_claim(record, status: "skipped") unless LanguageDetector.translatable?(prose)
46
+
47
+ source_lang = LanguageDetector.detect(prose)
48
+ update_claim(record, source_lang: source_lang)
49
+ return update_claim(record, status: "skipped") if (source_lang.nil? && !comment.is_a?(Collavre::Creative)) || source_lang == record.target_locale
50
+
51
+ vendor = CollavreTranslation.vendor
52
+ model = CollavreTranslation.model
53
+ translator = comment.is_a?(Collavre::Creative) ? HtmlTranslator : Translator
54
+ content = translator.call(source, record.target_locale, vendor: vendor, model: model)
55
+ # Never publish a result for a source edited while the provider was running.
56
+ return update_claim(record, status: "skipped") unless current_source?(record, comment.reload)
57
+
58
+ update_claim(record, content: content, status: "completed",
59
+ llm_vendor: vendor, llm_model: model)
60
+ end
61
+
62
+ def current_source?(record, comment)
63
+ Translation.digest(Translation.source(comment)) == record.source_digest
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,54 @@
1
+ module CollavreTranslation
2
+ class Translation < Collavre::ApplicationRecord
3
+ CLAIM_TIMEOUT = 5.minutes
4
+ RETRY_COOLDOWN = 1.minute
5
+
6
+ belongs_to :translatable, polymorphic: true
7
+ validates :target_locale, inclusion: { in: %w[en ko] }
8
+ validates :status, inclusion: { in: %w[pending processing translating completed skipped failed] }
9
+ validates :source_digest, presence: true
10
+
11
+ def stale_claim?
12
+ status == "translating" && updated_at < CLAIM_TIMEOUT.ago
13
+ end
14
+
15
+ def self.digest(content)
16
+ Digest::SHA256.hexdigest(content.to_s)
17
+ end
18
+
19
+ def self.source(record)
20
+ record.is_a?(Collavre::Creative) ? record.effective_description : record.content
21
+ end
22
+
23
+ def self.for_creative(creative, locale)
24
+ for_comment(creative.effective_origin, locale)
25
+ end
26
+
27
+ def self.for_comment(comment, locale)
28
+ record = find_by(translatable: comment, target_locale: locale, source_digest: digest(source(comment)))
29
+ record&.stale_claim? ? request!(comment, locale) : record
30
+ end
31
+
32
+ def self.retryable_failures(record, source)
33
+ failures = where(id: record.id, status: "failed")
34
+ source.is_a?(Collavre::Creative) ? failures.where("updated_at <= ?", RETRY_COOLDOWN.ago) : failures
35
+ end
36
+
37
+ def self.request!(comment, locale)
38
+ record = create_or_find_by!(translatable: comment, target_locale: locale,
39
+ source_digest: digest(source(comment)))
40
+ # A compare-and-swap also recovers an enqueue failure without duplicate jobs.
41
+ claimed = where(id: record.id, status: "pending").or(retryable_failures(record, comment)).or(where(id: record.id, status: "translating")
42
+ .where("updated_at < ?", CLAIM_TIMEOUT.ago)).update_all(status: "processing", updated_at: Time.current)
43
+ if claimed == 1
44
+ begin
45
+ TranslateJob.perform_later(record.id)
46
+ rescue StandardError
47
+ where(id: record.id, status: "processing").update_all(status: "pending", updated_at: Time.current)
48
+ raise
49
+ end
50
+ end
51
+ record.reload
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,18 @@
1
+ module CollavreTranslation
2
+ class ContentTranslationPolicy
3
+ def self.enabled?(record, reader)
4
+ return CollavreTranslation.enabled_for?(record.user) if public_content?(record)
5
+
6
+ CreativeTranslationPolicy.enabled?(reader)
7
+ end
8
+
9
+ # Public content follows its author's preference, so the answer is the same
10
+ # for every reader and shared markup can decide it without a request.
11
+ def self.public_content?(record)
12
+ creative = record.is_a?(Collavre::Comment) ? record.creative : record.effective_origin
13
+ public_content = creative.has_permission?(nil, :read)
14
+ public_content &&= !record.private? if record.is_a?(Collavre::Comment)
15
+ public_content
16
+ end
17
+ end
18
+ end