FluentResource.cpp (2325B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "nsContentUtils.h" 8 #include "FluentResource.h" 9 10 using namespace mozilla::dom; 11 12 namespace mozilla { 13 namespace intl { 14 15 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(FluentResource, mParent) 16 17 FluentResource::FluentResource(nsISupports* aParent, 18 const ffi::FluentResource* aRaw) 19 : mParent(aParent), mRaw(std::move(aRaw)), mHasErrors(false) {} 20 21 FluentResource::FluentResource(nsISupports* aParent, const nsACString& aSource) 22 : mParent(aParent), mHasErrors(false) { 23 mRaw = dont_AddRef(ffi::fluent_resource_new(&aSource, &mHasErrors)); 24 } 25 26 already_AddRefed<FluentResource> FluentResource::Constructor( 27 const GlobalObject& aGlobal, const nsACString& aSource) { 28 RefPtr<FluentResource> res = 29 new FluentResource(aGlobal.GetAsSupports(), aSource); 30 31 if (res->mHasErrors) { 32 nsContentUtils::LogSimpleConsoleError( 33 u"Errors encountered while parsing Fluent Resource."_ns, "chrome"_ns, 34 false, true /* from chrome context*/); 35 } 36 return res.forget(); 37 } 38 39 void FluentResource::TextElements( 40 nsTArray<dom::FluentTextElementItem>& aElements, ErrorResult& aRv) { 41 if (mHasErrors) { 42 aRv.ThrowInvalidStateError("textElements don't exist due to parse error"); 43 return; 44 } 45 46 nsTArray<ffi::TextElementInfo> elements; 47 ffi::fluent_resource_get_text_elements(mRaw, &elements); 48 49 auto maybeAssign = [](dom::Optional<nsCString>& aDest, nsCString&& aSrc) { 50 if (!aSrc.IsEmpty()) { 51 aDest.Construct() = std::move(aSrc); 52 } 53 }; 54 55 for (auto& info : elements) { 56 dom::FluentTextElementItem item; 57 maybeAssign(item.mId, std::move(info.id)); 58 maybeAssign(item.mAttr, std::move(info.attr)); 59 maybeAssign(item.mText, std::move(info.text)); 60 61 aElements.AppendElement(item); 62 } 63 } 64 65 JSObject* FluentResource::WrapObject(JSContext* aCx, 66 JS::Handle<JSObject*> aGivenProto) { 67 return FluentResource_Binding::Wrap(aCx, this, aGivenProto); 68 } 69 70 } // namespace intl 71 } // namespace mozilla