mirror of
https://github.com/google/blockly.git
synced 2026-01-09 18:10:08 +01:00
* fix: convert files to typescript * fix: add alias for AnyDuringMigration so that tsc will run * chore: format * chore: enable ts for the clang-format workflow (#6233) * chore: Restore @fileoverview comment locations (#6237) * chore: add declareModuleId (#6238) * fix: Revert comment change to app_controller.js (#6241) * fix: Add missing import goog statements (#6240) I've added the import statement immediately before the goog.declareModuleId calls that depend on it. There is an argument to be made that we should put the import statement in their normal place amongst any other imports, and move the declareModuleId statement to below the double blank line below the imports, but as these are so tightly coupled, replace the previous goog.module calls, and will both be deleted at the same time once the transition to TypeScript is fully complete I think it's fine (and certainly much easier) to do it this way. * chore: Fix whitespace (#6243) * fix: Remove spurious blank lines Remove extraneous blank lines introduced by deletion of 'use strict'; pragmas. Also fix the location of the goog.declareModuleId call in core/utils/array.ts. * fix: Add missing double-blank-line before body of modules Our convention is to have two blank lines between the imports (or module ID, if there are no imports) and the beginning of the body of the module. Enforce this. * fix: one addition format error for PR #6243 * fix(build): Skip npm prepare when running in CI (#6244) Have npm prepare do nothing when running in CI. We don't need to do any building, because npm test will build everything needed in the workflows in which it is run, and we don't want to build anything in other workflows because a tsc error would prevent those workflows from completing. * fix: re-add `@package` annotations as `@internal` annotations (#6232) * fix: add ~70% of internal attributes * fix: work on manually adding more @internal annotations * fix: add more manual internal annotations * fix: rename package typos to internal * fix: final manual fixes for internal annotations * chore: format * chore: make unnecessary multiline jsdoc a single line * fix: fix internal tags in serialization exceptions * fix: tsc errors picked up from develop (#6224) * fix: relative path for deprecation utils * fix: checking if properties exist in svg_math * fix: set all timeout PIDs to AnyDuringMigration * fix: make nullability errors explicity in block drag surface * fix: make null check in events_block_change explicit * fix: make getEventWorkspace_ internal so we can access it from CommentCreateDeleteHelper * fix: rename DIV -> containerDiv in tooltip * fix: ignore backwards compat check in category * fix: set block styles to AnyDuringMigration * fix: type typo in KeyboardShortcut * fix: constants name in row measurables * fix: typecast in mutator * fix: populateProcedures type of flattened array * fix: ignore errors related to workspace comment deserialization * chore: format files * fix: renaming imports missing file extensions * fix: remove check for sound.play * fix: temporarily remove bad requireType. All `export type` statements are stripped when tsc is run. This means that when we attempt to require BlockDefinition from the block files, we get an error because it does not exist. We decided to temporarily remove the require, because this will no longer be a problem when we conver the blocks to typescript, and everything gets compiled together. * fix: bad jsdoc in array * fix: silence missing property errors Closure was complaining about inexistant properties, but they actually do exist, they're just not being transpiled by tsc in a way that closure understands. I.E. if things are initialized in a function called by the constructor, rather than in a class field or in the custructor itself, closure would error. It would also error on enums, because they are transpiled to a weird IIFE. * fix: context menu action handler not knowing the type of this. this: TypeX information gets stripped when tsc is run, so closure could not know that this was not global. Fixed this by reorganizing to use the option object directly instead of passing it to onAction to be bound to this. * fix: readd getDeveloperVars checks (should not be part of migration) This was found because ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE was no longer being accessed. * fix: silence closure errors about overriding supertype props We propertly define the overrides in typescript, but these get removed from the compiled output, so closure doesn't know they exist. * fix: silence globalThis errors this: TypeX annotations get stripped from the compiled output, so closure can't know that we're accessing the correct things. However, typescript makes sure that this always has the correct properties, so silencing this should be fine. * fix: bad jsdoc name * chore: attempt compiling with blockly.js * fix: attempt moving the import statement above the namespace line * chore: add todo comments to block def files * chore: remove todo from context menu * chore: add comments abotu disabled errors * chore: move comments back to their correct positions (#6249) * fix: work on fixing comments * chore: finish moving all comments * chore: format * chore: move some other messed up comments * chore: format * fix: Correct enum formatting, use merged `namespace`s for types that are class static members (#6246) * fix: formatting of enum KeyCodes * fix: Use merged namespace for ContextMenuRegistry static types - Create a namespace to be merged with the ContextMenuRegistry class containing the types that were formerly declared as static properties on that class. - Use type aliases to export them individually as well, for compatibility with the changes made by MigranTS (and/or @gonfunko) to how other modules in core/ now import these types. - Update renamings.json5 to reflect the availability of the direct exports for modules that import this module directly (though they are not available to, and will not be used by, code that imports only via blockly.js/blockly.ts.) * fix: Use merged namespace for Input.Align - Create a merged namespace for the Input.Align enum. - Use type/const aliases to export it as Input too. - Update renamings.json5 to reflect the availability of the direct export. * fix: Use merged namespace for Names.NameType - Create a merged namespace for the Names.NameType enum. - Use type/const aliases to export it as NameType too. - Update renamings.json5 to reflect the availability of the direct export. (This ought to have happened in an earlier version as it was already available by both routes.) * chore: Fix minor issues for PR #6246 - Use `Align` instead of `Input.Align` where possible. * fix(build): Suppress irrelevant JSC_UNUSED_LOCAL_ASSIGNMENT errors tsc generates code for merged namespaces that looks like: (function (ClassName) { let EnumName; (function (EnumName) { EnumName[EnumNameAlign["v1"] = 0] = "v1"; // etc. })(EnumName = ClassName.EnumName || (ClassName.EnumName = {})); })(ClassName || (ClassName = {})); and Closure Compiler complains about the fact that the EnumName let binding is initialised but never used. (It exists so that any other code that was in the namespace could see the enum.) Suppress this message, since it is not actionable and lint and/or tsc should tell us if we have actual unused variables in our .ts files. * chore(build): Suppress spurious warnings from closure-make-deps (#6253) A little bit of an ugly hack, but it works: pipe stderr through grep -v to suppress error output starting with "WARNING in". * fix: remaining enums that weren't properly exported (#6251) * fix: remaining enums that weren't properly exported * chore: format * fix: add enum value exports * chore: format * fix: properly export interfaces that were typedefs (#6250) * fix: properly export interfaces that were typedefs * fix: allowCollsion -> allowCollision * fix: convert unconverted enums * fix: enums that were/are instance properties * fix: revert changes to property enums * fix: renamed protected parameter properties (#6252) * fix: bad protected parameter properties * chore:format * fix: gesture constructor * fix: overridden properties that were renamed * refactor: Migrate `blockly.js` to TypeScript (#6261) * chore: Apply changes to blockly.js to blockly.ts * fix: Build using core/blockly.ts instead of .js Compiles and runs in compressed mode correctly! * fix(build): Don't depend on execSync running bash (#6262) For some reason on Github CI servers execSync uses /bin/sh, which is (on Ubuntu) dash rather than bash, and does not understand the pipefail option. So remove the grep pipe on stderr and just discard all error output at all. This is not ideal as errors in test deps will go unreported AND not even cause test failure, but it's not clear that it's worth investing more time to fix this at the moment. * chore: use `import type` where possible (#6279) * chore: automatically change imports to import types * chore: revert changes that actually need to be imports * chore: format * chore: add more import type statements based on importsNotUsedAsValues * chore: fix tsconfig * chore: add link to compiler issue * fix: add type information to blockly options (#6283) * fix: add type information to blockly options * chore: format * chore: remove erroneous comment * fix: bugs revealed by getting the built output working (#6282) * fix: types of compose and decompose in block * fix: workspace naming in toolbox * chore: add jsdoc * chore: restore registry comments to better positions * chore: pr comments' * fix(variables): Revert inadvertent change to allDeveloperVariables (#6290) It appears that a function call got modified incorrectly (probably in an effort to fix a typing issue). This fix trivially reverts the line in question to match the original JS version from develop. This causes the generator tests to pass. * fix: circular dependencies (#6281) * chore: fix circular dependencies w/ static workspace funcs * remove preserved imports that aren't currently necessary (probably) * fix circular dependency with workspaces and block using stub * fix dependency between variables and xml by moving function to utils * add stub for trashcan as well * fix line endings from rebase * fix goog/base order * add trashcan patch * fix: types of compose and decompose in block * fix: workspace naming in toolbox * chore: add jsdoc * chore: restore registry comments to better positions * chore: remove implementations in goog.js * chore: fix types of stubs * chore: remove added AnyDuringMigration casts * chore: remove modifications to xml and variables * chore: format * chore: remove event requirements in workspace comments * chore: fix circular dependency with xml and workspace comments * fixup remove ContextMenu import * chore: fix dependency between mutator and workspace * chore: break circular dependency between names and procedures * chore: get tests to run? * chore: pr comments' * chore: fix stubbing field registry fromJson * chore: fix spying on fire * chore: fix stubbing parts of connection checker * chore: fix stubbing dialog * chore: fix stubbing style * chore: fix spying on duplicate * chore: fix stubbing variables * chore: fix stubbing copy * chore: fix stubbing in workspace * chore: remove unnecessary stubs * chore: fix formatting * chore: fix other formatting * chore: add backwards compatible static properties to workspace * chore: move static type properties * chore: move and comment stubs * chore: add newlines at EOF * chore: improve errors for monkey patched functions * chore: update comment with a pointer to the doc * chore: update comment with a pointer to the doc * chore: format * chore: revert changes to playground used for testing (#6292) * chore: get mocha tests to pass. (#6291) * chore: fix undo and empty code blocks * chore: skip IE test * chore: fix gesture test * chore: fix replace message references test * chore: fix string table interpolation * chore: skip getById tests * chore: fix field tests * chore: fix console errors by making workspace nullable * chore: format * chore: fix definition overwrite warning * chore: update metadata * chore: temporarily modify the the advanced compile test * chore: fix gestures by fixing test instead Co-authored-by: Neil Fraser <fraser@google.com> Co-authored-by: Christopher Allen <cpcallen+git@google.com>
680 lines
21 KiB
TypeScript
680 lines
21 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview A toolbox category used to organize blocks in the toolbox.
|
|
*/
|
|
|
|
/**
|
|
* A toolbox category used to organize blocks in the toolbox.
|
|
* @class
|
|
*/
|
|
import * as goog from '../../closure/goog/goog.js';
|
|
goog.declareModuleId('Blockly.ToolboxCategory');
|
|
|
|
import * as Css from '../css.js';
|
|
import type {ICollapsibleToolboxItem} from '../interfaces/i_collapsible_toolbox_item.js';
|
|
import type {ISelectableToolboxItem} from '../interfaces/i_selectable_toolbox_item.js';
|
|
import type {IToolbox} from '../interfaces/i_toolbox.js';
|
|
import type {IToolboxItem} from '../interfaces/i_toolbox_item.js';
|
|
import * as registry from '../registry.js';
|
|
import * as aria from '../utils/aria.js';
|
|
import * as colourUtils from '../utils/colour.js';
|
|
import * as dom from '../utils/dom.js';
|
|
import * as parsing from '../utils/parsing.js';
|
|
import * as toolbox from '../utils/toolbox.js';
|
|
|
|
import {ToolboxItem} from './toolbox_item.js';
|
|
|
|
|
|
/**
|
|
* Class for a category in a toolbox.
|
|
* @alias Blockly.ToolboxCategory
|
|
*/
|
|
export class ToolboxCategory extends ToolboxItem implements
|
|
ISelectableToolboxItem {
|
|
/** Name used for registering a toolbox category. */
|
|
static registrationName = 'category';
|
|
|
|
/** The number of pixels to move the category over at each nested level. */
|
|
static nestedPadding = 19;
|
|
|
|
/** The width in pixels of the strip of colour next to each category. */
|
|
static borderWidth = 8;
|
|
|
|
/**
|
|
* The default colour of the category. This is used as the background colour
|
|
* of the category when it is selected.
|
|
*/
|
|
static defaultBackgroundColour = '#57e';
|
|
|
|
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
|
|
override toolboxItemDef_!: toolbox.CategoryInfo;
|
|
|
|
/** The name that will be displayed on the category. */
|
|
protected name_ = '';
|
|
|
|
/** The colour of the category. */
|
|
protected colour_ = '';
|
|
|
|
/** The html container for the category. */
|
|
protected htmlDiv_: HTMLDivElement|null = null;
|
|
|
|
/** The html element for the category row. */
|
|
protected rowDiv_: HTMLDivElement|null = null;
|
|
|
|
/** The html element that holds children elements of the category row. */
|
|
protected rowContents_: HTMLDivElement|null = null;
|
|
|
|
/** The html element for the toolbox icon. */
|
|
protected iconDom_: Element|null = null;
|
|
|
|
/** The html element for the toolbox label. */
|
|
protected labelDom_: Element|null = null;
|
|
protected cssConfig_: CssConfig;
|
|
|
|
/** True if the category is meant to be hidden, false otherwise. */
|
|
protected isHidden_ = false;
|
|
|
|
/** True if this category is disabled, false otherwise. */
|
|
protected isDisabled_ = false;
|
|
|
|
/** The flyout items for this category. */
|
|
protected flyoutItems_: string|toolbox.FlyoutItemInfoArray = [];
|
|
|
|
/**
|
|
* @param categoryDef The information needed to create a category in the
|
|
* toolbox.
|
|
* @param parentToolbox The parent toolbox for the category.
|
|
* @param opt_parent The parent category or null if the category does not have
|
|
* a parent.
|
|
*/
|
|
constructor(
|
|
categoryDef: toolbox.CategoryInfo, parentToolbox: IToolbox,
|
|
opt_parent?: ICollapsibleToolboxItem) {
|
|
super(categoryDef, parentToolbox, opt_parent);
|
|
|
|
/** All the css class names that are used to create a category. */
|
|
this.cssConfig_ = this.makeDefaultCssConfig_();
|
|
}
|
|
|
|
/**
|
|
* Initializes the toolbox item.
|
|
* This includes creating the DOM and updating the state of any items based
|
|
* on the info object.
|
|
* Init should be called immediately after the construction of the toolbox
|
|
* item, to ensure that the category contents are properly parsed.
|
|
*/
|
|
override init() {
|
|
this.parseCategoryDef_(this.toolboxItemDef_);
|
|
this.parseContents_(this.toolboxItemDef_);
|
|
this.createDom_();
|
|
if (this.toolboxItemDef_['hidden'] === 'true') {
|
|
this.hide();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Creates an object holding the default classes for a category.
|
|
* @return The configuration object holding all the CSS classes for a
|
|
* category.
|
|
*/
|
|
protected makeDefaultCssConfig_(): CssConfig {
|
|
// AnyDuringMigration because: Type '{ container: string; row: string;
|
|
// rowcontentcontainer: string; icon: string; label: string; contents:
|
|
// string; selected: string; openicon: string; closedicon: string; }' is not
|
|
// assignable to type 'CssConfig'.
|
|
return {
|
|
'container': 'blocklyToolboxCategory',
|
|
'row': 'blocklyTreeRow',
|
|
'rowcontentcontainer': 'blocklyTreeRowContentContainer',
|
|
'icon': 'blocklyTreeIcon',
|
|
'label': 'blocklyTreeLabel',
|
|
'contents': 'blocklyToolboxContents',
|
|
'selected': 'blocklyTreeSelected',
|
|
'openicon': 'blocklyTreeIconOpen',
|
|
'closedicon': 'blocklyTreeIconClosed',
|
|
} as AnyDuringMigration;
|
|
}
|
|
|
|
/**
|
|
* Parses the contents array depending on if the category is a dynamic
|
|
* category, or if its contents are meant to be shown in the flyout.
|
|
* @param categoryDef The information needed to create a category.
|
|
*/
|
|
protected parseContents_(categoryDef: toolbox.CategoryInfo) {
|
|
const contents = (categoryDef as AnyDuringMigration)['contents'];
|
|
|
|
if ((categoryDef as AnyDuringMigration)['custom']) {
|
|
this.flyoutItems_ = (categoryDef as AnyDuringMigration)['custom'];
|
|
} else if (contents) {
|
|
for (let i = 0; i < contents.length; i++) {
|
|
const itemDef = contents[i];
|
|
const flyoutItem = itemDef as toolbox.FlyoutItemInfo;
|
|
// AnyDuringMigration because: Property 'push' does not exist on type
|
|
// 'string | FlyoutItemInfoArray'.
|
|
(this.flyoutItems_ as AnyDuringMigration).push(flyoutItem);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Parses the non-contents parts of the category def.
|
|
* @param categoryDef The information needed to create a category.
|
|
*/
|
|
protected parseCategoryDef_(categoryDef: toolbox.CategoryInfo) {
|
|
this.name_ = parsing.replaceMessageReferences(
|
|
(categoryDef as AnyDuringMigration)['name']);
|
|
this.colour_ = this.getColour_(categoryDef);
|
|
Object.assign(
|
|
this.cssConfig_,
|
|
categoryDef['cssconfig'] ||
|
|
(categoryDef as AnyDuringMigration)['cssConfig']);
|
|
}
|
|
|
|
/**
|
|
* Creates the DOM for the category.
|
|
* @return The parent element for the category.
|
|
*/
|
|
protected createDom_(): HTMLDivElement {
|
|
this.htmlDiv_ = this.createContainer_();
|
|
aria.setRole(this.htmlDiv_, aria.Role.TREEITEM);
|
|
aria.setState((this.htmlDiv_), aria.State.SELECTED, false);
|
|
aria.setState((this.htmlDiv_), aria.State.LEVEL, this.level_);
|
|
|
|
this.rowDiv_ = this.createRowContainer_();
|
|
this.rowDiv_.style.pointerEvents = 'auto';
|
|
this.htmlDiv_.appendChild(this.rowDiv_);
|
|
|
|
this.rowContents_ = this.createRowContentsContainer_();
|
|
this.rowContents_.style.pointerEvents = 'none';
|
|
this.rowDiv_.appendChild(this.rowContents_);
|
|
|
|
this.iconDom_ = this.createIconDom_();
|
|
aria.setRole(this.iconDom_, aria.Role.PRESENTATION);
|
|
this.rowContents_.appendChild(this.iconDom_);
|
|
|
|
this.labelDom_ = this.createLabelDom_(this.name_);
|
|
this.rowContents_.appendChild(this.labelDom_);
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string | number | boolean | string[]'.
|
|
aria.setState(
|
|
this.htmlDiv_ as Element, aria.State.LABELLEDBY,
|
|
this.labelDom_.getAttribute('id') as AnyDuringMigration);
|
|
|
|
this.addColourBorder_(this.colour_);
|
|
|
|
return this.htmlDiv_;
|
|
}
|
|
|
|
/**
|
|
* Creates the container that holds the row and any subcategories.
|
|
* @return The div that holds the icon and the label.
|
|
*/
|
|
protected createContainer_(): HTMLDivElement {
|
|
const container = (document.createElement('div'));
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.addClass(
|
|
container, (this.cssConfig_ as AnyDuringMigration)['container']);
|
|
return container;
|
|
}
|
|
|
|
/**
|
|
* Creates the parent of the contents container. All clicks will happen on
|
|
* this div.
|
|
* @return The div that holds the contents container.
|
|
*/
|
|
protected createRowContainer_(): HTMLDivElement {
|
|
const rowDiv = (document.createElement('div'));
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.addClass(rowDiv, (this.cssConfig_ as AnyDuringMigration)['row']);
|
|
let nestedPadding = ToolboxCategory.nestedPadding * this.getLevel();
|
|
// AnyDuringMigration because: Type 'string' is not assignable to type
|
|
// 'number'.
|
|
nestedPadding = (nestedPadding.toString() + 'px') as AnyDuringMigration;
|
|
// AnyDuringMigration because: Type 'number' is not assignable to type
|
|
// 'string'. AnyDuringMigration because: Type 'number' is not assignable to
|
|
// type 'string'.
|
|
this.workspace_.RTL ?
|
|
rowDiv.style.paddingRight = nestedPadding as AnyDuringMigration :
|
|
rowDiv.style.paddingLeft = nestedPadding as AnyDuringMigration;
|
|
return rowDiv;
|
|
}
|
|
|
|
/**
|
|
* Creates the container for the label and icon.
|
|
* This is necessary so we can set all subcategory pointer events to none.
|
|
* @return The div that holds the icon and the label.
|
|
*/
|
|
protected createRowContentsContainer_(): HTMLDivElement {
|
|
const contentsContainer = (document.createElement('div'));
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.addClass(
|
|
contentsContainer,
|
|
(this.cssConfig_ as AnyDuringMigration)['rowcontentcontainer']);
|
|
return contentsContainer;
|
|
}
|
|
|
|
/**
|
|
* Creates the span that holds the category icon.
|
|
* @return The span that holds the category icon.
|
|
*/
|
|
protected createIconDom_(): Element {
|
|
const toolboxIcon = document.createElement('span');
|
|
if (!this.parentToolbox_.isHorizontal()) {
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is
|
|
// not assignable to parameter of type 'string'.
|
|
dom.addClass(
|
|
toolboxIcon, (this.cssConfig_ as AnyDuringMigration)['icon']);
|
|
}
|
|
|
|
toolboxIcon.style.display = 'inline-block';
|
|
return toolboxIcon;
|
|
}
|
|
|
|
/**
|
|
* Creates the span that holds the category label.
|
|
* This should have an ID for accessibility purposes.
|
|
* @param name The name of the category.
|
|
* @return The span that holds the category label.
|
|
*/
|
|
protected createLabelDom_(name: string): Element {
|
|
const toolboxLabel = document.createElement('span');
|
|
toolboxLabel.setAttribute('id', this.getId() + '.label');
|
|
toolboxLabel.textContent = name;
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.addClass(
|
|
toolboxLabel, (this.cssConfig_ as AnyDuringMigration)['label']);
|
|
return toolboxLabel;
|
|
}
|
|
|
|
/** Updates the colour for this category. */
|
|
refreshTheme() {
|
|
this.colour_ = this.getColour_((this.toolboxItemDef_));
|
|
this.addColourBorder_(this.colour_);
|
|
}
|
|
|
|
/**
|
|
* Add the strip of colour to the toolbox category.
|
|
* @param colour The category colour.
|
|
*/
|
|
protected addColourBorder_(colour: string) {
|
|
if (colour) {
|
|
const border =
|
|
ToolboxCategory.borderWidth + 'px solid ' + (colour || '#ddd');
|
|
if (this.workspace_.RTL) {
|
|
this.rowDiv_!.style.borderRight = border;
|
|
} else {
|
|
this.rowDiv_!.style.borderLeft = border;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Gets either the colour or the style for a category.
|
|
* @param categoryDef The object holding information on the category.
|
|
* @return The hex colour for the category.
|
|
*/
|
|
protected getColour_(categoryDef: toolbox.CategoryInfo): string {
|
|
const styleName =
|
|
categoryDef['categorystyle'] || (categoryDef as any)['categoryStyle'];
|
|
const colour = categoryDef['colour'];
|
|
|
|
if (colour && styleName) {
|
|
console.warn(
|
|
'Toolbox category "' + this.name_ +
|
|
'" must not have both a style and a colour');
|
|
} else if (styleName) {
|
|
return this.getColourfromStyle_(styleName);
|
|
} else {
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is
|
|
// not assignable to parameter of type 'string | number'.
|
|
return this.parseColour_(colour as AnyDuringMigration);
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/**
|
|
* Sets the colour for the category using the style name and returns the new
|
|
* colour as a hex string.
|
|
* @param styleName Name of the style.
|
|
* @return The hex colour for the category.
|
|
*/
|
|
private getColourfromStyle_(styleName: string): string {
|
|
const theme = this.workspace_.getTheme();
|
|
if (styleName && theme) {
|
|
const style = theme.categoryStyles[styleName];
|
|
if (style && style.colour) {
|
|
return this.parseColour_(style.colour);
|
|
} else {
|
|
console.warn(
|
|
'Style "' + styleName + '" must exist and contain a colour value');
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/**
|
|
* Gets the HTML element that is clickable.
|
|
* The parent toolbox element receives clicks. The parent toolbox will add an
|
|
* ID to this element so it can pass the onClick event to the correct
|
|
* toolboxItem.
|
|
* @return The HTML element that receives clicks.
|
|
*/
|
|
override getClickTarget(): Element {
|
|
return this.rowDiv_ as Element;
|
|
}
|
|
|
|
/**
|
|
* Parses the colour on the category.
|
|
* @param colourValue HSV hue value (0 to 360), #RRGGBB string, or a message
|
|
* reference string pointing to one of those two values.
|
|
* @return The hex colour for the category.
|
|
*/
|
|
private parseColour_(colourValue: number|string): string {
|
|
// Decode the colour for any potential message references
|
|
// (eg. `%{BKY_MATH_HUE}`).
|
|
const colour = parsing.replaceMessageReferences(colourValue);
|
|
if (colour == null || colour === '') {
|
|
// No attribute. No colour.
|
|
return '';
|
|
} else {
|
|
const hue = Number(colour);
|
|
if (!isNaN(hue)) {
|
|
return colourUtils.hueToHex(hue);
|
|
} else {
|
|
const hex = colourUtils.parse(colour);
|
|
if (hex) {
|
|
return hex;
|
|
} else {
|
|
console.warn(
|
|
'Toolbox category "' + this.name_ +
|
|
'" has unrecognized colour attribute: ' + colour);
|
|
return '';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Adds appropriate classes to display an open icon.
|
|
* @param iconDiv The div that holds the icon.
|
|
*/
|
|
protected openIcon_(iconDiv: Element|null) {
|
|
if (!iconDiv) {
|
|
return;
|
|
}
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.removeClasses(
|
|
iconDiv, (this.cssConfig_ as AnyDuringMigration)['closedicon']);
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.addClass(iconDiv, (this.cssConfig_ as AnyDuringMigration)['openicon']);
|
|
}
|
|
|
|
/**
|
|
* Adds appropriate classes to display a closed icon.
|
|
* @param iconDiv The div that holds the icon.
|
|
*/
|
|
protected closeIcon_(iconDiv: Element|null) {
|
|
if (!iconDiv) {
|
|
return;
|
|
}
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.removeClasses(
|
|
iconDiv, (this.cssConfig_ as AnyDuringMigration)['openicon']);
|
|
// AnyDuringMigration because: Argument of type 'string | undefined' is not
|
|
// assignable to parameter of type 'string'.
|
|
dom.addClass(
|
|
iconDiv, (this.cssConfig_ as AnyDuringMigration)['closedicon']);
|
|
}
|
|
|
|
/**
|
|
* Sets whether the category is visible or not.
|
|
* For a category to be visible its parent category must also be expanded.
|
|
* @param isVisible True if category should be visible.
|
|
*/
|
|
override setVisible_(isVisible: boolean) {
|
|
this.htmlDiv_!.style.display = isVisible ? 'block' : 'none';
|
|
this.isHidden_ = !isVisible;
|
|
|
|
if (this.parentToolbox_.getSelectedItem() === this) {
|
|
this.parentToolbox_.clearSelection();
|
|
}
|
|
}
|
|
|
|
/** Hide the category. */
|
|
hide() {
|
|
this.setVisible_(false);
|
|
}
|
|
|
|
/**
|
|
* Show the category. Category will only appear if its parent category is also
|
|
* expanded.
|
|
*/
|
|
show() {
|
|
this.setVisible_(true);
|
|
}
|
|
|
|
/**
|
|
* Whether the category is visible.
|
|
* A category is only visible if all of its ancestors are expanded and
|
|
* isHidden_ is false.
|
|
* @return True if the category is visible, false otherwise.
|
|
*/
|
|
isVisible(): boolean {
|
|
return !this.isHidden_ && this.allAncestorsExpanded_();
|
|
}
|
|
|
|
/**
|
|
* Whether all ancestors of a category (parent and parent's parent, etc.) are
|
|
* expanded.
|
|
* @return True only if every ancestor is expanded
|
|
*/
|
|
protected allAncestorsExpanded_(): boolean {
|
|
let category: IToolboxItem = this;
|
|
while (category.getParent()) {
|
|
category = category.getParent()!;
|
|
if (!(category as ICollapsibleToolboxItem).isExpanded()) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
override isSelectable() {
|
|
return this.isVisible() && !this.isDisabled_;
|
|
}
|
|
|
|
/**
|
|
* Handles when the toolbox item is clicked.
|
|
* @param _e Click event to handle.
|
|
*/
|
|
onClick(_e: Event) {}
|
|
// No-op
|
|
|
|
/**
|
|
* Sets the current category as selected.
|
|
* @param isSelected True if this category is selected, false otherwise.
|
|
*/
|
|
setSelected(isSelected: boolean) {
|
|
if (isSelected) {
|
|
const defaultColour =
|
|
this.parseColour_(ToolboxCategory.defaultBackgroundColour);
|
|
this.rowDiv_!.style.backgroundColor = this.colour_ || defaultColour;
|
|
dom.addClass(this.rowDiv_!, this.cssConfig_['selected']!);
|
|
} else {
|
|
this.rowDiv_!.style.backgroundColor = '';
|
|
dom.removeClass(this.rowDiv_!, this.cssConfig_['selected']!);
|
|
}
|
|
aria.setState(this.htmlDiv_ as Element, aria.State.SELECTED, isSelected);
|
|
}
|
|
|
|
/**
|
|
* Sets whether the category is disabled.
|
|
* @param isDisabled True to disable the category, false otherwise.
|
|
*/
|
|
setDisabled(isDisabled: boolean) {
|
|
this.isDisabled_ = isDisabled;
|
|
// AnyDuringMigration because: Argument of type 'boolean' is not assignable
|
|
// to parameter of type 'string'.
|
|
this.getDiv()!.setAttribute('disabled', isDisabled as AnyDuringMigration);
|
|
isDisabled ? this.getDiv()!.setAttribute('disabled', 'true') :
|
|
this.getDiv()!.removeAttribute('disabled');
|
|
}
|
|
|
|
/**
|
|
* Gets the name of the category. Used for emitting events.
|
|
* @return The name of the toolbox item.
|
|
*/
|
|
getName(): string {
|
|
return this.name_;
|
|
}
|
|
|
|
override getParent() {
|
|
return this.parent_;
|
|
}
|
|
|
|
override getDiv() {
|
|
return this.htmlDiv_;
|
|
}
|
|
|
|
/**
|
|
* Gets the contents of the category. These are items that are meant to be
|
|
* displayed in the flyout.
|
|
* @return The definition of items to be displayed in the flyout.
|
|
*/
|
|
getContents(): toolbox.FlyoutItemInfoArray|string {
|
|
return this.flyoutItems_;
|
|
}
|
|
|
|
/**
|
|
* Updates the contents to be displayed in the flyout.
|
|
* If the flyout is open when the contents are updated, refreshSelection on
|
|
* the toolbox must also be called.
|
|
* @param contents The contents to be displayed in the flyout. A string can be
|
|
* supplied to create a dynamic category.
|
|
*/
|
|
updateFlyoutContents(contents: toolbox.FlyoutDefinition|string) {
|
|
this.flyoutItems_ = [];
|
|
|
|
if (typeof contents === 'string') {
|
|
(this.toolboxItemDef_ as AnyDuringMigration)['custom'] = contents;
|
|
} else {
|
|
// Removes old custom field when contents is updated.
|
|
delete (this.toolboxItemDef_ as AnyDuringMigration)['custom'];
|
|
(this.toolboxItemDef_ as AnyDuringMigration)['contents'] =
|
|
toolbox.convertFlyoutDefToJsonArray(contents);
|
|
}
|
|
this.parseContents_((this.toolboxItemDef_));
|
|
}
|
|
|
|
override dispose() {
|
|
dom.removeNode(this.htmlDiv_);
|
|
}
|
|
}
|
|
|
|
export namespace ToolboxCategory {
|
|
/** All the CSS class names that are used to create a category. */
|
|
export interface CssConfig {
|
|
container: string|undefined;
|
|
row: string|undefined;
|
|
rowcontentcontainer: string|undefined;
|
|
icon: string|undefined;
|
|
label: string|undefined;
|
|
selected: string|undefined;
|
|
openicon: string|undefined;
|
|
closedicon: string|undefined;
|
|
}
|
|
}
|
|
|
|
export type CssConfig = ToolboxCategory.CssConfig;
|
|
|
|
/** CSS for Toolbox. See css.js for use. */
|
|
Css.register(`
|
|
.blocklyTreeRow:not(.blocklyTreeSelected):hover {
|
|
background-color: rgba(255, 255, 255, .2);
|
|
}
|
|
|
|
.blocklyToolboxDiv[layout="h"] .blocklyToolboxCategory {
|
|
margin: 1px 5px 1px 0;
|
|
}
|
|
|
|
.blocklyToolboxDiv[dir="RTL"][layout="h"] .blocklyToolboxCategory {
|
|
margin: 1px 0 1px 5px;
|
|
}
|
|
|
|
.blocklyTreeRow {
|
|
height: 22px;
|
|
line-height: 22px;
|
|
margin-bottom: 3px;
|
|
padding-right: 8px;
|
|
white-space: nowrap;
|
|
}
|
|
|
|
.blocklyToolboxDiv[dir="RTL"] .blocklyTreeRow {
|
|
margin-left: 8px;
|
|
padding-right: 0;
|
|
}
|
|
|
|
.blocklyTreeIcon {
|
|
background-image: url(<<<PATH>>>/sprites.png);
|
|
height: 16px;
|
|
vertical-align: middle;
|
|
visibility: hidden;
|
|
width: 16px;
|
|
}
|
|
|
|
.blocklyTreeIconClosed {
|
|
background-position: -32px -1px;
|
|
}
|
|
|
|
.blocklyToolboxDiv[dir="RTL"] .blocklyTreeIconClosed {
|
|
background-position: 0 -1px;
|
|
}
|
|
|
|
.blocklyTreeSelected>.blocklyTreeIconClosed {
|
|
background-position: -32px -17px;
|
|
}
|
|
|
|
.blocklyToolboxDiv[dir="RTL"] .blocklyTreeSelected>.blocklyTreeIconClosed {
|
|
background-position: 0 -17px;
|
|
}
|
|
|
|
.blocklyTreeIconOpen {
|
|
background-position: -16px -1px;
|
|
}
|
|
|
|
.blocklyTreeSelected>.blocklyTreeIconOpen {
|
|
background-position: -16px -17px;
|
|
}
|
|
|
|
.blocklyTreeLabel {
|
|
cursor: default;
|
|
font: 16px sans-serif;
|
|
padding: 0 3px;
|
|
vertical-align: middle;
|
|
}
|
|
|
|
.blocklyToolboxDelete .blocklyTreeLabel {
|
|
cursor: url("<<<PATH>>>/handdelete.cur"), auto;
|
|
}
|
|
|
|
.blocklyTreeSelected .blocklyTreeLabel {
|
|
color: #fff;
|
|
}
|
|
`);
|
|
|
|
registry.register(
|
|
registry.Type.TOOLBOX_ITEM, ToolboxCategory.registrationName,
|
|
ToolboxCategory);
|