Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a sample using a webcomponent #7718

Draft
wants to merge 2 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 38 additions & 18 deletions core/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

/** Has CSS already been injected? */
let injected = false;
let styleSheet: CSSStyleSheet;

/**
* Add some CSS to the blob that will be injected later. Allows optional
Expand All @@ -33,27 +34,46 @@ export function register(cssContent: string) {
* document's responsibility).
* @param pathToMedia Path from page to the Blockly media directory.
*/
export function inject(hasCss: boolean, pathToMedia: string) {
// Only inject the CSS once.
if (injected) {
return;
}
injected = true;
export function inject(hasCss: boolean, pathToMedia: string, container: Element) {
if (!hasCss) {
injected = true;
return;
}
// Strip off any trailing slash (either Unix or Windows).
const mediaPath = pathToMedia.replace(/[\\/]$/, '');
const cssContent = content.replace(/<<<PATH>>>/g, mediaPath);
// Cleanup the collected css content after injecting it to the DOM.
content = '';

// Inject CSS tag at start of head.
const cssNode = document.createElement('style');
cssNode.id = 'blockly-common-style';
const cssTextNode = document.createTextNode(cssContent);
cssNode.appendChild(cssTextNode);
document.head.insertBefore(cssNode, document.head.firstChild);

const root = container?.getRootNode() ?? document;
if (root === document) {
// Only inject the CSS once.
if (injected) {
return;
}
injected = true;

// Strip off any trailing slash (either Unix or Windows).
const mediaPath = pathToMedia.replace(/[\\/]$/, '');
const cssContent = content.replace(/<<<PATH>>>/g, mediaPath);
// Cleanup the collected css content after injecting it to the DOM.
content = '';

// Inject CSS tag at start of head.
const cssNode = document.createElement('style');
cssNode.id = 'blockly-common-style';
const cssTextNode = document.createTextNode(cssContent);
cssNode.appendChild(cssTextNode);

document.head.insertBefore(cssNode, document.head.firstChild);
} else {
if (!styleSheet) {
// Strip off any trailing slash (either Unix or Windows).
const mediaPath = pathToMedia.replace(/[\\/]$/, '');
const cssContent = content.replace(/<<<PATH>>>/g, mediaPath);
// Cleanup the collected css content after injecting it to the DOM.
content = '';

styleSheet = new CSSStyleSheet();
styleSheet.replaceSync(cssContent);
}
(<ShadowRoot> root).adoptedStyleSheets = [...(<ShadowRoot> root).adoptedStyleSheets, styleSheet];
}
}

/**
Expand Down
2 changes: 1 addition & 1 deletion core/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function createDom(container: Element, options: Options): SVGElement {
container.setAttribute('dir', 'LTR');

// Load CSS.
Css.inject(options.hasCss, options.pathToMedia);
Css.inject(options.hasCss, options.pathToMedia, container);

// Build the SVG DOM.
/*
Expand Down
9 changes: 7 additions & 2 deletions core/renderers/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1077,7 +1077,9 @@ export class ConstantProvider {
* @param tagName The name of the style tag to use.
* @param selector The CSS selector to use.
*/
protected injectCSS_(tagName: string, selector: string) {
protected injectCSS_(tagName: string, selector: string, svg: SVGElement) {
const root = svg?.getRootNode() ?? document;

const cssArray = this.getCSS_(selector);
const cssNodeId = 'blockly-renderer-style-' + tagName;
this.cssNode = document.getElementById(cssNodeId) as HTMLStyleElement;
Expand All @@ -1092,7 +1094,10 @@ export class ConstantProvider {
cssNode.id = cssNodeId;
const cssTextNode = document.createTextNode(text);
cssNode.appendChild(cssTextNode);
document.head.insertBefore(cssNode, document.head.firstChild);
if (root === document)
document.head.insertBefore(cssNode, document.head.firstChild);
else
root.insertBefore(cssNode, root.firstChild);
this.cssNode = cssNode;
}

Expand Down
204 changes: 204 additions & 0 deletions tests/webcomponent.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
<!doctype html>
<html>

<head>
<meta charset="utf-8" />
<title>Blockly Playground Webcomponent</title>

<script type="module">
import { COMPRESSED, loadScript } from './scripts/load.mjs';

import * as Blockly from '../build/blockly.loader.mjs';
import '../build/blocks.loader.mjs';
import { dartGenerator } from '../build/dart.loader.mjs';
import { luaGenerator } from '../build/lua.loader.mjs';
import { javascriptGenerator } from '../build/javascript.loader.mjs';
import { phpGenerator } from '../build/php.loader.mjs';
import { pythonGenerator } from '../build/python.loader.mjs';

await loadScript('../build/msg/en.js');
await loadScript('playgrounds/screenshot.js');
await loadScript('../node_modules/@blockly/dev-tools/dist/index.js');

function toParString(strings, values) {
if (strings.length === 1)
return strings.raw[0];
else {
let r = ''
for (let i = 0; i < strings.length; i++) {
r += strings[i] + (values[i] ?? '');
}
return r;
}
}

const html = function (strings, ...values) {
const template = document.createElement('template');
template.innerHTML = toParString(strings, values);
return template;
};

const css = function (strings, ...values) {
const cssStyleSheet = new CSSStyleSheet();
cssStyleSheet.replaceSync(toParString(strings, values));
return cssStyleSheet;
};

let toolbox = {
"kind": "flyoutToolbox",
"contents": [
{
"kind": "block",
"type": "controls_if"
},
{
"kind": "block",
"type": "controls_whileUntil"
},
{
type: 'text',
kind: 'block',
fields: {
TEXT: '',
},
},
]
};

class BlocklyComponent extends HTMLElement {

static template = html`
<div id="blocklyDiv" style="position: absolute; width: 100%; height: 100%;"></div>
`;

static style = css`
:host {
box-sizing: border-box;
position: absolute;
height: 100%;
width: 100%;
}`;

static blocklyStyle1;
static blocklyStyle2;

blocklyDiv;
workspace;
resizeObserver;

constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.adoptedStyleSheets = [BlocklyComponent.style];
this.shadowRoot.appendChild(BlocklyComponent.template.content.cloneNode(true));

this.blocklyDiv = this.shadowRoot.getElementById('blocklyDiv');
this.createBlockly();
}

createBlockly() {
//Blockly.setParentContainer(this.shadowRoot);
this.workspace = Blockly.inject(this.blocklyDiv, {
toolbox: toolbox,
renderer: 'zelos',
trashcan: true,
zoom: {
controls: true,
wheel: false,
startScale: 0.7,
maxScale: 3,
minScale: 0.3,
scaleSpeed: 1.2,
pinch: false
},
move: {
scrollbars: {
horizontal: true,
vertical: true
},
drag: true,
wheel: true
}
});
}

connectedCallback() {
Blockly.svgResize(this.workspace);

if (!this.resizeObserver) {
this.resizeObserver = new ResizeObserver((entries) => {
Blockly.svgResize(this.workspace);
});
this.resizeObserver.observe(this);
}
}

save() {
const state = Blockly.serialization.workspaces.save(this.workspace);
return state;
}

load(data) {
Blockly.serialization.workspaces.load(data, this.workspace);
}
}
customElements.define('blockly-component', BlocklyComponent);
</script>

<style>
html,
body {
height: 100%;
}

body {
background-color: #fff;
font-family: sans-serif;
overflow: hidden;
}

h1 {
font-weight: normal;
font-size: 140%;
}

#blocklyDiv {
float: right;
height: 95%;
width: 70%;
}

#importExport {
font-family: monospace;
}

.ioLabel>.blocklyFlyoutLabelText {
font-style: italic;
}

#blocklyDiv.renderingDebug .blockRenderDebug {
display: block;
}

.playgroundToggleOptions {
list-style: none;
padding: 0;
}

.playgroundToggleOptions li {
margin-top: 1em;
}

.zelos-renderer .blocklyFlyoutButton .blocklyText {
font-size: 1.5rem;
}
</style>
</head>

<body>
<blockly-component style="position:absolute; left: 50px; top: 50px; width: 500px; height: 600px;"></blockly-component>
<blockly-component
style="position:absolute; left: 600px; top: 50px; width: 500px; height: 600px;"></blockly-component>
</body>

</html>