|
| 1 | +declare const Blazor: any; |
| 2 | + |
| 3 | +// This function is called by the framework because RegisterAsCustomElement sets it as the initializer function |
| 4 | +(window as any).registerBlazorCustomElement = function defaultRegisterCustomElement(elementName: string, parameters: JSComponentParameter[]): void { |
| 5 | + customElements.define(elementName, class ConfiguredBlazorCustomElement extends BlazorCustomElement { |
| 6 | + static get observedAttributes() { |
| 7 | + return BlazorCustomElement.getObservedAttributes(parameters); |
| 8 | + } |
| 9 | + |
| 10 | + constructor() { |
| 11 | + super(parameters); |
| 12 | + } |
| 13 | + }); |
| 14 | +} |
| 15 | + |
| 16 | +export class BlazorCustomElement extends HTMLElement { |
| 17 | + private _attributeMappings: { [attributeName: string]: JSComponentParameter }; |
| 18 | + private _parameterValues: { [dotNetName: string]: any } = {}; |
| 19 | + private _addRootComponentPromise: Promise<any>; |
| 20 | + private _hasPendingSetParameters = true; // The constructor will call setParameters, so it starts true |
| 21 | + private _isDisposed = false; |
| 22 | + private _disposalTimeoutHandle: any; |
| 23 | + |
| 24 | + public renderIntoElement = this; |
| 25 | + |
| 26 | + // Subclasses will need to call this if they want to retain the built-in behavior for knowing which |
| 27 | + // attribute names to observe, since they have to return it from a static function |
| 28 | + static getObservedAttributes(parameters: JSComponentParameter[]): string[] { |
| 29 | + return parameters.map(p => dasherize(p.name)); |
| 30 | + } |
| 31 | + |
| 32 | + constructor(parameters: JSComponentParameter[]) { |
| 33 | + super(); |
| 34 | + |
| 35 | + // Keep track of how we'll map the attributes to parameters |
| 36 | + this._attributeMappings = {}; |
| 37 | + parameters.forEach(parameter => { |
| 38 | + const attributeName = dasherize(parameter.name); |
| 39 | + this._attributeMappings[attributeName] = parameter; |
| 40 | + }); |
| 41 | + |
| 42 | + // Defer until end of execution cycle so that (1) we know the heap is unlocked, and (2) the initial parameter |
| 43 | + // values will be populated from the initial attributes before we send them to .NET |
| 44 | + this._addRootComponentPromise = Promise.resolve().then(() => { |
| 45 | + this._hasPendingSetParameters = false; |
| 46 | + return Blazor.rootComponents.add(this.renderIntoElement, this.localName, this._parameterValues); |
| 47 | + }); |
| 48 | + |
| 49 | + // Also allow assignment of parameters via properties. This is the only way to set complex-typed values. |
| 50 | + for (const [attributeName, parameterInfo] of Object.entries(this._attributeMappings)) { |
| 51 | + const dotNetName = parameterInfo.name; |
| 52 | + Object.defineProperty(this, camelCase(dotNetName), { |
| 53 | + get: () => this._parameterValues[dotNetName], |
| 54 | + set: newValue => { |
| 55 | + if (this.hasAttribute(attributeName)) { |
| 56 | + // It's nice to keep the DOM in sync with the properties. This set a string representation |
| 57 | + // of the value, but this will get overwritten with the original typed value before we send it to .NET |
| 58 | + this.setAttribute(attributeName, newValue); |
| 59 | + } |
| 60 | + |
| 61 | + this._parameterValues[dotNetName] = newValue; |
| 62 | + this._supplyUpdatedParameters(); |
| 63 | + } |
| 64 | + }); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + connectedCallback() { |
| 69 | + if (this._isDisposed) { |
| 70 | + throw new Error(`Cannot connect component ${this.localName} to the document after it has been disposed.`); |
| 71 | + } |
| 72 | + |
| 73 | + clearTimeout(this._disposalTimeoutHandle); |
| 74 | + } |
| 75 | + |
| 76 | + disconnectedCallback() { |
| 77 | + this._disposalTimeoutHandle = setTimeout(async () => { |
| 78 | + this._isDisposed = true; |
| 79 | + const rootComponent = await this._addRootComponentPromise; |
| 80 | + rootComponent.dispose(); |
| 81 | + }, 1000); |
| 82 | + } |
| 83 | + |
| 84 | + attributeChangedCallback(name: string, oldValue: string, newValue: string) { |
| 85 | + const parameterInfo = this._attributeMappings[name]; |
| 86 | + if (parameterInfo) { |
| 87 | + this._parameterValues[parameterInfo.name] = BlazorCustomElement.parseAttributeValue(newValue, parameterInfo.type, parameterInfo.name); |
| 88 | + this._supplyUpdatedParameters(); |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + private async _supplyUpdatedParameters() { |
| 93 | + if (!this._hasPendingSetParameters) { |
| 94 | + this._hasPendingSetParameters = true; |
| 95 | + |
| 96 | + // Continuation from here will always be async, so at the earliest it will be at |
| 97 | + // the end of the current JS execution cycle |
| 98 | + const rootComponent = await this._addRootComponentPromise; |
| 99 | + if (!this._isDisposed) { |
| 100 | + const setParametersPromise = rootComponent.setParameters(this._parameterValues); |
| 101 | + this._hasPendingSetParameters = false; // We just snapshotted _parameterValues, so we need to start allowing new calls in case it changes further |
| 102 | + await setParametersPromise; |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + static parseAttributeValue(attributeValue: string, type: JSComponentParameterType, parameterName: string): any { |
| 108 | + switch (type) { |
| 109 | + case 'string': |
| 110 | + return attributeValue; |
| 111 | + case 'boolean': |
| 112 | + switch (attributeValue) { |
| 113 | + case 'true': |
| 114 | + case 'True': |
| 115 | + return true; |
| 116 | + case 'false': |
| 117 | + case 'False': |
| 118 | + return false; |
| 119 | + default: |
| 120 | + throw new Error(`Invalid boolean value '${attributeValue}' for parameter '${parameterName}'`); |
| 121 | + } |
| 122 | + case 'number': |
| 123 | + const number = Number(attributeValue); |
| 124 | + if (Number.isNaN(number)) { |
| 125 | + throw new Error(`Invalid number value '${attributeValue}' for parameter '${parameterName}'`); |
| 126 | + } else { |
| 127 | + return number; |
| 128 | + } |
| 129 | + case 'boolean?': |
| 130 | + return attributeValue ? BlazorCustomElement.parseAttributeValue(attributeValue, 'boolean', parameterName) : null; |
| 131 | + case 'number?': |
| 132 | + return attributeValue ? BlazorCustomElement.parseAttributeValue(attributeValue, 'number', parameterName) : null; |
| 133 | + case 'object': |
| 134 | + throw new Error(`The parameter '${parameterName}' accepts a complex-typed object so it cannot be set using an attribute. Try setting it as a element property instead.`); |
| 135 | + default: |
| 136 | + throw new Error(`Unknown type '${type}' for parameter '${parameterName}'`); |
| 137 | + } |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +function dasherize(value: string): string { |
| 142 | + return camelCase(value).replace(/([A-Z])/g, "-$1").toLowerCase(); |
| 143 | +} |
| 144 | + |
| 145 | +function camelCase(value: string): string { |
| 146 | + return value[0].toLowerCase() + value.substring(1); |
| 147 | +} |
| 148 | + |
| 149 | +interface JSComponentParameter { |
| 150 | + name: string; |
| 151 | + type: JSComponentParameterType; |
| 152 | +} |
| 153 | + |
| 154 | +// JSON-primitive types, plus for those whose .NET equivalent isn't nullable, a '?' to indicate nullability |
| 155 | +// This allows custom element authors to coerce attribute strings into the appropriate type |
| 156 | +type JSComponentParameterType = 'string' | 'boolean' | 'boolean?' | 'number' | 'number?' | 'object'; |
0 commit comments