SVGWrapper.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (C) 2015 - present Instructure, Inc.
  3. *
  4. * This file is part of Canvas.
  5. *
  6. * Canvas is free software: you can redistribute it and/or modify it under
  7. * the terms of the GNU Affero General Public License as published by the Free
  8. * Software Foundation, version 3 of the License.
  9. *
  10. * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
  11. * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  13. * details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License along
  16. * with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. import React from 'react'
  19. import PropTypes from 'prop-types'
  20. import $ from 'jquery'
  21. const DOCUMENT_NODE = 9;
  22. const ELEMENT_NODE = 1;
  23. class SVGWrapper extends React.Component {
  24. static propTypes = {
  25. url: PropTypes.string.isRequired,
  26. fillColor: PropTypes.string
  27. }
  28. componentDidMount () {
  29. this.fetchSVG();
  30. }
  31. componentWillReceiveProps (newProps) {
  32. if (newProps.url !== this.props.url) {
  33. this.fetchSVG();
  34. }
  35. }
  36. fetchSVG () {
  37. $.ajax(this.props.url, {
  38. success: function (data) {
  39. this.svg = data;
  40. if (data.nodeType === DOCUMENT_NODE) {
  41. this.svg = data.firstChild;
  42. }
  43. if (this.svg.nodeType !== ELEMENT_NODE && this.svg.nodeName !== 'SVG') {
  44. throw new Error(`SVGWrapper: SVG Element must be returned by request to ${this.props.url}`);
  45. }
  46. if (this.props.fillColor) {
  47. this.svg.setAttribute('style', `fill:${this.props.fillColor}`);
  48. }
  49. this.svg.setAttribute('focusable', false);
  50. this.rootSpan.appendChild(this.svg);
  51. }.bind(this)
  52. });
  53. }
  54. render () {
  55. return <span ref={(c) => { this.rootSpan = c; }} />;
  56. }
  57. }
  58. export default SVGWrapper