Giter VIP home page Giter VIP logo

ngx-blockly's People

Contributors

dependabot[bot] avatar iblacki avatar kencwlau avatar lambainsaan avatar markfinn avatar mirkowerner avatar ncc1701m avatar patboe avatar roroettg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-blockly's Issues

Cannot reopen Blockly component with custom theme

When I use a custom theme, initializing it like so:
config: NgxBlocklyConfig = { ... theme: exampleTheme.createBlocklyTheme()
and the theme:

export const blockStyles: BlockStyles = {
    logic_blocks: {
        colourPrimary: '#997710',
    },
    math_blocks: {
        colourPrimary: '#521f73',
    },
    control_blocks: {
        colourPrimary: '#005a16',
    }
};
export const categoryStyles: CategoryStyles = {
    logic_category: {
        colour: '#997710',
    },
    math_category: {
        colour: '#521f73',
    },
    control_category: {
        colour: '#005a16',
    },
};
export const componentStyle: ComponentStyle = {
    workspaceBackgroundColour: '#2c2c2c',
    toolboxBackgroundColour: '#3d3d3d',
    scrollbarColour: '#ba131b',
    insertionMarkerColour: '#2fff00',
    insertionMarkerOpacity: 0.2,
    flyoutBackgroundColour: '#2e2e2e',
    flyoutOpacity: 1
};
export const exampleTheme: Theme = new Theme (
    'ThemeName',
    blockStyles,
    categoryStyles,
    componentStyle
);

I can only open it once. When I go to another component and go back I'm receiving a following message:

ERROR Error: Uncaught (in promise): Error: Name "themename" with type "theme" already registered.
Error: Name "themename" with type "theme" already registered.
at Object.Blockly.registry.register (blockly_compressed.js:18)
at new Blockly.Theme (blockly_compressed.js:127)
at Theme.createBlocklyTheme (ngx-blockly.js:630)
at new CompleteScriptUpdateComponent (complete-script-update.component.ts:133)
at NodeInjectorFactory.CompleteScriptUpdateComponent_Factory [as factory] (complete-script-update.component.ts:309)
at getNodeInjectable (core.js:4274)
at instantiateRootComponent (core.js:7972)
at createRootComponent (core.js:13488)
at ComponentFactory$1.create (core.js:24047)
at ViewContainerRef.createComponent (core.js:10151)
at resolvePromise (zone-evergreen.js:798)
at resolvePromise (zone-evergreen.js:750)
at zone-evergreen.js:860
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27492)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at drainMicroTaskQueue (zone-evergreen.js:569)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
at invokeTask (zone-evergreen.js:1621)

Bug when using FieldTextInput or FieldDropdown

When I want to use an input or dropdown in a custom block, it selects and won't unselect when I try to use the input or dropdown. When I do, it prints the following error message:

ERROR TypeError: a is undefined
render blockly_compressed.js:564
showEditor_ blockly_compressed.js:1126
showEditor blockly_compressed.js:491
doFieldClick_ blockly_compressed.js:473
handleUp blockly_compressed.js:467
handleUp blockly_compressed.js:701
h blockly_compressed.js:854
Angular 14
bindEvent_ blockly_compressed.js:856
bindDocumentEvents_ blockly_compressed.js:791
init_ blockly_compressed.js:789
inject blockly_compressed.js:782
ngAfterViewInit ngx-blockly.js:96
Angular 25
RxJS 5
Angular 19
RxJS 5
Angular 15
core.js:6140

Tried to start the same gesture twice. 2 blockly_compressed.js:780:261

Trying to end a gesture recursively. blockly_compressed.js:467:92

This is what my defineBlock code looks like:

  defineBlock(): any {
    // set name
    this.block.appendValueInput('FIRST')
    this.block.appendDummyInput().appendField(new Blockly.FieldDropdown([
      ["==", "EQ"],
      ["!=", "NE"],
      [">", "GT"],
      [">=", "GTE"],
      ["<", "LT"],
      ["<=", "LTE"]
    ]), 'FUNCTION');
    this.block.appendValueInput('SECOND')
    //set content
    this.block.setColour(20)
    this.block.setTooltip('Compare two values')
    this.block.setHelpUrl('')
    this.block.setPreviousStatement(true)
    this.block.setNextStatement(true)
  }

appendFromXml not working.

i'm trying to append any block from previously defined xml, like:

But nothing happen, it just doesn't work at all. Before that, i'm using "fromXml" (which clear the previous content, something that i don't want to do when i call appendFromXml). fromXml works, just with an error at the console: ERROR TypeError: Cannot read property 'setResizesEnabled' of undefined
at Object.Blockly.Xml.clearWorkspaceAndLoadFromXml (blockly_compressed.js:181)
at NgxBlocklyComponent.fromXml (ngx-blockly.js:398).

Thats my code where i try to append a block that comes from database at the workspace:
let saved = localStorage.getItem('saved_workspace');
if (saved)
this.workspace.fromXml(saved);
this.workspace.appendFromXml(this.globals.xml);

Problem with readonly flag

Shouldn't the readonly flag be readOnly in NgxBlocklyConfig type declaration?

readOnly option is case-sensitive in Blockly library, but NgxBlocklyConfig type declaration expects readonly (lowercase)

blockly docs ref

Missed "scripts" and "services" folder during npm package download from version 10.1.3

Good Morning,
In the past few days the directories "scripts" and "services" were no longer contained in the "node_modules/ngx-blockly" package with version 10.1.3. Yesterday around 2 p.m. these were available again. I cannot explain the behavior for versions that have existed for a long time. I was looking for a way to inform you about this. Currently that is no longer a problem. Everything works fine now. But you have to know this what happend.

Greetings from Germay (Lübeck) ;-)

readme update required

I am trying to build angular app using this demo.
I do not see the files like node_modules/ngx-blockly/scripts/blockly/blockly_compressed.js
Readme seems to be not updated. Please check.
Thanks

Dropdown Options on workspace not appearing

Hi,
I am new in Blockly and found this wrapper quite impressive. I am using default block of "logic_operation" which is supposed to compare values. Things are working fine except the context menu on the workspace is not appearing. It is happening for everything. I mean the context menu is not coming for any of the block like variable change etc.

image

Am i missing anything to get the context menu.

My angular.json file import

"scripts": [
"node_modules/ngx-blockly/scripts/blockly/blockly_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/blocks_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/msg/js/en.js",
"node_modules/ngx-blockly/scripts/blockly/javascript_compressed.js"
],

Toolbox definition:

{
kind: "category",
name: "Logic",
contents: [{
kind: "block",
type: "logic_compare"
}, {
kind: "block",
type: "logic_operation"
}, {
kind: "block",
type: "logic_boolean"
}]
}

Config:

config: NgxBlocklyConfig = {
toolbox: this.customToolbox,
comments: true,
trashcan: true,
zoom: {
controls: true,
wheel: false
}
};

Please help.

Thanks,
Arindam

Add custom block array

Hello,
How could I add customBlock dynamically?
Something like the example below.
I tried to use a loop and add to the CustomBlock array, but it is not displayed in the toolbox.
Any idea?

this.array.forEach((item) => {
          this.customBlocks.push(new TestBlock('test', null, null));
  });

Can i receive code when i drag custom block in angular ?

Custom block

import { Blockly, CustomBlock } from "ngx-blockly";

export class ToogleLed extends CustomBlock {
  constructor() {
    // Add Mutator or further args if needed
    super('ToogleLed');
    this.class = ToogleLed;
  }

  defineBlock() {
    this.block.appendDummyInput()
      .appendField("Chớp tắt Led")
      .appendField(new Blockly.FieldColour("#ff0000"), "NAME")
      .appendField(new Blockly.FieldImage("https://www.gstatic.com/codesite/ph/images/star_on.gif", 15, 15, "*"));
    this.block.setPreviousStatement(true, null);
    this.block.setNextStatement(true, null);
    this.block.setColour(330);
    this.block.setTooltip('');
    this.block.setHelpUrl('http://www.example.com/');
  }

  public  override toJavaScriptCode(block: Blockly.Block): string | any[] {
    return 'console.log();';
  }

  override  onChange(changeEvent: any) {
    console.log(changeEvent);
  }
}

Code in html
<ngx-blockly #blockly [config]="config" [customBlocks]="customBlocks" (javascriptCode)="onCode($event)"> </ngx-blockly>

In ts file

public config: NgxBlocklyConfig = {
    trashcan: true,
    generators: [
       NgxBlocklyGenerator.DART,
       NgxBlocklyGenerator.LUA,
       NgxBlocklyGenerator.JAVASCRIPT,
       NgxBlocklyGenerator.PHP,
       NgxBlocklyGenerator.PYTHON,
       NgxBlocklyGenerator.XML
    ],
    defaultBlocks: true,
    renderer: 'zelos',
    zoom: {
      controls: true,
      wheel: false
    },
    move: {
      scrollbars: true,
      wheel: true
    }
  };

ngOnInit(): void {
    const workspace = new Blockly.WorkspaceSvg(new Blockly.Options({}));
    const toolbox: NgxBlocklyToolbox = new NgxBlocklyToolbox(workspace);
    toolbox.nodes = [
      LOGIC_CATEGORY,
      new Category("Robot", "#ff9800", [
        ...this.customBlocks,
      ]),
      LOOP_CATEGORY,
      MATH_CATEGORY,
      TEXT_CATEGORY,
      LISTS_CATEGORY,
      COLOUR_CATEGORY,
      new Separator(),
      VARIABLES_CATEGORY,
      FUNCTIONS_CATEGORY,
    ];
    this.config.toolbox = toolbox.toXML();

    }
  public onCode(code: string) {
    console.log("hi");
    console.log(code);
  }

Angular.json

"scripts": [
              "node_modules/blockly/blockly_compressed.js",
              "node_modules/blockly/blocks_compressed.js",
              "node_modules/blockly/msg/vi.js",
              "node_modules/blockly/javascript_compressed.js"

            ]

I can not receive the code generation. Are you have idea ?
I use ngx-blockly version "ngx-blockly": "^12.0.2",

Accessing statement blocks of an input

Hi,
I have a custom block that has a statement input named "UPDATE_SCRIPT". How could I access all the statements that have been inserted in this input?

I tried something like

toLuaCode(block: CustomBlock): string | any[] {
...
let child_block=block.block.getInputTargetBlock('UPDATE_SCRIPT');

    if(child_block)
    do{
        // do something here with each statement block that was inserted in the statement input
    }while (child_block = child_block.getNextBlock());

...
}
but I get an error TypeError: Cannot read property 'getInputTargetBlock' of undefined
Thank you very much for your help.

override existing code generator

Hello,
is there a way to override the current behavior of the Blockly.Lua['procedures_defreturn'] function?

I would like to implement some extra actions when this function is called
Thank you very much for your help

Add custom block to the main workspace

Hi,
I am wondering how to add a custom block to the mainworkspace programatically. Something like
Blockly.mainWorkspace.newBlock(...) but in my case I have a CustomBlock class named GameObjectNamesBlock and I need to invoke its constructor to pass some initial values
Thank you very much for your help

Readonly disappears forever if window is resized while not readonly

If anything calls Blockly.svgResize while readonly is false you will never see the readonly workspace again unless you call Blockly.svgResize again. Blockly.svgResize is called a lot in my code for dynamic reflows, but it's also easy to trigger in NGX-Blockly itself by resizing the browser window.

The cause is that when the secondaryContainer div is hidden it will report a size of 0x0 and Blockly.svgResize will smash the blockly workspace down to that invisible size. That's fine while hidden, but when you un-hide, the SVG workspace is still 0x0. The fix is to call svgResize after removing the hidden class from secondaryContainer:

     public setReadonly(readOnly: boolean) {
         this.readOnly = readOnly;
         if (readOnly) {
             this.secondaryContainer.nativeElement.classList.remove('hidden');
             if (!this._secondaryWorkspace) {
                 const config = {...this.config};
                 config.readOnly = true;
                 this._secondaryWorkspace = Blockly.inject(this.secondaryContainer.nativeElement, config);
             }
             Blockly.Xml.clearWorkspaceAndLoadFromXml(Blockly.Xml.textToDom(this.toXml()), this._secondaryWorkspace);
+            Blockly.svgResize(this._secondaryWorkspace);
         } else {
             if (this._secondaryWorkspace) {
                 this.secondaryContainer.nativeElement.classList.add('hidden');

Note that this fix alone actually doesn't work yet because of a Blockly issue but I have a fix requested over there too. At the moment I have both this change and that one monkey-patched in and everything works as expected when the widows is resized in either state.

Thanks!

ReadOnly property not working

I am using version : 10.1.4 , and in the config.json file setting the readonly flag true should disable editing , it doesn't. Can you help me here ?

ReferenceError: Blockly is not defined - Angular 8

Hello,

I am facing an error when using the ngx-blockly module in my Angular 8.1.0 app (running with Node 10.16.0 and npm 6.9.0).
I exactly followed the setup steps described in the Github page but I get an error, which seems to arise within the file ngx-blockly.js (line 125).
The complete error message is:

ERROR ReferenceError: Blockly is not defined
    at NgxBlocklyComponent.ngAfterViewInit (ngx-blockly.js:125)
    at callProviderLifecycles (core.js:28194)
    at callElementProvidersLifecycles (core.js:28159)
    at callLifecycleHooksChildrenFirst (core.js:28141)
    at checkAndUpdateView (core.js:38380)
    at callViewAction (core.js:38736)
    at execComponentViewsAction (core.js:38664)
    at checkAndUpdateView (core.js:38377)
    at callViewAction (core.js:38736)
    at execComponentViewsAction (core.js:38664)

I already tried to install the node-blockly package and to add the import of Blockly to my component's module like so:
import {Blockly} from "node-blockly;
and

@NgModule({
	... ,
	imports: [
		... ,
                Blockly,
	]
})

But it doesn't seem to help.

Any other suggestions?

Pass parameter to CustomBlock

Hello, how are you?

First of all I would like to congratulate you on working with ngx-blockly.
I have a question: I would like to send a parameter to CustomBlock.
For example, a custom block with a dynamic image.
I did a test by passing a parameter to the CustomBlock constructor, the value for the parameter arrives in the constructor, however, when clicking on the block in toolbox the constructor is called again without this parameter.
I marked the changes
How can I do this?
Thanks.

......
export class TestBlock extends CustomBlock {
nameImage: string;
constructor(type: string, block: any, blockMutator: BlockMutator, nameImage: string) {
super(type, block, blockMutator);
this.class = TestBlock;
this.nameImage = nameImage;
}

.......
.appendField(new Blockly.FieldImage(this.nameImage, 50, 50, '*'))

Unknown block types

Behaviour

When I try to open one of the build in categories I get an error, that the block type is unknown e.g.

ERROR TypeError: Unknown block type: math_number
ERROR TypeError: Unknown block type: controls_repeat_ext
ERROR TypeError: Unknown block type: controls_if

Setup

I build the toolbox as follows:

const config: NgxBlocklyConfig = {
	generators: [
		NgxBlocklyGenerator.JAVASCRIPT
	],
	toolbox: "",
	trashcan: true
};

this.customBlocks = [
	// getDefaultBlocks are static methods which return all the blocks for the category
	...FirstCustomCategory.getDefaultBlocks(),
	...SecondCustomCategory.getDefaultBlocks()
];

const workspace = new Blockly.WorkspaceSvg(new Blockly.Options({}));
const toolbox = new NgxBlocklyToolbox(workspace);

toolbox.nodes = [
	new FirstCustomCategory(),
	new SecondCustomCategory(),
	new Separator(),
	LOGIC_CATEGORY,
	LOOP_CATEGORY,
	MATH_CATEGORY,
	TEXT_CATEGORY,
	LISTS_CATEGORY,
	VARIABLES_CATEGORY
];
this.config.toolbox = toolbox.toXML();
<ngx-blockly *ngIf="showEditor"
             [config]="config"
             [customBlocks]="customBlocks"
             (workspaceChange)="onWorkspaceChanged($event)"
             (workspaceCreate)="onWorkspaceCreated($event)"></ngx-blockly>

Hints

It works fine for all custom categories / blocks and also for the VARIABLES_CATEGORY. But within the VARIABLES_CATEGORY have the button Create Variable... and when I click on it the input dialog opens but after entering a variable name, nothing happens, now variable block appears and no error message.

Information

Package Version
Angular 11
Angular Material 11
ngx-blockly version 11.0.2

DropDownField Generator

Hi,
I have a custom block with a drowpdown field and a generator like this

this.block.appendDummyInput().appendField(new Blockly.FieldDropdown(this.populateOptions), "OBJECTS");

However in my populateOptions function I would like to access properties of my custom block using "this"

populateOptions(){
return this.options;
}
However when I execute the code "this" is of type Blockly.Field; I tried to do something like

populateOptions(){
var b:any=this;
var c=b.getSourceBlock();
...
}
but I get a null value on c.
Do you know how to get a reference to the CustomBlock object that contains the dropdown field?
Many thanks in advance
J.

Blockly 7 update ?

Hi,

I'm very interested in blockly 7 support, that brings major updates, but also a lot of breaking changes.
Is there any plan to update to blockly 7 anytime soon ?

I personnaly tried to patch the library, but didn't succeed yet. I can try to initiate something or contribute to the effort if needed.

Thanks !

how to use block in BlockMutator

Thanks for ngx-blockly;
in method mutationToDom, i want to call method getFieldValue like official example.
I have an idea:
ngx-blockly.component.ts:
mutationToDom: function () {
return this.blockInstance.blockMutator.mutationToDom(this);
},
block-mutator.ts:
public abstract mutationToDom(block: any);

have any better idea??

And i send a 'pull request' yesterday to let BlockMutator support decompose and compose, can you help me?

Migrating from ngx-blockly 10.0.16 to 12.0.5

Hi,
I am migrating my code from version 10.0.16 to 12.0.5 and I got several errors.

  1. import { ..., NgxToolboxBuilderService, ... } from 'ngx-blockly'; and I get an error saying that ngx-blockly"' has no exported member 'NgxToolboxBuilderService'

  2. public config: NgxBlocklyConfig = {
    scrollbars: true,
    trashcan: true,
    grid: {
    spacing: 50,
    length: 1,
    colour: "blue",
    snap: true
    },
    plugins: {
    toolbox: NgxBlocklyToolbox
    }
    }
    and I get an error saying that scrollbars does not exist in type 'NgxBlocklyConfig'

  3. new Category('Game Objects', '#FF00FF',[],this.gameobjectcategories) and I get an error a parameter of type Category[] cannot be assigned to a parameter of type string

Any help with these errors would be much appreciated
J.

The component's content overflows the parent div

Hi there,

Here's my template set up:

<div style="height: 600px; width: 600px;">
  <ng-container #blocklyContainer></ng-container>
</div>

And in my component

@ViewChild("blocklyContainer", { read: ViewContainerRef }) blocklyContainer: ViewContainerRef;

let ngxBlockyFactory = this.resolver.resolveComponentFactory(NgxBlocklyComponent);

          this.ngxToolboxBuilder.nodes = [
          LOGIC_CATEGORY,
          LOOP_CATEGORY,
          MATH_CATEGORY,
          TEXT_CATEGORY,
          LISTS_CATEGORY,
          FUNCTIONS_CATEGORY,
          new Separator() 
          //my custom blocks here....
        ];

        this.config.toolbox = this.ngxToolboxBuilder.build();

        let blockly = this.blocklyContainer.createComponent(ngxBlockyFactory);
        blockly.instance["config"] = this.config;
        blockly.instance["customBlocks"] = this.customBlocks;
        blockly.instance["generatorConfig"] = this.generatorConfig;
        blockly.instance["javascriptCode"].subscribe((e) => {
          this.onCode(e);
        });

As you can see, I create the ngx-blocky component dynamically, main reason being that my custom blocks can be different, depending on application context.

The problem is that the resulting workspace overflows the div in which I set the size (600x600).

I can see in the inspector, there's a div being produced that matches the correct size (with id #blockly-wrapper) and also ngx-blockly has the correct dimensions.

But the child of #blockly-wrapper which is #blocky, doesn't, it's much bigger.

I've tried this styling

ngx-blockly {
  position: absolute;
  width: 100%;
  height: 100%;
}

But then all the div's ignore the 600x600 dimensions...

Any way to fix that ?

Thanks

goog is not defined

When I am using
"var htmlInput = goog.dom.createDom(goog.dom.TagName.INPUT, 'blocklyHtmlInput')"
in my project then I am getting error :
goog is not defined

How can I define goog, So I will not get this error?

Publish latest build to NPM

It looks like the latest change to expose theme.ts needs to be pushed to the npm registry. Can you please push so others can consume without building locally?

Initiliazing workspace with blocks

Hi,
I am trying to initialize the workspace with some initial existing blocks. As a test I am trying something like

ngOnInit(): void {
var xml_text="<xml xmlns="https://developers.google.com/blockly/xml\"><block type="controls_repeat_ext" id=";/Qokx+iabLf6gwTJ+mg" x="25" y="25">"
var xml=Blockly.Xml.textToDom(xml_text);
Blockly.Xml.domToWorkspace(xml, Blockly.mainWorkspace);

}
but I get an exception
ERROR TypeError: Cannot read properties of null (reading 'RTL')
at Object.Blockly.Xml.domToWorkspace

Do you know what is the right way to add some initial blocks in the workspace after it is created? (I need this feature to restore the state of a previously saved workspace)
Many Thanks
J.

How to read block parameters

I would like to know how can I read a parameter of block eg. I have a block which require a text, I'd like to read taht text and converted to text for my program

sorry for my bad English

Readonly causes exception and fails when initially set to true

Readonly can't be set to true when the ngx-blockly component is first drawn or the lifecycle hooks get called in a way to make setReadonly() try to to access the secondary workspace before it exists.

The problem is that ngOnChanges() is fist called before the content is initialized, so you can't call setReadonly() in the first run of ngOnChanges(). I suspect this was the issue reported in #62. One solution is to instead set up the initial secondary workspace in ngAfterViewInit() when needed. This seems to work:

diff --git a/projects/ngx-blockly/src/lib/ngx-blockly/ngx-blockly.component.ts b/projects/ngx-blockly/src/lib/ngx-blockly/ngx-blockly.component.ts
index dcee601..a5d9291 100644
--- a/projects/ngx-blockly/src/lib/ngx-blockly/ngx-blockly.component.ts
+++ b/projects/ngx-blockly/src/lib/ngx-blockly/ngx-blockly.component.ts
@@ -130,11 +130,14 @@ export class NgxBlocklyComponent implements OnInit, AfterViewInit, OnChanges, On
         this.workspace = Blockly.inject(this.primaryContainer.nativeElement, this.config);
         this.workspace.addChangeListener(this._onWorkspaceChange.bind(this));
         this.workspaceCreate.emit(this.workspace);
+        if (this.readonly)
+          this.setReadonly(this.readonly);
         this.resize();
     }
 
     ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
-        if (changes.readonly) {
+        //skip this if the change comes before we are initialized
+        if (changes.readonly && this._secondaryWorkspace) {
             this.setReadonly(changes.readonly.currentValue);
         }
     }

Blockly mainWorkspace undefined

Hi,
I am accessing the main workspace by using
declare var Blockly: any;
...
Blockly.mainWorkspace

within the "defineBlock" method of a CustomBlock but I get an error saying this property (mainWorkspace) is undefined.

At the time I am trying to access Blockly.mainworkspace I have an active workspace because
this.block.workspace returns a valid object and I also can see in my browser a workspace in which I can drag and drop blocks

Does any one know what the problem might be?
Thank you very much

Issue translating values and statements

Hi! First of all, thanks for your efforts creating this library. It's really useful.

I've been working with it and defined my own custom blocks and now I'm working on the traslations. Everything was going well with simple blocks that only had fields. However, more complex blocks that have statements and value inputs seem impossible to translate.

I've been reading the official documentation about Blockly and I've found this two methods: statementToCode and valueToCode, but I'm not sure on how tu use them in angular.

Could you help me with that?

Many thanks in advance.

Regards.

Call function when clicking on FieldImage

Hello,

I am trying to call a function when clicking FieldImage in a CustomBlock.
I tried to use the setOnClickHandler method and pass the function, however, the function is called by dragging and dropping the block, not by clicking on the image.
I also tried to pass the function in the FieldImage constructor, with the same result.
Is there another way to do this?

How to upgrade to latest version?

Hi,

I am using ngx-blockly of version 0.0.45 and I want to upgrade it to latest version. I can install the latest version but my concern is that is there anything which will be break after upgrading to latest version because I have used many blocks in current version. Please suggest the best way to upgrade.

Thanks

Error: Cannot read property 'workspaceToCode' of undefined

Steps followed as per Github reference:

My Application:
Controller:
image
image

HTML:
image

Browser VIEW:
image

Issue:
Unable to find the event workspaceToCode

this event will fire for every change done on the blockly and based on result emitted by workspaceToCode function , it sends results to our local function onCode()

but unfortunately, it is not working as expected, I'm not sure where did I do mistake on my code.
Please let me know, what was the issue

image

image

Workspace disappears when status bar appears on window.

I am using blockly-workspace on fullscreen and when the status bar of chrome appears at the bottom and the workspace (where I drag block-codes) gets all white (it disables) . And when the status bar is removed it reappears(enable).

Screenshot 2021-07-05 at 1 48 18 PM

Screenshot 2021-07-05 at 1 33 06 PM

Add custom block with another block

I having some issue on the custom block when connected to another block. For example, the custom block that I created have the function "x set to" is connected with math number block "2" but the javascript code is unable to show the correct format. It only show "var x;" but it should show "x=2;".

How to generate js code for custom blocks?

I am using ngx-blockly for my project and I have created custom blocks, which is working fine but now I want to generate the JavaScript code from the xml which has been created by my custom blocks. Or there is any event for directly getting the js code for custom blocks like we are getting for predefined blocks by (javascriptCode) event. Please help me, I got stuck here.

Is is possible to load custom blocks from JSON definitions ?

Hi there

I'm rewriting an ASP .NET MVC application to an Angular 9/.NET Core backend one and I used to load my custom blocks defined in JSON rather than Javascript.

My custom blocks are coming from the backend as the field_dropdown's options are dynamic.

For example:

{
  "type": "color_choice",
  "message0": "Choose color %1",
  "args0": [
    {
      "type": "field_dropdown",
      "name": "color",
      "options": [
        [
          "red",
          "OPTIONNAME"
        ],
        [
          "green",
          "OPTIONNAME"
        ],
        [
          "blue",
          "OPTIONNAME"
        ]
      ]
    }
  ],
  "output": null,
  "colour": 230,
  "tooltip": "",
  "helpUrl": ""
}

I'm trying to figure out how I could do it like in your CustomBlock example, but I'm struggling to come up with something. It'd be nice if I could just plug in the JSON definition in.

Is this possible ?

Thanks for your work.

[Help want] Variable

I'd like to create a variable before render a blockly workspace.
I look around in Google Blockly document and I found

Blockly.Variables.createVariableButtonHandler(button.getTargetWorkspace(), null, 'panda');

But I'm not sure how to implement it with your lib

Cannot read property 'workspaceToCode' of undefined

Hello,
I have TypeError when using a custom block to generate Lua code

My angular.json scripts are
"scripts": [
"node_modules/ngx-blockly/scripts/blockly/blockly_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/blocks_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/msg/js/en.js",
"node_modules/ngx-blockly/scripts/blockly/lua_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/python_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/javascript_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/php_compressed.js",
"node_modules/ngx-blockly/scripts/blockly/dart_compressed.js"
]
my html contains

<ngx-blockly [config]="config" [customBlocks]="customBlocks" [generatorConfig]="generatorConfig" (javascriptCode)="onCode($event)" (luaCode)="onCode($event)">

and my generatorConfig is

public generatorConfig: NgxBlocklyGeneratorConfig = {
javascript:true,
lua:true
};

In my custom block class the method
toJavaScriptCode(block: CustomBlock): string | any[] is corrrectly called but

the method toLuaCode(block: CustomBlock): string | any[] is never called

Instead a TypeError is generated
stack: "TypeError: Cannot read property 'workspaceToCode' of undefined
at NgxBlocklyComponent.workspaceToCode (http://localhost:4200/vendor.js:53873:43)
at NgxBlocklyComponent.onWorkspaceChange (http://localhost:4200/vendor.js:53992:14)
at Blockly.WorkspaceSvg.Blockly.Workspace.fireChangeListener (http://localhost:4200/scripts.js:357:447)
at Blockly.Events.fireNow (http://localhost:4200/scripts.js:58:220)
at timer (http://localhost:4200/polyfills.js:11942:41)
at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:9787:31)
at Object.onInvokeTask (http://localhost:4200/vendor.js:39541:33)
at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:9786:60)
at Zone.runTask (http://localhost:4200/polyfills.js:9559:47)
at invokeTask (http://localhost:4200/polyfills.js:9868:34)"

Am I missing anything? Thanks for your help

Display blockly workspace for each div it belongs

I have a list of files of type JSON and XML. XML files have blockly data. I am enumerating through each file and identifying if those are blockly or non-blockly and want to display accordingly in their respective div. The problem here is I am not able to have the blockly workspace display correctly under its own div and it stacks up against one below another. how do I map each workspace with its div it should display under.

This is how the view looks and few have tabular data and few need to display blockly workspace.
image
image
image

Here's my HTML

<div>
  <div *ngIf="!isBlocky">
    <ag-grid-angular style="width:100%;"
                        class="ag-theme-material"
                        [gridOptions]="jobViewGridOptions"
                        [rowData]="jobDetailData"></ag-grid-angular>
  </div>
  <div *ngIf="isBlocky" >
    <mat-card>No visual available for a script file.</mat-card> 
    <ngx-blockly [config]="blockConfig" [customBlocks]="customBlocks"></ngx-blockly>
  </div>
</div>

I understand customBlocks array will have all the workspaces but how should I do a for each and display workspace specific to each div and not all at once as one below another as you see in picture 3 ScriptTest has all the workspaces and not just it's own.
I tried a for each on customBlocks but it did not do the work and said cannot read type of undefined.

and my function where I prepare the data to display

public ngOnInit(): void {
        this.initializeJobTable();
        this.customBlocks = [
            new SendCommandBlock(),
            new SendCommandExpectResponseBlock(),
            new RunAfterBlock(),
        ];
        this.ngxToolboxBuilder.nodes = [
            new Category("CommandTron", "#FF00FF", this.customBlocks, undefined),
            LOGIC_CATEGORY,
            LOOP_CATEGORY,
            MATH_CATEGORY,
            TEXT_CATEGORY,
            new Separator(),
            LISTS_CATEGORY,
            // COLOUR_CATEGORY,
            VARIABLES_CATEGORY,
            FUNCTIONS_CATEGORY,
        ];
        this.blockConfig = {
            disable: true,
            sounds: false,
            readOnly: true,
            grid: {
                spacing: 20,
                length: 2,
                colour: "#ccc",
                snap: false,
            },
        };
        this.blockConfig.toolbox = this.ngxToolboxBuilder.build();
        this.jobDataService.get(this.inputJobId)
        .subscribe((data) => {
            this.job = data;
            try {
                if (!this.isBlocky){
                    const commands = (ObjectUtils.deserializeJson(this.job.jobFile) as ICommandResponsePair[]);
                    for (const cmd of commands) {
                        this.jobDetailData.push({
                            command : cmd.command,
                            response : cmd.response,
                        });
                    }
                } else {
                    console.log("hfs" + StringUtils.b64DecodeUnicode(this.job.jobFile));
                    setTimeout(() => {this.blockWorkspace.fromXml(StringUtils.b64DecodeUnicode(this.job.jobFile));}, 0);
                }
            }   catch (e) {
                    this.notificationService.showErrorNoTimeout("Error parsing job file contents.");
            }
        });

    }

Not sure where I am wrong and stuck on this.

custom fields

Hello,
thanks for the great library. I appreciate if you can give me a hint on how I could create/integrate a custom field with/without this library somehow. The examples here use google closure, especially the inheritance doesn't seem to be straight forward without using it. The use-case for us is a typeahead suggestion type of text-input/dropdown, which is sadly not supported out of the box.

I appreciate your help/tips. I would be willing to code/fork/integrate our code into the library once I finished developing it.

Custom blocks example

Hello,
in your custom blocks example you create a testblock

new TestBlock('test', null, null)

but I get an error

Argument of type 'null' is not assignable to parameter of type 'BlockMutator'.ts(2345)

The same occurs with the null parameter in

Category('Test', '#FF00FF',this.customBlocks, null)

Argument of type 'null' is not assignable to parameter of type 'Category[] | undefined'.ts(2345)

Thanks for your help

ERROR in Symbol NgxBlocklyComponent

Steps to reproduce

  • Create a new angular application
  • Follow the readme steps
  • ng serve the application

Result
ERROR in Symbol NgxBlocklyComponent declared in /home/ubuntu/source/block-playground/node_modules/ngx-blockly/lib/ngx-blockly/ngx-blockly.component.d.ts is not exported from ngx-blockly/lib/ngx-blockly.module (import into /home/ubuntu/source/block-playground/src/app/app.component.ts)

Tried with version 10.0.1 and 10.0.2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.