Msg.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2018 Red Hat, Inc. and/or its affiliates.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import * as React from "../../../common/keycloak/web_modules/react.js";
  17. export class Msg extends React.Component {
  18. constructor(props) {
  19. super(props);
  20. }
  21. render() {
  22. if (this.props.children) {
  23. return Msg.localizeWithChildren(this.props.msgKey, this.props.children);
  24. }
  25. return React.createElement(React.Fragment, null, Msg.localize(this.props.msgKey, this.props.params));
  26. }
  27. static localizeWithChildren(msgKey, children) {
  28. const message = l18nMsg[this.processKey(msgKey)];
  29. const parts = message.split(/\{\{param_\d*}}/);
  30. const count = React.Children.count(children);
  31. return React.Children.map(children, (child, i) => [parts[i], child, count === i + 1 ? parts[count] : '']);
  32. }
  33. static localize(msgKey, params) {
  34. let message = l18nMsg[this.processKey(msgKey)];
  35. if (message === undefined) message = msgKey;
  36. if (params !== undefined && params.length > 0) {
  37. params.forEach((value, index) => {
  38. value = this.processParam(value);
  39. message = message.replace('{{param_' + index + '}}', value);
  40. });
  41. }
  42. return unescape(message);
  43. } // if the message key has Freemarker syntax, remove it
  44. static processKey(msgKey) {
  45. if (!(msgKey.startsWith('${') && msgKey.endsWith('}'))) return msgKey; // remove Freemarker syntax
  46. return msgKey.substring(2, msgKey.length - 1);
  47. } // if the param has Freemarker syntax, try to look up its value
  48. static processParam(param) {
  49. if (!(param.startsWith('${') && param.endsWith('}'))) return param; // remove Freemarker syntax
  50. const key = param.substring(2, param.length - 1);
  51. let value = l18nMsg[key];
  52. if (value === undefined) return param;
  53. return value;
  54. }
  55. }
  56. //# sourceMappingURL=Msg.js.map