repo_name
string | dataset
string | owner
string | lang
string | func_name
string | code
string | docstring
string | url
string | sha
string |
|---|---|---|---|---|---|---|---|---|
obsidian-beautitab
|
github_2023
|
andrewmcgivery
|
typescript
|
Observable.setValue
|
setValue(value: any) {
this.value = value;
this.subscribers.forEach((callback) => callback({ ...this.value }));
}
|
/**
* Set the value
* @param value
*/
|
https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/src/Utils/Observable.ts#L16-L19
|
8b796a66bd05e1aaab61b09f48b8a346d323dea7
|
obsidian-beautitab
|
github_2023
|
andrewmcgivery
|
typescript
|
Observable.getValue
|
getValue() {
return this.value;
}
|
/**
* Get the current value
*/
|
https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/src/Utils/Observable.ts#L24-L26
|
8b796a66bd05e1aaab61b09f48b8a346d323dea7
|
obsidian-beautitab
|
github_2023
|
andrewmcgivery
|
typescript
|
Observable.onChange
|
onChange(callback: Function) {
this.subscribers.push(callback);
return () => {
this.subscribers = this.subscribers.filter(
(value) => value === callback
);
};
}
|
/**
* Subscribe to changes in the value. Function returns a "unsubscribe" function to clean up as nessessary.
* @param callback
*/
|
https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/src/Utils/Observable.ts#L32-L40
|
8b796a66bd05e1aaab61b09f48b8a346d323dea7
|
obsidian-beautitab
|
github_2023
|
andrewmcgivery
|
typescript
|
capitalizeFirstLetter
|
const capitalizeFirstLetter = (string: string) =>
string.charAt(0).toUpperCase() + string.slice(1);
|
/**
* Capitlizes the firt letter of a string
* @param string
*/
|
https://github.com/andrewmcgivery/obsidian-beautitab/blob/8b796a66bd05e1aaab61b09f48b8a346d323dea7/src/Utils/capitalizeFirstLetter.ts#L5-L6
|
8b796a66bd05e1aaab61b09f48b8a346d323dea7
|
starpls
|
github_2023
|
withered-magic
|
typescript
|
Context.start
|
async start() {
// Establish connection to the language server.
console.log('context: connecting to the language server');
const client = await this.getOrCreateClient();
await client.start();
// Register commands with the VSCode API.
console.log('context: registering commands');
this.registerCommands();
}
|
/**
* Initializes the context and establishes
*/
|
https://github.com/withered-magic/starpls/blob/75ea08c66670a6fd9ba8ee321795bda391d958cd/editors/code/src/context.ts#L34-L43
|
75ea08c66670a6fd9ba8ee321795bda391d958cd
|
ollama-autocoder
|
github_2023
|
10Nates
|
typescript
|
messageHeaderSub
|
function messageHeaderSub(document: vscode.TextDocument) {
const sub = apiMessageHeader
.replace("{LANG}", document.languageId)
.replace("{FILE_NAME}", document.fileName)
.replace("{PROJECT_NAME}", vscode.workspace.name || "Untitled");
return sub;
}
|
// Give model additional information
|
https://github.com/10Nates/ollama-autocoder/blob/84b0e99deddafd024f2b5460a7c063cff726a9af/src/extension.ts#L40-L46
|
84b0e99deddafd024f2b5460a7c063cff726a9af
|
ollama-autocoder
|
github_2023
|
10Nates
|
typescript
|
autocompleteCommand
|
async function autocompleteCommand(textEditor: vscode.TextEditor, cancellationToken?: vscode.CancellationToken) {
const document = textEditor.document;
const position = textEditor.selection.active;
// Get the current prompt
let prompt = document.getText(new vscode.Range(document.lineAt(0).range.start, position));
prompt = prompt.substring(Math.max(0, prompt.length - promptWindowSize), prompt.length);
// Show a progress message
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: "Ollama Autocoder",
cancellable: true,
},
async (progress, progressCancellationToken) => {
try {
progress.report({ message: "Starting model..." });
let axiosCancelPost: () => void;
const axiosCancelToken = new axios.CancelToken((c) => {
const cancelPost = function () {
c("Autocompletion request terminated by user cancel");
};
axiosCancelPost = cancelPost;
if (cancellationToken) cancellationToken.onCancellationRequested(cancelPost);
progressCancellationToken.onCancellationRequested(cancelPost);
vscode.workspace.onDidCloseTextDocument(cancelPost);
});
const completeInput = messageHeaderSub(textEditor.document) + prompt;
// Make a request to the ollama.ai REST API
const response = await axios.post(apiEndpoint, {
model: apiModel, // Change this to the model you want to use
prompt: completeInput,
stream: true,
raw: true,
options: {
num_predict: numPredict,
temperature: apiTemperature,
stop: ["```"],
num_ctx: Math.min(completeInput.length, promptWindowSize) // Assumes absolute worst case of 1 char = 1 token
}
}, {
cancelToken: axiosCancelToken,
responseType: 'stream'
}
);
//tracker
let currentPosition = position;
response.data.on('data', async (d: Uint8Array) => {
progress.report({ message: "Generating..." });
// Check for user input (cancel)
if (currentPosition.line != textEditor.selection.end.line || currentPosition.character != textEditor.selection.end.character) {
axiosCancelPost(); // cancel axios => cancel finished promise => close notification
return;
}
// Get a completion from the response
const completion: string = JSON.parse(d.toString()).response;
// lastToken = completion;
if (completion === "") {
return;
}
//complete edit for token
const edit = new vscode.WorkspaceEdit();
edit.insert(document.uri, currentPosition, completion);
await vscode.workspace.applyEdit(edit);
// Move the cursor to the end of the completion
const completionLines = completion.split("\n");
const newPosition = new vscode.Position(
currentPosition.line + completionLines.length - 1,
(completionLines.length > 1 ? 0 : currentPosition.character) + completionLines[completionLines.length - 1].length
);
const newSelection = new vscode.Selection(
position,
newPosition
);
currentPosition = newPosition;
// completion bar
progress.report({ message: "Generating...", increment: 1 / (numPredict / 100) });
// move cursor
textEditor.selection = newSelection;
});
// Keep cancel window available
const finished = new Promise((resolve) => {
response.data.on('end', () => {
progress.report({ message: "Ollama completion finished." });
resolve(true);
});
axiosCancelToken.promise.finally(() => { // prevent notification from freezing on user input cancel
resolve(false);
});
});
await finished;
} catch (err: any) {
if (err.response && err.response.data) err.response.data.on('data', async (d: Uint8Array) => {
const completion: string = JSON.parse(d.toString()).error;
err.message = completion;
handleError(err);
}).catch(handleError);
else handleError(err);
}
}
);
}
|
// internal function for autocomplete, not directly exposed
|
https://github.com/10Nates/ollama-autocoder/blob/84b0e99deddafd024f2b5460a7c063cff726a9af/src/extension.ts#L65-L182
|
84b0e99deddafd024f2b5460a7c063cff726a9af
|
ollama-autocoder
|
github_2023
|
10Nates
|
typescript
|
provideCompletionItems
|
async function provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, cancellationToken: vscode.CancellationToken) {
// Create a completion item
const item = new vscode.CompletionItem("Autocomplete with Ollama");
// Set the insert text to a placeholder
item.insertText = new vscode.SnippetString('${1:}');
// Wait before initializing Ollama to reduce compute usage
if (responsePreview) await new Promise(resolve => setTimeout(resolve, responsePreviewDelay * 1000));
if (cancellationToken.isCancellationRequested) {
return [item];
}
// Set the label & inset text to a shortened, non-stream response
if (responsePreview) {
try {
let prompt = document.getText(new vscode.Range(document.lineAt(0).range.start, position));
prompt = prompt.substring(Math.max(0, prompt.length - promptWindowSize), prompt.length);
const completeInput = messageHeaderSub(document) + prompt;
const response_preview = await axios.post(apiEndpoint, {
model: apiModel, // Change this to the model you want to use
prompt: completeInput,
stream: false,
raw: true,
options: {
num_predict: responsePreviewMaxTokens, // reduced compute max
temperature: apiTemperature,
stop: ['\n', '```'],
num_ctx: Math.min(completeInput.length, promptWindowSize) // Assumes absolute worst case of 1 char = 1 token
}
}, {
cancelToken: new axios.CancelToken((c) => {
const cancelPost = function () {
c("Autocompletion request terminated by completion cancel");
};
cancellationToken.onCancellationRequested(cancelPost);
})
});
if (response_preview.data.response.trim() != "") { // default if empty
item.label = response_preview.data.response.trimStart(); // tended to add whitespace at the beginning
item.insertText = response_preview.data.response.trimStart();
}
} catch (err: any) {
if (err.response && err.response.data) err.message = err.response.data.error;
handleError(err);
}
}
// Set the documentation to a message
item.documentation = new vscode.MarkdownString('Press `Enter` to get an autocompletion from Ollama');
// Set the command to trigger the completion
if (continueInline || !responsePreview) item.command = {
command: 'ollama-autocoder.autocomplete',
title: 'Autocomplete with Ollama',
arguments: [cancellationToken]
};
// Return the completion item
return [item];
}
|
// Completion item provider callback for activate
|
https://github.com/10Nates/ollama-autocoder/blob/84b0e99deddafd024f2b5460a7c063cff726a9af/src/extension.ts#L185-L246
|
84b0e99deddafd024f2b5460a7c063cff726a9af
|
ollama-autocoder
|
github_2023
|
10Nates
|
typescript
|
activate
|
function activate(context: vscode.ExtensionContext) {
// Register a completion provider for JavaScript files
const completionProvider = vscode.languages.registerCompletionItemProvider("*", {
provideCompletionItems
},
...completionKeys.split("")
);
// Register a command for getting a completion from Ollama through command/keybind
const externalAutocompleteCommand = vscode.commands.registerTextEditorCommand(
"ollama-autocoder.autocomplete",
(textEditor, _, cancellationToken?) => {
// no cancellation token from here, but there is one from completionProvider
autocompleteCommand(textEditor, cancellationToken);
}
);
// Add the commands & completion provider to the context
try {
context.subscriptions.push(completionProvider);
context.subscriptions.push(externalAutocompleteCommand);
} catch (err) {
handleError(err);
}
}
|
// This method is called when extension is activated
|
https://github.com/10Nates/ollama-autocoder/blob/84b0e99deddafd024f2b5460a7c063cff726a9af/src/extension.ts#L249-L274
|
84b0e99deddafd024f2b5460a7c063cff726a9af
|
ollama-autocoder
|
github_2023
|
10Nates
|
typescript
|
deactivate
|
function deactivate() { }
|
// This method is called when extension is deactivated
|
https://github.com/10Nates/ollama-autocoder/blob/84b0e99deddafd024f2b5460a7c063cff726a9af/src/extension.ts#L277-L277
|
84b0e99deddafd024f2b5460a7c063cff726a9af
|
cv
|
github_2023
|
BartoszJarocki
|
typescript
|
getCommandMenuLinks
|
function getCommandMenuLinks() {
const links = [];
if (RESUME_DATA.personalWebsiteUrl) {
links.push({
url: RESUME_DATA.personalWebsiteUrl,
title: "Personal Website",
});
}
return [
...links,
...RESUME_DATA.contact.social.map((socialMediaLink) => ({
url: socialMediaLink.url,
title: socialMediaLink.name,
})),
];
}
|
/**
* Transform social links for command menu
*/
|
https://github.com/BartoszJarocki/cv/blob/4bb244f5ffaca27a246c6ec07e76513858b1aaca/src/app/page.tsx#L39-L56
|
4bb244f5ffaca27a246c6ec07e76513858b1aaca
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
handleError
|
function handleError(_error: unknown) {
switch (_error) {
case ERR_INVALID_AUTH:
console.error('ERR_INVALID_AUTH');
options.clearTokens();
break;
case ERR_CANNOT_CONNECT:
console.error('ERR_CANNOT_CONNECT');
break;
case ERR_CONNECTION_LOST:
console.error('ERR_CONNECTION_LOST');
break;
case ERR_HASS_HOST_REQUIRED:
console.error('ERR_HASS_HOST_REQUIRED');
break;
case ERR_INVALID_HTTPS_TO_HTTP:
console.error('ERR_INVALID_HTTPS_TO_HTTP');
break;
default:
console.error(_error);
}
throw _error;
}
|
// error string instead of code
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Socket.ts#L158-L180
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
random
|
function random(list: HassEntity[] | any[]) {
if (!list || list.length === 0) return undefined;
return list[Math.floor(Math.random() * list.length)];
}
|
/**
* Returns a random entity_id from provided array
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/getRandomEntity.ts#L6-L9
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
handleDeviceTracker
|
function handleDeviceTracker(stateObj: HassEntity) {
const { state, attributes } = stateObj;
if (attributes?.source_type === 'router') {
return state === 'home' ? 'lan-connect' : 'lan-disconnect';
}
if (['bluetooth', 'bluetooth_le'].includes(attributes?.source_type)) {
return state === 'home' ? 'bluetooth-connect' : 'bluetooth';
}
return state === 'not_home' ? 'account-arrow-right' : 'account';
}
|
// https://github.com/home-assistant/frontend/blob/dev/src/common/entity/device_tracker_icon.ts
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/computeIcon.ts#L144-L154
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
handleInputDatetime
|
function handleInputDatetime(stateObj: HassEntity) {
const { attributes } = stateObj;
if (!attributes?.has_date) {
return 'clock';
}
if (!attributes?.has_time) {
return 'calendar';
}
return FIXED_DOMAIN_ICONS['input_datetime'];
}
|
// https://github.com/home-assistant/frontend/blob/dev/src/common/entity/state_icon.ts
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/computeIcon.ts#L157-L167
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
handleAlarmControlPanel
|
function handleAlarmControlPanel(stateObj: HassEntity) {
const { state } = stateObj;
switch (state) {
case 'armed_away':
return 'shield-lock';
case 'armed_custom_bypass':
return 'security';
case 'armed_home':
return 'shield-home';
case 'armed_night':
return 'shield-moon';
case 'armed_vacation':
return 'shield-airplane';
case 'disarmed':
return 'shield-off';
case 'pending':
return 'shield-outline';
case 'triggered':
return 'bell-ring';
default:
return 'shield';
}
}
|
// https://github.com/home-assistant/frontend/blob/dev/src/fake_data/entity_component_icons.ts
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/computeIcon.ts#L185-L208
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
batteryIcon
|
function batteryIcon(state: number | string, attributes: any) {
const BATTERY_ICONS: Record<number, string> = {
10: 'battery-10',
20: 'battery-20',
30: 'battery-30',
40: 'battery-40',
50: 'battery-50',
60: 'battery-60',
70: 'battery-70',
80: 'battery-80',
90: 'battery-90',
100: 'battery'
};
const BATTERY_CHARGING_ICONS: Record<number, string> = {
10: 'battery-charging-10',
20: 'battery-charging-20',
30: 'battery-charging-30',
40: 'battery-charging-40',
50: 'battery-charging-50',
60: 'battery-charging-60',
70: 'battery-charging-70',
80: 'battery-charging-80',
90: 'battery-charging-90',
100: 'battery-charging'
};
const batteryValue = Number(state);
if (isNaN(batteryValue)) {
if (state === 'off') {
return 'battery';
}
if (state === 'on') {
return 'battery-alert';
}
return 'battery-unknown';
}
const batteryRound = Math.round(batteryValue / 10) * 10;
if (attributes?.is_charging && batteryValue >= 10) {
return BATTERY_CHARGING_ICONS[batteryRound];
}
if (attributes?.is_charging) {
return 'battery-charging-outline';
}
if (batteryValue <= 5) {
return 'battery-alert-variant-outline';
}
return BATTERY_ICONS[batteryRound];
}
|
// https://github.com/home-assistant/frontend/blob/dev/src/common/entity/battery_icon.ts
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/computeIcon.ts#L368-L417
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.updateCallback
|
protected updateCallback() {
// this.update();
}
|
/**
* Can be overridden in `KonvaEditor`
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L53-L55
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.isGuide
|
protected isGuide(node: Konva.Node): boolean {
return node?.attrs?.type?.includes('-guide');
}
|
/**
* Helper to check for `Konva.Line` guides
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L60-L62
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.updateStateIcon
|
protected async updateStateIcon(node: Konva.Image, $states: HassEntities | undefined) {
const entity_id = node.getAttr('entity_id');
if (!entity_id) {
node.setAttr('icon', icons['state-icon']);
node.setAttr('state_color', undefined);
this.updateIcon(node);
return;
}
if (!$states) $states = get(states);
const nodeIcon = node.getAttr('icon');
const nodeColor = node.getAttr('color');
const nodeStateColor = node.getAttr('state_color');
const computedIcon = computeIcon(entity_id, $states);
const entityAttrs = $states?.[entity_id]?.attributes;
const computedStateColor = entityAttrs?.hs_color
? `hsl(${entityAttrs?.hs_color}%, 50%)`
: undefined;
node.setAttrs({
icon: computedIcon,
color: nodeColor,
state_color: computedStateColor
});
if (computedIcon && computedIcon !== nodeIcon) {
node.setAttrs({
icon: computedIcon,
color: nodeColor,
state_color: computedStateColor
});
await this.updateIcon(node);
} else if (computedStateColor && computedStateColor !== nodeStateColor) {
node.setAttr('state_color', computedStateColor);
this.updateIconColor(node, computedStateColor);
} else if (!computedStateColor) {
this.updateIconColor(node, nodeColor);
}
}
|
/**
* Handles updating `state-icon`
* - sets default icon if `entity_id` is missing
* - updates `icon` if it doesn't match previous icon
* - updates icon `state_color` if icon matches but not color
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L70-L111
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.updateStateLabel
|
protected updateStateLabel(node: Konva.Text, $states: HassEntities | undefined) {
const unknownState = 'unknown';
const entity_id = node.getAttr('entity_id');
if (!entity_id || entity_id?.trim() === '') {
if (node.text() !== unknownState) {
node.text(unknownState);
}
return;
}
if (!$states) $states = get(states);
const entity = $states?.[entity_id];
const entityState = entity?.state;
if (entityState) {
if (node.text() !== entityState) node.text(entityState);
} else {
if (node.text() !== unknownState) node.text(unknownState);
}
}
|
/**
* Handles updating `state-label`
* - Updates `text` if it doesn't match previous text
* - Sets text to 'unknown' if it can't update
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L118-L139
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.updateImage
|
protected async updateImage(node: Konva.Image, src: string, fitImage: boolean) {
return new Promise<void>((resolve) => {
const image = new Image();
image.onload = () => {
node.image(image);
node.width(image.naturalWidth);
node.height(image.naturalHeight);
if (fitImage) this.fitImage(node);
this.updateCallback();
resolve();
};
image.onerror = () => {
const canvas = document.createElement('canvas');
canvas.width = node.width() || 100;
canvas.height = node.height() || 100;
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.fillStyle = 'gray';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
node.image(canvas);
resolve();
};
node.setAttr('src', src);
image.src = src;
});
}
|
/**
* Update image
* - Sets gray placeholder on error
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L145-L177
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.fitImage
|
protected fitImage(node: Konva.Image) {
const canvasLayer = this.stage.findOne('Layer') as Konva.Layer;
const canvas = canvasLayer.findOne('Rect') as Konva.Rect;
const padding = 15;
const centerX = canvas.x() + canvas.width() / 2;
const centerY = canvas.y() + canvas.height() / 2;
const maxWidth = canvas.width() - padding * 2;
const maxHeight = canvas.height() - padding * 2;
const scale = Math.min(1, maxWidth / node.width(), maxHeight / node.height());
node.setAttrs({
x: centerX - (node.width() * scale) / 2,
y: centerY - (node.height() * scale) / 2,
scaleX: scale,
scaleY: scale
});
node.move({
x: -this.layer.x(),
y: -this.layer.y()
});
}
|
/**
* Fits image to canvas
* - canvas reference is defined in editor
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L183-L207
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.loadImage
|
protected async loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = () => reject(new Error(`Failed to load image: ${src}`));
image.src = src;
});
}
|
/**
* Helper method to load image
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L212-L219
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.updateImageCache
|
protected updateImageCache(id: string, image: HTMLImageElement) {
konvaImageCache.update((cache) => {
if (!cache[this.selId]) cache[this.selId] = {};
cache[this.selId][id] = image;
return cache;
});
}
|
/**
* Handles $konvaImageCache store
*
* Stores images by id so it can be passed
* to KonvaEditor without refetching images
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L227-L233
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.updateIcon
|
protected async updateIcon(node: Konva.Image) {
if (!node.getAttr('icon')) return;
const result = await this.handleSvg(node, undefined);
if (!result) return;
const { width, height, url } = result;
return new Promise<void>((resolve, reject) => {
const image = new Image();
image.onload = () => {
node.image(image);
node.setAttrs({ width, height });
if (node.getAttr('id')) {
this.updateImageCache(node.getAttr('id'), image);
}
this.updateCallback();
resolve();
};
image.onerror = (err) => reject(err);
image.src = url;
});
}
|
/**
* Updates icon
* - Loads new icon from `handleSvg` data
* - Adds it to `$konvaImageCache`
* - Update callback for `KonvaEditor`
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L241-L264
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.updateIconColor
|
protected updateIconColor(node: Konva.Image, color: string) {
const image = node.getAttr('image') as HTMLImageElement;
if (!image) return;
const parts = image.src.split(',');
const decoded = decodeURIComponent(parts[1]);
const parsed = this.parser.parseFromString(decoded, 'image/svg+xml');
const svg = parsed.documentElement;
svg.style.color = color;
const svgString = this.serializer.serializeToString(svg);
image.src = 'data:image/svg+xml,' + encodeURIComponent(svgString);
this.updateCallback();
}
|
/**
* Sets icon color by decoding svg
* uri without fetching icon again
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L270-L285
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.handleSvg
|
protected async handleSvg(
node: Konva.Image | undefined,
icon: string | undefined,
color?: string
): Promise<{
url: string;
width: number;
height: number;
color: string;
} | void> {
icon = icon || node?.getAttr('icon');
if (!icon) {
console.error('no icon specified');
return;
}
let data: IconifyIcon;
try {
if (iconExists(icon)) {
const existingIcon = getIcon(icon);
if (existingIcon) {
data = existingIcon;
} else {
data = await loadIcon(icon);
}
} else {
data = await loadIcon(icon);
}
} catch {
data = await loadIcon('mdi:image-broken');
}
const defaultSize = 64;
const iconWidth = data?.width || defaultSize;
const iconHeight = data?.height || defaultSize;
const iconColor = color || node?.getAttr('state_color') || node?.getAttr('color');
const scalingFactor = defaultSize / Math.max(iconWidth, iconHeight);
const maxWidth = Math.round(iconWidth * scalingFactor);
const maxHeight = Math.round(iconHeight * scalingFactor);
const offsetX = (defaultSize - maxWidth) / 2;
const offsetY = (defaultSize - maxHeight) / 2;
const scale = `${maxWidth / iconWidth}, ${maxHeight / iconHeight}`;
const svg = `
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 ${defaultSize} ${defaultSize}"
width="${defaultSize}"
height="${defaultSize}"
preserveAspectRatio="none"
style="color: ${iconColor};"
>
<g transform="translate(${offsetX}, ${offsetY}) scale(${scale})">
${data?.body || ''}
</g>
</svg>
`;
return {
url: `data:image/svg+xml,${encodeURIComponent(svg)}`,
width: node?.getAttr('width') || defaultSize,
height: node?.getAttr('height') || defaultSize,
color: iconColor
};
}
|
/**
* Loads iconify data and returns an svg encoded uri
* - handles either a `node` or string like 'mdi:dog'
* - fetches new icon using iconify api
* - handles aspect ratio for non-uniform icons like 'fa6-solid:arrow-down-long'
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L293-L360
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.getShapeAttrs
|
protected getShapeAttrs(node: Konva.Node) {
const type = node?.attrs?.type;
let attrs: Record<string, any> = {
id: node.id(),
type: node?.attrs?.type,
name: node.name(),
x: node.x(),
y: node.y(),
width: node.width(),
height: node.height(),
scaleX: node.scaleX(),
scaleY: node.scaleY(),
rotation: node.rotation(),
opacity: node.opacity(),
draggable: node.draggable(),
listening: node.listening(),
visible: node.visible(),
prevDraggable: node?.getAttr('prevDraggable')
};
const onclick = node.getAttr('onclick');
if (onclick) attrs.onclick = JSON.parse(JSON.stringify(onclick));
if (node instanceof Konva.Image) {
if (type === 'image') {
attrs = {
...attrs,
image: node.image(),
src: node.getAttr('src')
};
} else if (type === 'icon') {
attrs = {
...attrs,
image: node.image(),
icon: node.getAttr('icon'),
color: node.getAttr('color')
};
} else if (type === 'state-icon') {
attrs = {
...attrs,
entity_id: node.getAttr('entity_id'),
state_color: node.getAttr('state_color'),
color: node.getAttr('color')
};
}
} else if (node instanceof Konva.Text) {
attrs = {
...attrs,
box: !!node?.getAttr('box'),
fill: node.fill(),
fontFamily: node.fontFamily(),
fontSize: node.fontSize(),
letterSpacing: node.letterSpacing(),
lineHeight: node.lineHeight(),
fontStyle: node.fontStyle(),
align: node.align(),
ellipsis: node.ellipsis()
};
if (!node.getAttr('box')) {
attrs.width = undefined;
attrs.height = undefined;
}
if (type === 'state-label') {
attrs.entity_id = node.getAttr('entity_id');
} else if (type !== 'state-label') {
attrs.text = node.text();
}
} else if (node instanceof Konva.Rect) {
attrs = {
...attrs,
fill: node.fill(),
cornerRadius: node.cornerRadius()
};
} else if (node instanceof Konva.Circle) {
attrs = {
...attrs,
fill: node.fill(),
radius: node.radius()
};
} else if (node instanceof Konva.Line) {
attrs = {
...attrs,
points: node.points(),
stroke: node.stroke(),
strokeWidth: node.strokeWidth(),
hitStrokeWidth: node.hitStrokeWidth(),
strokeScaleEnabled: node.strokeScaleEnabled()
};
}
return attrs;
}
|
/**
* Explicitly get shape attributes, because
* Konva doesn't include default values with `toJSON()` ...
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L366-L460
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.debounce
|
private debounce(func: (event: Event) => void, wait: number) {
let timeout: ReturnType<typeof setTimeout>;
return (event: Event) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(event), wait);
};
}
|
/**
* Debounce method for `handleScaleChange()`
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L465-L471
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.handleScaleChange
|
private handleScaleChange = (event: Event) => {
const visualViewport = event.target as VisualViewport;
const current = visualViewport?.scale;
if (this.visualViewportScale !== current) {
this.stage.getLayers().forEach((layer) => {
if (this.devicePixelRatio && current) {
layer.getCanvas().setPixelRatio(this.devicePixelRatio * current);
}
});
this.stage.batchDraw();
this.visualViewportScale = current;
}
}
|
/**
* Handles canvas pixel ratio on viewport scale (smart zoom)
* by multiplying devicePixelRatio with visualViewport scale
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaBase.destroyBase
|
protected destroyBase() {
if (visualViewport) {
visualViewport.removeEventListener('resize', this.debounceFunction);
}
window.removeEventListener('resize', this.handleZoomChange);
this.stage.destroy();
}
|
/**
* Destroy konva
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaBase.ts#L509-L515
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.update
|
private update() {
konvaStore.set({
children: this.layer.toObject()?.children || [],
selectedShapes: this.selectedShapes.map((shape) => this.getNodeData(shape)),
mode: this.mode,
undoStack: this.undoStack,
redoStack: this.redoStack
});
}
|
/**
* Update $konvaStore to render ui updates
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L85-L93
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.updateCallback
|
protected updateCallback() {
this.update();
}
|
/**
* Runs update if called from `KonvaBase`
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L98-L100
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.handleMount
|
private async handleMount() {
this.layer.find('Text').forEach((node) => {
if (node?.attrs?.type === 'state-label' && node instanceof Konva.Text) {
this.updateStateLabel(node, undefined);
}
});
const images = this.layer.find('Image');
const imageCache = get(konvaImageCache)?.[this.selId] || {};
await Promise.all(
images.map(async (node) => {
if (node instanceof Konva.Image) {
const cachedImage = imageCache[node.id()];
const src = node.getAttr('src');
if (cachedImage instanceof HTMLImageElement) {
node.image(cachedImage);
} else {
await this.updateImage(node, src, false);
const image = node.image();
if (image instanceof HTMLImageElement && node.id()) {
this.updateImageCache(node.id(), image);
}
}
}
})
);
this.record();
this.update();
}
|
/**
* Handles mount
* - handles state-label with no entity_id
* - loads images from $konvaImageCache
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L107-L138
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setupCanvas
|
private setupCanvas() {
this.stage.add(this.canvasLayer);
this.canvasLayer.moveToBottom();
this.canvasLayer.listening(false);
this.canvas.setAttrs({
x: (this.stage.width() - this.canvasWidth) / 2,
y: (this.stage.height() - this.canvasHeight) / 2,
width: this.canvasWidth,
height: this.canvasHeight,
fill: 'rgba(0, 0, 0, 0.2)',
stroke: 'rgba(255, 255, 255, 0.25)',
strokeWidth: 1,
strokeScaleEnabled: false,
cornerRadius: 9.6
});
this.canvasLayer.add(this.canvas);
this.layer.position({
x: this.canvas.x(),
y: this.canvas.y()
});
}
|
/**
* Setup canvas layer
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L143-L165
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setupTransformer
|
private setupTransformer() {
this.stage.add(this.selectionLayer);
this.selectionLayer.add(this.transformer);
this.transformer.setAttrs({
keepRatio: true,
rotationSnapTolerance: 15 / 2
});
this.transformer.on('transformstart transform transformend', (event) => {
const activeAnchor = this.transformer.getActiveAnchor();
const cornerHandles = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
if (activeAnchor && cornerHandles.includes(activeAnchor)) {
this.transformer.shiftBehavior(this.transformer.keepRatio() ? 'inverted' : 'default');
}
this.transformer.setAttr('boundBoxFunc', (oldBox: Box, newBox: Box) => {
const shapes = this.transformer.nodes();
const textBox = shapes.some((shape) => shape instanceof Konva.Text && shape.getAttr('box'));
return textBox && (newBox.width < 0 || newBox.height < 0) ? oldBox : newBox;
});
if (event.type === 'transformend') this.record();
this.update();
});
const nodes = this.layer.find('Text') as Konva.Text[];
nodes.forEach((node) => {
if (node.getAttr('box')) {
this.addTextBoxEventListener(node);
}
});
this.selectionLayer.add(this.selectionRect);
this.selectionRect.setAttrs({
stroke: 'rgba(255, 255, 255, 0.75)',
strokeWidth: 1,
fill: 'rgba(255, 255, 255, 0.025)',
visible: false,
listening: false,
strokeScaleEnabled: false
});
}
|
/**
* Setup selection layer
* - `rotationSnapTolerance` is half of a `rotationSnap`
* - handle dragging corner anchors when shift is pressed
* - limit `boundBox` if text node has custom `box` attribute
* - add any text `box` event listeners
* - add selection rectangle (mouse drag)
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L175-L217
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setupEvents
|
private setupEvents() {
this.stage.on('click tap dragstart', (event) => this.handleClick(event));
this.stage.on('add remove dragmove dragend', (event) => {
const { type, target } = event;
if (type === 'dragmove' && this.panning) {
this.updateGuidePos();
}
// prevent `record` when panning with guides drawn
if (type === 'dragend' && target?.className !== undefined) {
this.record();
}
this.update();
});
this.stage.on('mousedown', (event) => this.handleMousedown(event));
window.addEventListener('mouseup', this.handleMouseup.bind(this));
window.addEventListener('mousemove', this.handleMouseMove.bind(this));
this.layer
.find('Line')
.filter((node) => this.isGuide(node))
.forEach((node) => this.setupGuideEvents(node as Konva.Line));
this.layer.on('dragmove', this.handleShiftDragMove);
this.setupAltDuplicateEvents();
this.setupGuideSnap();
}
|
/**
* Adds event listeners
* - handle click event
* - record history and update on drag event
* - handle mousedown/mouseup event
* - handle mousemove event
* - adds events guides
* - add events for alt-duplicate
* - adds guide snapping events
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L229-L260
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.handleShiftDragMove
|
public updateGuidePos = () => {
const nodes = this.layer.find('Line').filter((node): node is Konva.Line => this.isGuide(node));
if (!nodes?.length) {
this.guides = [];
return;
}
const stagePos = this.stage.position();
const scaleX = this.stage.scaleX();
const scaleY = this.stage.scaleY();
this.guides = nodes.map((node) => {
if (node?.attrs?.type === 'v-guide') {
const lineX = node.points()[0];
node.points([
lineX,
-stagePos.y / scaleY - this.canvas.y(),
lineX,
(this.stage.height() - stagePos.y) / scaleY - this.canvas.y()
]);
} else if (node?.attrs?.type === 'h-guide') {
const lineY = node.points()[1];
node.points([
-stagePos.x / scaleX - this.canvas.x(),
lineY,
(this.stage.width() - stagePos.x) / scaleX - this.canvas.x(),
lineY
]);
}
return node;
});
}
|
/**
* Updates `v-guide | h-guide` position
*
* Guides are drawn to fit stage dimensions, so
* by zooming or panning they need to be updated
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.handleClick
|
private async handleClick(event: Konva.KonvaEventObject<MouseEvent | TouchEvent>) {
const activeElement = document?.activeElement;
if (activeElement instanceof HTMLInputElement || activeElement instanceof HTMLTextAreaElement) {
activeElement.blur();
await tick();
}
if (this.mode === 'pan' || this.spaceKey) return;
if (this.mode === 'zoom') {
const pointerPos = this.stage.getPointerPosition();
if (pointerPos) {
if (!this.altKey) {
this.setZoom('in', pointerPos);
} else if (this.altKey) {
this.setZoom('out', pointerPos);
}
}
return;
}
const target = event.target;
if (target === this.stage) {
this.deselectAll();
this.update();
return;
}
const getParentNode = (node: Konva.Node) => {
const parent = node.getParent();
if (parent !== this.layer && parent instanceof Konva.Group) {
return getParentNode(parent);
}
return node;
};
const node = getParentNode(target);
if (!node) return;
if (node.visible() && node.draggable() && !this.isGuide(node)) {
const { ctrlKey, metaKey } = event.evt;
const cmd = ctrlKey || metaKey;
const selected = this.transformer.nodes().indexOf(node) >= 0;
type Node = Konva.Shape | Konva.Group;
if (event.type === 'dragstart') {
if (!selected) {
if (!cmd) {
this.transformer.nodes([node]);
this.selectedShapes = [node as Node];
} else {
const nodes = this.transformer.nodes().concat([node]);
this.transformer.nodes(nodes);
this.selectedShapes = nodes as Node[];
}
}
} else {
if (!cmd && !selected) {
this.transformer.nodes([node]);
this.selectedShapes = [node as Node];
} else if (cmd && selected) {
const nodes = this.transformer.nodes().slice();
nodes.splice(nodes.indexOf(node), 1);
this.transformer.nodes(nodes);
this.selectedShapes = nodes as Node[];
} else if (cmd && !selected) {
const nodes = this.transformer.nodes().concat([node]);
this.transformer.nodes(nodes);
this.selectedShapes = nodes as Node[];
}
}
}
this.update();
}
|
/**
* Handle click event
* - blurs any active input field so data can be saved
* - handle pan and zoom clicks
* - handle stage click (no nodes)
* - get node parent if group
* - handle mutiselect cmd click
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L310-L386
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.handleMousedown
|
private handleMousedown(event: Konva.KonvaEventObject<MouseEvent | TouchEvent>) {
if (this.mode === 'pan' || this.panning) return;
const draggableNode = (node: Konva.Node): boolean => {
if (node.draggable()) return true;
const parent = node.getParent();
return parent && parent !== this.stage ? draggableNode(parent) : false;
};
const target = event.target;
const startSelection = target === this.stage || !draggableNode(target);
if (startSelection) {
event.evt.preventDefault();
const pos = this.stage.getPointerPosition();
if (pos) {
const x = (pos.x - this.stage.x()) / this.zoomFactor;
const y = (pos.y - this.stage.y()) / this.zoomFactor;
this.x1 = this.x2 = x;
this.y1 = this.y2 = y;
this.selectionStartX = x;
this.selectionStartY = y;
}
this.selectionRect.setAttrs({
width: 0,
height: 0,
visible: false
});
this.selecting = true;
this.dragSelecting = false;
} else {
this.selecting = false;
if (target instanceof Konva.Shape || target instanceof Konva.Group) {
target.setAttr('startPos', { x: target.x(), y: target.y() });
}
}
}
|
/**
* Handle mousedown event
* - handles panning
* - checks if target is `stage` or non-draggable node
* - starts selection rectangle
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L394-L433
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setupAltDuplicateEvents
|
private setupAltDuplicateEvents() {
let nodes: (Konva.Shape | Konva.Group)[] = [];
let clones: (Konva.Shape | Konva.Group)[] = [];
let duplicating = false;
this.stage.on('dragstart', (event) => {
if (!this.altKey || duplicating || event?.target instanceof Konva.Line) return;
duplicating = true;
const children = this.layer.getChildren();
nodes = this.selectedShapes
.filter((node): node is Konva.Shape | Konva.Group => !this.isGuide(node))
.sort((a, b) => children.indexOf(a) - children.indexOf(b));
const nodeOrder = nodes.map((shape) => shape.zIndex());
clones = nodes
.map((node) => {
const clone = node.clone({
id: this.generateUniqueId(node?.attrs?.type)
});
if (clone) {
this.layer.add(clone);
if (node instanceof Konva.Image) {
const image = node.image();
if (image instanceof HTMLImageElement) {
clone.image(image);
if (image instanceof HTMLImageElement && clone.id()) {
this.updateImageCache(clone.id(), image);
}
}
}
}
return clone;
})
.filter((clone): clone is Konva.Shape | Konva.Group => clone !== null);
clones.forEach((clone, index) => {
clone.zIndex(nodeOrder[index]);
});
nodes.forEach((node) => node.moveToTop());
});
this.stage.on('dragend', () => {
if (!duplicating) return;
duplicating = false;
nodes = [];
clones = [];
this.record();
this.update();
});
}
|
/**
* Handles alt-duplicate
* - original nodes are already being dragged, so move them to top
* - keep clones in place, so it looks like the original node is the clone
* - keeps the original layer children node order when cloning
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L587-L644
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setupGuideSnap
|
private setupGuideSnap() {
this.layer.on('dragmove', (event) => {
if (this.isGuide(event.target)) return;
const nodes = this.selectedShapes.filter(
(node): node is Konva.Shape | Konva.Group => !this.isGuide(node)
);
const box = this.getSnapBoundingBox(nodes);
const points = this.getSnapPoints(box);
if (points.length) {
let offsetX = 0;
let offsetY = 0;
points.forEach((point) => {
if (point.orientation === 'v-guide') {
switch (point.snap) {
case 'start':
offsetX = point.pos - box.x;
break;
case 'center':
offsetX = point.pos - (box.x + box.width / 2);
break;
case 'end':
offsetX = point.pos - (box.x + box.width);
break;
}
} else if (point.orientation === 'h-guide') {
switch (point.snap) {
case 'start':
offsetY = point.pos - box.y;
break;
case 'center':
offsetY = point.pos - (box.y + box.height / 2);
break;
case 'end':
offsetY = point.pos - (box.y + box.height);
break;
}
}
});
nodes.forEach((node) => {
const pos = node.position();
node.position({
x: pos.x + offsetX,
y: pos.y + offsetY
});
});
}
});
}
|
/**
* Sets up event listener for snap functionality
* for when dragging shapes in close proximity to guides
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L650-L702
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.getSnapBoundingBox
|
private getSnapBoundingBox(nodes: (Konva.Shape | Konva.Group)[]) {
const boxes = nodes.map((node) => node.getClientRect({ relativeTo: this.layer }));
const x = Math.min(...boxes.map((box) => box.x));
const y = Math.min(...boxes.map((box) => box.y));
const width = Math.max(...boxes.map((box) => box.x + box.width)) - x;
const height = Math.max(...boxes.map((box) => box.y + box.height)) - y;
return {
x,
y,
width,
height
};
}
|
/**
* Calculates bounding box that encloses selected nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L707-L721
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.subscribeStates
|
subscribeStates() {
this.unsubscribe = states.subscribe(($states) => {
if (this.layer && $states) {
const shapes = this.layer.getChildren(
(node) => node.getAttr('entity_id') && node?.attrs?.type?.startsWith('state-')
);
shapes.forEach((node) => {
if (!this.transformer.nodes().includes(node)) {
if (node instanceof Konva.Image) {
this.updateStateIcon(node, $states);
} else if (node instanceof Konva.Text) {
this.updateStateLabel(node, $states);
}
}
});
}
});
}
|
/**
* Subscribes to $states store
* and updates 'state-' nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L727-L744
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.record
|
private record() {
if (this.applyingState) return;
const currentState: KonvaHistory = {
elements: this.layer.children.map((shape) => this.getNodeData(shape)),
selectedShapes: this.selectedShapes.map((shape) => shape.id())
};
const previousState = this.undoStack[this.undoStack.length - 1];
if (!this.stateEqual(previousState, currentState)) {
this.undoStack.push(currentState);
if (this.undoStack.length > this.maxHistory) {
this.undoStack.shift();
}
this.redoStack = [];
}
this.update();
}
|
/**
* Saves history state
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L749-L770
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.undo
|
public undo() {
if (this.undoStack.length > 1) {
const currentState = this.undoStack.pop();
if (currentState) this.redoStack.push(currentState);
const previousState = this.undoStack[this.undoStack.length - 1];
this.applyState(previousState);
if (previousState.selectedShapes.length === 0) {
this.restoreSelection(this.selectedShapes.map((shape) => shape.id()));
}
this.update();
}
}
|
/**
* Handle undo
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L775-L789
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.redo
|
public redo() {
if (this.redoStack.length > 0) {
const previousState = this.redoStack.pop();
if (previousState) {
this.undoStack.push(previousState);
this.applyState(previousState);
if (previousState.selectedShapes.length === 0) {
this.restoreSelection(this.selectedShapes.map((shape) => shape.id()));
}
this.update();
}
}
}
|
/**
* Handle redo
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L794-L809
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.applyState
|
private applyState(state: KonvaHistory) {
this.applyingState = true;
/**
* Handles history state
* - remove, updates or add nodes
*/
const localHandleState = (layer: Konva.Container, nodes: Konva.Node[]) => {
layer.children.slice().forEach((node) => {
const exists = nodes.some((item) => item?.attrs?.id === node.id());
if (!exists) node.destroy();
});
nodes.forEach(async (item, index) => {
if (!item.attrs?.id) return;
let node = layer.findOne(`#${item?.attrs?.id}`) as Konva.Shape | Konva.Group;
if (node) {
localUpdateNode(node, item?.attrs);
} else {
const newNode = await localAddNode(item);
if (newNode) {
node = newNode;
layer.add(node);
} else {
console.error(`failed to create node with id ${item?.attrs?.id}`);
return;
}
}
if (node instanceof Konva.Group && 'children' in item) {
localHandleState(node, item?.children as Konva.Node[]);
}
node.zIndex(index);
});
};
/**
* Update node
*/
const localUpdateNode = async (node: Konva.Shape | Konva.Group, attrs: ShapeConfig) => {
const onclick = attrs?.onclick;
node.setAttr('onclick', onclick ? JSON.parse(JSON.stringify(onclick)) : undefined);
const type = node?.attrs?.type;
if (type === 'state-label') {
node.setAttrs({ ...attrs, text: node.getAttr('text') });
} else if (type === 'state-icon') {
node.setAttrs({
...attrs,
...{
image: node.getAttr('image'),
color: node.getAttr('color'),
icon: node.getAttr('icon')
}
});
} else if (node instanceof Konva.Image && ['image', 'icon'].includes(type)) {
const src = node.getAttr('src');
node.setAttrs(attrs);
if (attrs?.src !== src) {
await this.updateImage(node, attrs?.src, false);
const image = node.image();
if (image instanceof HTMLImageElement && attrs?.id) {
this.updateImageCache(attrs?.id, image);
}
}
} else {
node.setAttrs(attrs);
}
};
/**
* Add node
*/
const localAddNode = async (nodeData: Konva.Node) => {
let node: any;
const attrs = nodeData?.attrs;
const type = attrs?.type;
switch (type) {
case 'state-label':
node = new Konva.Text(attrs);
this.updateStateLabel(node, undefined);
break;
case 'text':
node = new Konva.Text(attrs);
break;
case 'rectangle':
node = new Konva.Rect(attrs);
break;
case 'circle':
node = new Konva.Circle(attrs);
break;
case 'v-guide':
case 'h-guide':
node = new Konva.Line(attrs);
this.setupGuideEvents(node);
break;
case 'group':
node = new Konva.Group(attrs);
if (
nodeData instanceof Konva.Group &&
nodeData.children &&
Array.isArray(nodeData.children)
) {
nodeData.children.forEach((child: Konva.Shape | Konva.Group) => {
const childNode = localAddNode(child);
if (childNode) node.add(childNode);
});
}
break;
case 'image':
case 'icon':
case 'state-icon': {
node = new Konva.Image(attrs);
const imageCache = get(konvaImageCache)?.[this?.selId]?.[attrs?.id];
if (imageCache instanceof HTMLImageElement) {
node.image(imageCache);
} else {
await this.updateImage(node, attrs?.src, false);
const image = node.image();
if (image instanceof HTMLImageElement && attrs?.id) {
this.updateImageCache(attrs?.id, image);
}
}
if (type === 'state-icon') {
this.updateStateIcon(node as Konva.Image, undefined);
} else if (type === 'icon') {
this.updateIcon(node as Konva.Image);
}
break;
}
default:
console.error(type, 'type not found');
node = new Konva.Shape(attrs);
}
return node;
};
localHandleState(this.layer, state.elements);
if (state.selectedShapes.length > 0) {
this.restoreSelection(state.selectedShapes);
}
this.updateGuidePos();
this.applyingState = false;
this.update();
}
|
/**
* Sets state from that point in history
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L814-L969
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
localHandleState
|
const localHandleState = (layer: Konva.Container, nodes: Konva.Node[]) => {
layer.children.slice().forEach((node) => {
const exists = nodes.some((item) => item?.attrs?.id === node.id());
if (!exists) node.destroy();
});
nodes.forEach(async (item, index) => {
if (!item.attrs?.id) return;
let node = layer.findOne(`#${item?.attrs?.id}`) as Konva.Shape | Konva.Group;
if (node) {
localUpdateNode(node, item?.attrs);
} else {
const newNode = await localAddNode(item);
if (newNode) {
node = newNode;
layer.add(node);
} else {
console.error(`failed to create node with id ${item?.attrs?.id}`);
return;
}
}
if (node instanceof Konva.Group && 'children' in item) {
localHandleState(node, item?.children as Konva.Node[]);
}
node.zIndex(index);
});
};
|
/**
* Handles history state
* - remove, updates or add nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L821-L850
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
localUpdateNode
|
const localUpdateNode = async (node: Konva.Shape | Konva.Group, attrs: ShapeConfig) => {
const onclick = attrs?.onclick;
node.setAttr('onclick', onclick ? JSON.parse(JSON.stringify(onclick)) : undefined);
const type = node?.attrs?.type;
if (type === 'state-label') {
node.setAttrs({ ...attrs, text: node.getAttr('text') });
} else if (type === 'state-icon') {
node.setAttrs({
...attrs,
...{
image: node.getAttr('image'),
color: node.getAttr('color'),
icon: node.getAttr('icon')
}
});
} else if (node instanceof Konva.Image && ['image', 'icon'].includes(type)) {
const src = node.getAttr('src');
node.setAttrs(attrs);
if (attrs?.src !== src) {
await this.updateImage(node, attrs?.src, false);
const image = node.image();
if (image instanceof HTMLImageElement && attrs?.id) {
this.updateImageCache(attrs?.id, image);
}
}
} else {
node.setAttrs(attrs);
}
};
|
/**
* Update node
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L855-L886
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
localAddNode
|
const localAddNode = async (nodeData: Konva.Node) => {
let node: any;
const attrs = nodeData?.attrs;
const type = attrs?.type;
switch (type) {
case 'state-label':
node = new Konva.Text(attrs);
this.updateStateLabel(node, undefined);
break;
case 'text':
node = new Konva.Text(attrs);
break;
case 'rectangle':
node = new Konva.Rect(attrs);
break;
case 'circle':
node = new Konva.Circle(attrs);
break;
case 'v-guide':
case 'h-guide':
node = new Konva.Line(attrs);
this.setupGuideEvents(node);
break;
case 'group':
node = new Konva.Group(attrs);
if (
nodeData instanceof Konva.Group &&
nodeData.children &&
Array.isArray(nodeData.children)
) {
nodeData.children.forEach((child: Konva.Shape | Konva.Group) => {
const childNode = localAddNode(child);
if (childNode) node.add(childNode);
});
}
break;
case 'image':
case 'icon':
case 'state-icon': {
node = new Konva.Image(attrs);
const imageCache = get(konvaImageCache)?.[this?.selId]?.[attrs?.id];
if (imageCache instanceof HTMLImageElement) {
node.image(imageCache);
} else {
await this.updateImage(node, attrs?.src, false);
const image = node.image();
if (image instanceof HTMLImageElement && attrs?.id) {
this.updateImageCache(attrs?.id, image);
}
}
if (type === 'state-icon') {
this.updateStateIcon(node as Konva.Image, undefined);
} else if (type === 'icon') {
this.updateIcon(node as Konva.Image);
}
break;
}
default:
console.error(type, 'type not found');
node = new Konva.Shape(attrs);
}
return node;
};
|
/**
* Add node
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L891-L958
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.restoreSelection
|
private restoreSelection(selectedShapes: string[]) {
this.selectedShapes = selectedShapes
.map((id) => this.layer.findOne(`#${id}`))
.filter(
(shape): shape is Konva.Shape | Konva.Group =>
shape instanceof Konva.Shape || shape instanceof Konva.Group
);
this.transformer.nodes(this.selectedShapes);
}
|
/**
* Restores transformer nodes on redo/undo
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L974-L983
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.stateEqual
|
private stateEqual(state1: KonvaHistory, state2: KonvaHistory) {
if (!state1) return false;
if (!this.arraysEqual(state1.selectedShapes, state2.selectedShapes)) return false;
if (state1.elements.length !== state2.elements.length) return false;
return state1.elements.every((node1: Konva.Node, index: number) => {
const node2 = state2.elements[index];
return this.nodeEqual(node1, node2);
});
}
|
/**
* Helper method to check history state equality
* Prevents duplicate entries if mutiple events are fired
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L989-L999
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.duplicateSelected
|
public duplicateSelected() {
if (this.selectedShapes.length === 0) return;
const clones: (Konva.Shape | Konva.Group)[] = [];
const layerChildren = this.layer.getChildren();
const layerOrder = this.selectedShapes.sort(
(a, b) => layerChildren.indexOf(a) - layerChildren.indexOf(b)
);
layerOrder.forEach((node) => {
const clone = node.clone({
id: this.generateUniqueId(node?.attrs?.type)
});
if (clone instanceof Konva.Image && node instanceof Konva.Image) {
const image = node.image();
if (image instanceof HTMLImageElement && clone.id()) {
clone.image(image);
this.updateImageCache(clone.id(), image);
}
}
this.layer.add(clone);
clones.push(clone);
});
if (this.selectedShapes.length === 1) {
clones[0].zIndex(this.selectedShapes[0].zIndex() + 1);
} else {
clones.forEach((clone) => clone.moveToTop());
}
this.selectedShapes = clones;
this.transformer.nodes(clones);
this.record();
this.update();
}
|
/**
* Duplicate selected shape (with Ctrl+J)
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1049-L1087
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.getSnapPoints
|
private getSnapPoints(box: { x: number; y: number; width: number; height: number }) {
const points: { pos: number; diff: number; snap: string; orientation: string }[] = [];
const pos = (start: number, size: number) => [
{ guide: Math.round(start), snap: 'start' },
{ guide: Math.round(start + size / 2), snap: 'center' },
{ guide: Math.round(start + size), snap: 'end' }
];
const nodeEdges = {
vertical: pos(box.x, box.width),
horizontal: pos(box.y, box.height)
};
const offsetX = this.canvas.width() / 2;
const offsetY = this.canvas.height() / 2;
this.guides.forEach((node) => {
if (!node.visible()) return;
const type = node?.attrs?.type;
const vertical = type === 'v-guide';
const edges = vertical ? nodeEdges.vertical : nodeEdges.horizontal;
const position = vertical ? node.x() + offsetX : node.y() + offsetY;
edges.forEach((edge) => {
const diff = Math.abs(position - edge.guide);
if (diff < this.snapOffset / this.stage.scaleX()) {
points.push({
pos: position,
diff: diff,
snap: edge.snap,
orientation: type
});
}
});
});
return points;
}
|
/**
* Determines snapping points for the bounding box relative to guide lines
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1092-L1131
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setupGuideEvents
|
private setupGuideEvents(node: Konva.Line) {
if (!this.isGuide(node)) return;
node.on('mouseover dragstart', (event) => {
if (node.visible() && node.draggable() && !this.selectionRect.isVisible()) {
this.updateCursor(event);
}
});
node.on('dragmove', () => {
if (node.attrs.type === 'v-guide') {
node.y(0);
} else if (node.attrs.type === 'h-guide') {
node.x(0);
}
});
node.on('mouseout dragend', (event) => {
this.updateCursor();
if (event.type === 'dragend') {
this.record();
}
});
}
|
/**
* Setup special guide events for `v-guide | h-guide`
* - handle cursor update
* - limit guide x/y position
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1138-L1161
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.updateCursor
|
public updateCursor(event?: Konva.KonvaEventObject<MouseEvent>) {
const container = this.stage.container();
if (event && this.isGuide(event.target)) {
const type = event.target?.attrs?.type;
container.style.cursor = type === 'v-guide' ? 'col-resize' : 'row-resize';
return;
}
if (this.mode === 'pan' || this.panning) {
container.style.cursor = 'grab';
} else if (this.mode === 'zoom') {
container.style.cursor = this.altKey ? 'zoom-out' : 'zoom-in';
} else {
container.style.cursor = 'default';
}
}
|
/**
* Updates mouse cursor
* - guide
* - pan
* - zoom
* - default
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1170-L1186
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.toggleTextBox
|
public toggleTextBox(id: string) {
const node = this.layer.findOne(`#${id}`);
if (node instanceof Konva.Text) {
if (node.getAttr('box')) {
node.setAttrs({
box: false,
width: undefined,
height: undefined,
scaleX: 1,
scaleY: 1
});
node.off('transform');
this.transformer.setAttr('boundBoxFunc', undefined);
} else if (!node.getAttr('box')) {
node.setAttrs({
box: true,
width: node.width() * node.scaleX(),
height: node.height() * node.scaleY(),
scaleX: 1,
scaleY: 1
});
this.addTextBoxEventListener(node);
}
this.record();
this.update();
}
}
|
/**
* Toggles text box attribute
* - adds/removes event listener
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1192-L1221
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addTextBoxEventListener
|
private addTextBoxEventListener(node: Konva.Text) {
node.off('transform');
node.on('transform', () => {
node.setAttrs({
width: node.width() * node.scaleX(),
height: node.height() * node.scaleY(),
scaleX: 1,
scaleY: 1
});
});
}
|
/**
* Adds shape event listener to set fixed scale on text
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1226-L1237
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.fitCanvas
|
public fitCanvas() {
const padding = 15;
const stageWidth = this.stage.width() - padding * 2;
const stageHeight = this.stage.height() - padding * 2;
const scale = Math.min(stageWidth / this.canvasWidth, stageHeight / this.canvasHeight);
const x = (this.stage.width() - this.canvasWidth * scale) / 2 - this.canvas.x() * scale;
const y = (this.stage.height() - this.canvasHeight * scale) / 2 - this.canvas.y() * scale;
this.currentTween = new Konva.Tween({
node: this.stage,
duration: 0.15,
easing: Konva.Easings.EaseInOut,
scaleX: scale,
scaleY: scale,
x: x,
y: y,
onUpdate: () => {
this.zoomFactor = this.stage.scaleX();
this.updateGuidePos();
},
onFinish: () => {
this.currentTween = undefined;
}
}).play();
}
|
/**
* Fits canvas to stage (double-clicking pan tool)
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1242-L1268
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.moveSelectedShapes
|
public moveSelectedShapes(x: number, y: number) {
if (this.mode !== 'default' || this.selectedShapes.length === 0) return;
this.selectedShapes.forEach((node) => {
if (node.draggable()) {
node.position({
x: node.x() + x,
y: node.y() + y
});
}
});
this.update();
}
|
/**
* Move nodes (arrow keys)
* - don't record
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1274-L1287
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.updateAttr
|
public async updateAttr(id: string, key: string, value: any, oninput = false) {
const node = this.layer.findOne(`#${id}`);
if (!node) return;
const attrs = node.attrs;
const type = attrs?.type;
switch (true) {
case key === 'src' && node instanceof Konva.Image:
await this.updateImage(node, value, true);
break;
case key === 'icon' && node instanceof Konva.Image:
node.setAttr('icon', value);
await this.updateIcon(node);
break;
case type === 'state-icon' && key === 'entity_id' && node instanceof Konva.Image:
if (value.trim() !== '') {
node.setAttr('entity_id', value);
this.updateStateIcon(node, undefined);
} else {
node.setAttrs({
entity_id: '',
icon: icons['state-icon']
});
await this.updateIcon(node);
}
break;
case type === 'state-icon' && key === 'color' && node instanceof Konva.Image:
node.setAttr('color', value);
this.updateStateIcon(node, undefined);
break;
case type === 'state-label' && key === 'entity_id' && node instanceof Konva.Text:
node.setAttr('entity_id', value);
this.updateStateLabel(node, undefined);
break;
case type === 'icon' && key === 'color' && node instanceof Konva.Image:
node.setAttr('color', value);
this.updateIconColor(node, value);
break;
case typeof node.getAttr(key) === 'number': {
const parsedValue = parseFloat(value);
if (!isNaN(parsedValue)) {
if ((key === 'scaleX' || key === 'scaleY') && this.transformer.keepRatio()) {
node.setAttrs({
scaleX: parsedValue,
scaleY: parsedValue
});
} else if (key === 'opacity') {
const opacityRange = Math.max(0, Math.min(100, parsedValue));
node.setAttr(key, opacityRange / 100);
} else {
node.setAttr(key, parsedValue);
}
}
break;
}
default:
node.setAttr(key, value);
break;
}
if (this.transformer && node instanceof Konva.Text) {
this.transformer.forceUpdate();
}
if (!oninput) this.record();
this.update();
}
|
/**
* Helper method for `setAttr`
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1292-L1368
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.toggleVisibility
|
public toggleVisibility(id?: string) {
const nodes = id ? [this.layer.findOne(`#${id}`)] : this.selectedShapes;
nodes.forEach((node) => {
if (node) node.visible(!node.visible());
});
this.transformer.nodes(
this.selectedShapes.filter(
(node) => node.visible() && node.draggable() && !this.isGuide(node)
)
);
this.record();
this.update();
}
|
/**
* Handles node visibility
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1373-L1388
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.toggleDraggable
|
public toggleDraggable(id?: string) {
const nodes = id ? [this.layer.findOne(`#${id}`)] : this.selectedShapes;
const validNodes = nodes.filter(
(shape): shape is Konva.Shape | Konva.Group =>
shape instanceof Konva.Shape || shape instanceof Konva.Group
);
if (validNodes.length) {
const state = !validNodes[0].draggable();
validNodes.forEach((node) => {
node.draggable(state);
node.listening(state);
});
this.transformer.nodes(state ? validNodes.filter((shape) => shape.visible()) : []);
this.record();
this.update();
}
}
|
/**
* Toggles node lock
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1393-L1414
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.toggleKeepRatio
|
public toggleKeepRatio() {
if (this.transformer) {
this.transformer.keepRatio(!this.transformer.keepRatio());
this.update();
}
}
|
/**
* Toggles shape scale ratio lock
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1419-L1425
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.handleElementClick
|
public handleElementClick(event: MouseEvent, id: string) {
const { shiftKey, ctrlKey, metaKey } = event;
if (shiftKey && this.selectedShapes.length > 0) {
const start = this.layer.findOne(`#${this.selectedShapes[0].id()}`) as Konva.Shape;
const end = this.layer.findOne(`#${id}`) as Konva.Shape;
if (!start && !end) return;
const nodes = this.layer.getChildren().map((node) => node as Konva.Shape);
const startIndex = nodes.indexOf(start);
const endIndex = nodes.indexOf(end);
this.selectedShapes = nodes.slice(
Math.min(startIndex, endIndex),
Math.max(startIndex, endIndex) + 1
);
} else if (ctrlKey || metaKey) {
const node = this.layer.findOne(`#${id}`) as Konva.Shape;
if (!node) return;
const index = this.selectedShapes.indexOf(node);
if (index > -1) {
this.selectedShapes.splice(index, 1);
} else {
this.selectedShapes.push(node);
}
} else {
this.selectShapesById([id]);
}
this.transformer.nodes(
this.selectedShapes.filter(
(node) => node.visible() && node.draggable() && !this.isGuide(node)
)
);
this.update();
}
|
/**
* Handle node select in elements panel (outside of canvas)
* - handles range select (shift)
* - handles multi select (cmd)
* - handles default click
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1433-L1470
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.selectShapesById
|
public selectShapesById(ids: string[]) {
this.selectedShapes = ids
.map((id) => this.layer.findOne(`#${id}`))
.filter((node) => node instanceof Konva.Shape || node instanceof Konva.Group);
this.transformer.nodes(
this.selectedShapes.filter(
(node) => node.visible() && node.draggable() && !this.isGuide(node)
)
);
this.update();
}
|
/**
* Selects nodes by ids
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1475-L1487
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.selectAll
|
public selectAll() {
this.selectedShapes = this.layer.getChildren(
(node) => node instanceof Konva.Shape || node instanceof Konva.Group
);
this.transformer.nodes(
this.selectedShapes.filter(
(node) => node.visible() && node.draggable() && !this.isGuide(node)
)
);
this.update();
}
|
/**
* Selects all nodes (Ctrl+A)
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1492-L1504
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.deselectAll
|
public deselectAll() {
this.selectedShapes = [];
this.transformer.nodes([]);
}
|
/**
* Deselects all nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1509-L1512
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.deleteSelected
|
public deleteSelected() {
this.selectedShapes.forEach((node) => {
node.destroy();
});
this.deselectAll();
this.record();
this.update();
}
|
/**
* Delete selected nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1517-L1525
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.reorderElements
|
public async reorderElements(shapes: string[]) {
shapes.forEach((id, index) => {
const node = this.layer.findOne(`#${id}`);
if (node) node.zIndex(this.layer.children.length - 1 - index);
});
await tick();
this.record();
this.update();
}
|
/**
* Reorders nodes with drag and drop
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1530-L1540
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.updateRotationSnaps
|
public updateRotationSnaps() {
const snapPoints = [
0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285,
300, 315, 330, 345
];
this.transformer.rotationSnaps(this.shiftPressed ? snapPoints : []);
}
|
/**
* Handles rotation snapping
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1545-L1552
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.handleGroup
|
public handleGroup() {
if (this.selectedShapes.length > 1) {
this.group();
} else if (this.selectedShapes.length === 1 && this.selectedShapes[0] instanceof Konva.Group) {
this.ungroup();
}
}
|
/**
* Handles group and ungrouping
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1557-L1563
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.group
|
private group() {
const nodes = this.selectedShapes
.filter((node) => !this.isGuide(node))
.sort((a, b) => {
return this.layer.children.indexOf(a) - this.layer.children.indexOf(b);
});
if (nodes.length < 2) return;
const group = new Konva.Group({
id: this.generateUniqueId('group'),
type: 'group',
name: 'Group',
draggable: true
});
let index = Infinity;
nodes.forEach((node) => {
index = Math.min(index, this.layer.children.indexOf(node));
node.setAttr('prevDraggable', node.draggable());
node.draggable(false);
node.remove();
group.add(node);
});
this.layer.add(group);
group.zIndex(index);
this.selectedShapes = [group];
this.transformer.nodes([group]);
this.record();
this.update();
}
|
/**
* Groups nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1568-L1602
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.ungroup
|
private ungroup() {
if (this.selectedShapes.length !== 1 && !(this.selectedShapes[0] instanceof Konva.Group))
return;
const selectedShapes: (Konva.Shape | Konva.Group)[] = [];
const group = this.selectedShapes[0] as Konva.Group;
const groupIndex = this.layer.children.indexOf(group);
group
.getChildren()
.map((node) => node as Konva.Shape | Konva.Group)
.forEach((node, index) => {
node.setAttrs({
id: this.generateUniqueId(node?.attrs?.type),
draggable: !!node.getAttr('prevDraggable'),
prevDraggable: undefined
});
this.layer.add(node);
node.zIndex(groupIndex + index);
selectedShapes.push(node);
});
group.destroy();
this.selectedShapes = selectedShapes;
this.transformer.nodes(selectedShapes);
this.record();
this.update();
}
|
/**
* Ungroups nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1607-L1639
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setMode
|
public setMode(mode: KonvaMode) {
this.mode = mode;
if (mode === 'pan') {
this.startPan();
} else {
this.stopPan();
}
this.update();
}
|
/**
* Set tool mode
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1644-L1654
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.startPan
|
public startPan() {
this.panning = true;
this.stage.draggable(true);
this.layer.setAttr('listening', false);
this.selectionLayer.setAttr('listening', false);
this.updateCursor();
}
|
/**
* Starts pan mode (space)
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1659-L1667
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.stopPan
|
public stopPan() {
this.panning = false;
this.stage.draggable(false);
this.layer.setAttr('listening', this.mode === 'default');
this.selectionLayer.setAttr('listening', this.mode === 'default');
this.updateCursor();
}
|
/**
* Stops pan mode (space release)
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1672-L1680
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.setZoom
|
public setZoom(type: 'in' | 'out' | 'reset', point: { x: number; y: number }) {
if (this.currentTween) {
this.currentTween.finish();
this.currentTween = undefined;
}
let scale;
if (type === 'reset') {
scale = 1;
} else {
const duration = 0.4;
const zoomFactor = this.zoomFactor * Math.exp(duration * (type === 'in' ? 1 : -1));
scale = Math.exp(
Math.min(Math.max(Math.log(zoomFactor), Math.log(this.minZoom)), Math.log(this.maxZoom))
);
}
this.currentTween = new Konva.Tween({
node: this.stage,
duration: 0.15,
easing: Konva.Easings.StrongEaseOut,
x: point.x - (point.x - this.stage.x()) * (scale / this.zoomFactor),
y: point.y - (point.y - this.stage.y()) * (scale / this.zoomFactor),
scaleX: scale,
scaleY: scale,
onUpdate: () => {
this.zoomFactor = this.stage.scaleX();
this.updateGuidePos();
},
onFinish: () => {
this.currentTween = undefined;
}
}).play();
}
|
/**
* Handle zoom
* - logarithmic scale otherwise it takes forever to zoom with extreme values
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1686-L1720
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.zoomToArea
|
private zoomToArea(box: { x: number; y: number; width: number; height: number }) {
if (this.altKey) return;
box = {
x: (box.x - this.stage.x()) / this.zoomFactor,
y: (box.y - this.stage.y()) / this.zoomFactor,
width: box.width / this.zoomFactor,
height: box.height / this.zoomFactor
};
const centerX = box.x + box.width / 2;
const centerY = box.y + box.height / 2;
const scaleX = this.stage.width() / box.width;
const scaleY = this.stage.height() / box.height;
const scale = Math.min(Math.max(Math.min(scaleX, scaleY), this.minZoom), this.maxZoom);
this.currentTween = new Konva.Tween({
node: this.stage,
duration: 0.25,
easing: Konva.Easings.StrongEaseOut,
x: this.stage.width() / 2 - centerX * scale,
y: this.stage.height() / 2 - centerY * scale,
scaleX: scale,
scaleY: scale,
onUpdate: () => {
this.zoomFactor = this.stage.scaleX();
this.updateGuidePos();
},
onFinish: () => {
this.currentTween = undefined;
}
}).play();
}
|
/**
* Zooms to area within selection rectangle
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1725-L1758
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addStateLabel
|
public addStateLabel() {
const node = new Konva.Text({
type: 'state-label',
name: 'State Label',
entity_id: '',
fontSize: 60,
fill: '#ffffff',
fontStyle: 'normal',
fontFamily: 'Inter Variable',
draggable: true
});
this.updateStateLabel(node, undefined);
this.handleAddNode(node);
}
|
/**
* Add state-label
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1763-L1778
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addStateIcon
|
public async addStateIcon() {
try {
const icon = icons['state-icon'];
const color = '#d5d5d5';
const result = await this.handleSvg(undefined, icon, color);
if (!result) return;
const { width, height, url } = result;
const image = await this.loadImage(url);
const node = new Konva.Image({
type: 'state-icon',
name: 'State Icon',
entity_id: '',
icon,
color,
image,
width,
height,
draggable: true
});
this.handleAddNode(node);
} catch (err) {
console.error('error adding state-icon:', err);
}
}
|
/**
* Adds state-icon
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1783-L1812
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addText
|
public addText() {
const node = new Konva.Text({
type: 'text',
name: 'Text',
text: 'Text',
fontSize: 60,
fill: '#ffffff',
fontFamily: 'Inter Variable',
draggable: true,
align: 'left'
});
this.handleAddNode(node);
}
|
/**
* Add text
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1817-L1830
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addIcon
|
public async addIcon() {
try {
const icon = icons['icon'];
const color = '#d5d5d5';
const result = await this.handleSvg(undefined, icon, color);
if (!result) return;
const { width, height, url } = result;
const image = await this.loadImage(url);
const node = new Konva.Image({
type: 'icon',
name: 'Icon',
icon: icon,
color: color,
image: image,
width: width,
height: height,
draggable: true
});
this.handleAddNode(node);
} catch (err) {
console.error('error adding icon:', err);
}
}
|
/**
* Add icon
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1835-L1863
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addImage
|
public async addImage() {
const src = 'https://demo.home-assistant.io/stub_config/t-shirt-promo.png';
try {
const image = await this.loadImage(src);
const node = new Konva.Image({
type: 'image',
name: 'Image',
image: image,
src: src,
width: image.naturalWidth || 64,
height: image.naturalHeight || 64,
draggable: true
});
this.handleAddNode(node);
} catch (err) {
console.error('error adding image:', err);
// add empty fallback
const node = new Konva.Image({
type: 'image',
name: 'Image',
image: undefined,
src: src,
width: 100,
height: 100,
draggable: true
});
this.handleAddNode(node);
// gray box onerror
await this.updateImage(node, src, false);
}
}
|
/**
* Add image
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1868-L1904
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addRectangle
|
public addRectangle() {
const node = new Konva.Rect({
type: 'rectangle',
name: 'Rectangle',
width: 150,
height: 80,
fill: '#ffffff',
draggable: true
});
this.handleAddNode(node);
}
|
/**
* Add rectangle
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1909-L1920
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addCircle
|
public addCircle() {
const node = new Konva.Circle({
type: 'circle',
name: 'Circle',
radius: 50,
fill: '#ffffff',
draggable: true
});
this.handleAddNode(node);
}
|
/**
* Add circle
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1925-L1935
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addVerticalGuide
|
public addVerticalGuide() {
const stageHeight = this.stage.height();
const centerX = this.canvasWidth / 2;
const topY = -(stageHeight - this.canvasHeight) / 2;
const bottomY = stageHeight / 2 + this.canvasHeight / 2;
const node = new Konva.Line({
type: 'v-guide',
points: [centerX, topY, centerX, bottomY],
stroke: '#75fcfd',
name: 'Vertical Guide',
strokeWidth: 1,
hitStrokeWidth: 8,
draggable: true,
strokeScaleEnabled: false
});
this.handleAddNode(node);
}
|
/**
* Add v-guide
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1940-L1958
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.addHorizontalGuide
|
public addHorizontalGuide() {
const stageWidth = this.stage.width();
const centerY = this.canvasHeight / 2;
const leftX = -(stageWidth - this.canvasWidth) / 2;
const rightX = stageWidth / 2 + this.canvasWidth / 2;
const node = new Konva.Line({
type: 'h-guide',
points: [leftX, centerY, rightX, centerY],
stroke: '#75fcfd',
name: 'Horizontal Guide',
strokeWidth: 1,
hitStrokeWidth: 8,
draggable: true,
strokeScaleEnabled: false
});
this.handleAddNode(node);
}
|
/**
* Add h-guide
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1963-L1981
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.handleAddNode
|
private handleAddNode(node: Konva.Shape) {
const type = node?.attrs?.type;
node.setAttrs({
id: this.generateUniqueId(type)
});
if (node instanceof Konva.Circle)
node.position({
x: this.canvasWidth / 2,
y: this.canvasHeight / 2
});
else if (!this.isGuide(node)) {
node.position({
x: (this.canvasWidth - node.width()) / 2,
y: (this.canvasHeight - node.height()) / 2
});
}
if (type === 'image' && node instanceof Konva.Image) {
this.fitImage(node);
}
this.layer.add(node);
if (this.isGuide(node) && node instanceof Konva.Line) {
this.setupGuideEvents(node);
this.updateGuidePos();
} else {
this.selectedShapes = [node];
this.transformer.nodes([node]);
}
this.record();
this.update();
}
|
/**
* Handle add node
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L1986-L2021
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.getElementsData
|
public getElementsData() {
return this.layer.getChildren().map((node) => this.getNodeData(node));
}
|
/**
* onDestroy helper to record data
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L2026-L2028
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.getNodeData
|
private getNodeData(node: Konva.Node) {
const attrs = this.getShapeAttrs(node);
delete attrs.image;
if (attrs.type === 'state-icon') delete attrs.state_color;
const data: any = {
attrs,
className: node.getClassName()
};
if (node instanceof Konva.Group) {
data.children = node.getChildren().map((child) => this.getNodeData(child));
}
return data;
}
|
/**
* Get node
* - removes image attribute because it can't be serialized
* - removes state-icon color
* - handles nested group nodes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L2036-L2052
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaEditor.destroyEditor
|
public destroyEditor() {
window.removeEventListener('mousemove', this.handleMouseMove);
window.removeEventListener('mouseup', this.handleMouseup);
this.unsubscribe?.();
super.destroyBase();
}
|
/**
* Destroy editor
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaEditor.ts#L2063-L2068
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaViewer.handleMount
|
private async handleMount() {
this.layer
.getChildren((node) => node instanceof Konva.Shape || node instanceof Konva.Group)
.forEach((node) => {
if (!node.isVisible() || this.isGuide(node)) {
node.remove();
} else {
this.handleNodeClick(node);
if (node?.attrs?.type === 'state-label' && node instanceof Konva.Text) {
this.updateStateLabel(node, undefined);
}
}
});
await Promise.all(
this.layer.find('Image').map(async (node) => {
if (node instanceof Konva.Image) {
const type = node.attrs.type;
switch (type) {
case 'icon':
case 'state-icon':
await this.updateIcon(node);
break;
case 'image':
await this.updateImage(node, node.getAttr('src'), false);
if (node.getAttr('id')) {
const image = node.image();
if (image instanceof HTMLImageElement) {
this.updateImageCache(node.getAttr('id'), image);
}
}
break;
}
}
})
);
// update state-icon again when everything's loaded
await Promise.all(
this.layer.find('Image').map(async (node) => {
if (node instanceof Konva.Image && node.attrs.type === 'state-icon') {
await this.updateStateIcon(node, undefined);
}
})
);
}
|
/**
* Handles mount
* - removes guides and hidden shapes
* - disables `draggable` attribute
* - handles state-label with no entity_id
* - loads images and icons
* - updates $konvaImageCache
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L27-L73
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaViewer.subscribeStates
|
private subscribeStates() {
this.unsubscribe = states.subscribe(($states) => {
if (this.layer && $states) {
const nodes = this.layer.getChildren(
(node) => node.getAttr('entity_id') && node?.attrs?.type?.startsWith('state-')
);
nodes.forEach((node) => {
if (node instanceof Konva.Image) {
this.updateStateIcon(node, $states);
} else if (node instanceof Konva.Text) {
this.updateStateLabel(node, $states);
}
});
}
});
}
|
/**
* Subscribes to $states store
* and updates 'state-' shapes
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L79-L94
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaViewer.handleNodeClick
|
private handleNodeClick(node: Konva.Node) {
const onclick = node.getAttr('onclick');
node.listening(!!onclick);
node.draggable(false);
node.off('mouseenter mouseleave click tap');
if (onclick && typeof onclick === 'object') {
const setCursor = (cursor: string) => {
this.stage.container().style.cursor = get(editMode) ? 'unset' : cursor;
};
node.on('mouseenter', () => setCursor('pointer'));
node.on('mouseleave', () => setCursor('default'));
node.on('click tap', async () => {
if (get(editMode)) return;
const conn = get(connection);
if (!conn) {
console.error('No connection', conn);
return;
}
const { domain, service, data, target } = onclick;
if (!domain || !service) {
console.error('Invalid service call', onclick);
return;
}
const pos = this.stage.getPointerPosition();
if (pos) this.ripple(pos.x, pos.y);
try {
await callService(conn, domain, service, data, target);
} catch (err) {
console.error('Error calling service:', err);
}
});
}
}
|
/**
* Handle click events
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L99-L140
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaViewer.updateLayerChildren
|
public async updateLayerChildren(data: any[]) {
this.layer
.getChildren((node) => !data.some((nodeData) => nodeData?.attrs?.id === node.getAttr('id')))
.forEach((node) => node.destroy());
await Promise.all(
data
.filter((nodeData) => !this.isGuide(nodeData))
.map(async (nodeData, index) => {
let node = this.layer.findOne(`#${nodeData?.attrs?.id}`) as Konva.Node;
if (node) {
await this.updateNode(node, nodeData);
} else {
node = await this.createNode(nodeData);
this.layer.add(node as Konva.Shape | Konva.Group);
}
if (node) {
node.zIndex(index);
if (node instanceof Konva.Image && node.getAttr('id')) {
const image = node.image();
if (image instanceof HTMLImageElement) {
this.updateImageCache(node.getAttr('id'), image);
}
}
}
})
);
}
|
/**
* Updates layer children
* - removes nonexistent nodes
* - updates or creates nodes
* - updates $konvaImageCache
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L148-L176
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaViewer.updateNode
|
private async updateNode(node: Konva.Node, nodeData: Konva.Node) {
const onclick = nodeData?.attrs?.onclick;
node.setAttr('onclick', onclick ? JSON.parse(JSON.stringify(onclick)) : undefined);
const type = node?.attrs?.type;
if (type === 'state-label' && node instanceof Konva.Text) {
node.setAttrs({
...nodeData?.attrs,
text: node.getAttr('text')
});
} else if (type === 'state-icon' && node instanceof Konva.Image) {
node.setAttrs({
...nodeData?.attrs,
...{
image: node.getAttr('image'),
icon: node.getAttr('icon'),
state_color: node.getAttr('state_color')
}
});
} else {
node.setAttrs(nodeData?.attrs);
}
if (node instanceof Konva.Image) {
if (type === 'state-icon') {
await this.updateStateIcon(node, undefined);
} else if (type === 'icon') {
await this.updateIcon(node);
} else if (type === 'image') {
await this.updateImage(node, node.getAttr('src'), false);
}
}
this.handleNodeClick(node);
}
|
/**
* Handle node updates
* - updates `onclick` attribute
* - updates node attributes
* - loads any icons/images
*
* does not update reactive attributes:
* - state-label `text`
* - state-icon `image`, `icon` and `state_color`
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L188-L222
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
ha-fusion
|
github_2023
|
matt8707
|
typescript
|
KonvaViewer.createNode
|
private async createNode(nodeData: Konva.Node) {
let node;
const attrs = nodeData?.attrs;
const type = attrs?.type;
switch (type) {
case 'state-label':
node = new Konva.Text(attrs);
this.updateStateLabel(node, undefined);
break;
case 'state-icon':
node = new Konva.Image(attrs);
this.updateStateIcon(node, undefined);
break;
case 'text':
node = new Konva.Text(attrs);
break;
case 'icon':
node = new Konva.Image(attrs);
await this.updateIcon(node);
break;
case 'image':
node = new Konva.Image(attrs);
await this.updateImage(node, attrs?.src, false);
break;
case 'rectangle':
node = new Konva.Rect(attrs);
break;
case 'circle':
node = new Konva.Circle(attrs);
break;
case 'group':
node = new Konva.Group(attrs);
if ('children' in nodeData && Array.isArray(nodeData?.children)) {
for (const child of nodeData.children) {
// recursive
const childNode = await this.createNode(child);
node.add(childNode);
}
}
break;
default:
console.error(type, 'type not found');
node = new Konva.Shape(attrs);
}
this.handleNodeClick(node);
return node;
}
|
/**
* Handle node creation
*/
|
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L227-L276
|
25c374d31ccf1ea05aaf324d473ff975181c0308
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.