discourse-translator/assets/javascripts/discourse/components/post-menu/toggle-translation-button.gjs
Natalie Tay 6e8b183a6a
FEATURE: Allow untranslated posts in inline-translation mode to be manually translated (#230)
Currently the 🌐 only appears in dual-text mode (not inline translation mode) when the `experimental_topic_translation` feature is disabled. This means we are unable to translate old posts when in `experimental_topic_translation`.

This PR allows 🌐 to show up when `experimental_topic_translation` is enabled, and does not show the dual-text translation below (the old method) but replaces the content inline instead.

In addition in this PR, when `experimental_topic_translation` is enabled, it takes the response from /translate and updates the post cooked and topic title for inline replacement. (in other scenarios, translation updates are done by messagebus)

(also backfills many untested js files)
2025-02-27 13:50:53 +08:00

85 lines
2 KiB
Text

import Component from "@glimmer/component";
import { action } from "@ember/object";
import { service } from "@ember/service";
import DButton from "discourse/components/d-button";
import concatClass from "discourse/helpers/concat-class";
import { popupAjaxError } from "discourse/lib/ajax-error";
export default class ToggleTranslationButton extends Component {
static shouldRender(args) {
return args.post.can_translate;
}
@service modal;
@service translator;
get isTranslating() {
return this.args.post.isTranslating;
}
get isTranslated() {
return this.args.post.isTranslated;
}
get showButton() {
return this.args.post.can_translate;
}
get title() {
if (this.isTranslating) {
return "translator.translating";
}
return this.isTranslated
? "translator.hide_translation"
: "translator.view_translation";
}
@action
hideTranslation() {
this.args.post.isTranslated = false;
this.args.post.isTranslating = false;
this.translator.clearPostTranslation(this.args.post);
}
@action
toggleTranslation() {
return this.args.post.isTranslated
? this.hideTranslation()
: this.translate();
}
@action
async translate() {
const post = this.args.post;
post.isTranslating = true;
try {
await this.translator.translatePost(post);
post.isTranslated = true;
} catch (error) {
this.translator.clearPostTranslation(this.args.post);
post.isTranslated = false;
popupAjaxError(error);
} finally {
post.isTranslating = false;
}
}
<template>
{{#if this.showButton}}
<DButton
class={{concatClass
"post-action-menu__translate"
(if this.isTranslated "translated")
}}
...attributes
@action={{this.toggleTranslation}}
@disabled={{this.isTranslating}}
@icon="globe"
@label={{if @showLabel this.title}}
@title={{this.title}}
/>
{{/if}}
</template>
}