preview.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * Blockly Demos: Block Factory
  3. *
  4. * Copyright 2013 Google Inc.
  5. * https://developers.google.com/blockly/
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /**
  20. * @fileoverview JavaScript for Blockly's Block Factory preview.
  21. * @author fraser@google.com (Neil Fraser)
  22. */
  23. 'use strict';
  24. /**
  25. * The uneditable preview block.
  26. * @type {Blockly.Block}
  27. */
  28. var previewBlock = null;
  29. /**
  30. * Create the specified block in this preview pane.
  31. * @param {string} type Name of block.
  32. * @param {string} code JavaScript code to create a block.
  33. */
  34. function updateFunc(type, code) {
  35. if (previewBlock) {
  36. previewBlock.dispose();
  37. previewBlock = null;
  38. }
  39. eval(code);
  40. // Create the preview block.
  41. previewBlock = Blockly.Block.obtain(Blockly.mainWorkspace, type);
  42. previewBlock.initSvg();
  43. previewBlock.render();
  44. previewBlock.setMovable(false);
  45. previewBlock.setDeletable(false);
  46. previewBlock.moveBy(15, 10);
  47. }
  48. /**
  49. * Initialize Blockly. Called on page load.
  50. */
  51. function init() {
  52. var rtl = (document.location.search == '?rtl');
  53. Blockly.inject(document.body, {rtl: rtl});
  54. try {
  55. // Let the top-level application know that Blockly is ready.
  56. window.parent.initPreview(updateFunc);
  57. } catch (e) {
  58. // Attempt to diagnose the problem.
  59. var msg = 'Error: Unable to communicate between frames.\n' +
  60. 'The preview frame will not be functional.\n\n';
  61. if (window.parent == window) {
  62. msg += 'Try loading index.html instead of preview.html';
  63. } else if (window.location.protocol == 'file:') {
  64. msg += 'This may be due to a security restriction preventing\n' +
  65. 'access when using the file:// protocol.\n\n' +
  66. 'Try using a different browser, or use the Block Factory online at:\n' +
  67. 'https://blockly-demo.appspot.com/static/demos/blockfactory/index.html';
  68. }
  69. alert(msg);
  70. }
  71. }
  72. window.addEventListener('load', init);