{{ message }}
Repository navigation
2d-color-picker: code editor support and other improvements #9161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mxmou
wants to merge
9
commits into
ScratchAddons:master
Choose a base branch
from
mxmou:2d-color-picker
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+264
−227
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
24588af
2d-color-picker: simpler implementation
mxmou 6157f51
Improve shade slider
mxmou 7a3c31a
2D color picker in code editor
mxmou ac80feb
Fix dragging on touch screen
mxmou d5d890b
Dynamic enable/disable
mxmou 2b01c18
Use same rounding as Scratch in code editor
mxmou 2106ff1
Update addon.json
mxmou e7d88fe
Format code
mxmou febe5b3
Explain added quotes
mxmou File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This SVG file is intentionally not minified - it contains a comment explaining how I calculated the offsets for gradient stops. |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import ShadePicker from "./shade-picker.js"; | ||
|
|
||
| export default async function ({ addon, console, msg }) { | ||
| const Blockly = await addon.tab.traps.getBlockly(); | ||
|
|
||
| const oldShowEditor = Blockly.FieldColourSlider.prototype.showEditor_; | ||
| Blockly.FieldColourSlider.prototype.showEditor_ = function (...args) { | ||
| oldShowEditor.call(this, ...args); | ||
|
|
||
| this.saShadePicker = new ShadePicker(addon, msg, { roundMethod: Math.floor }); | ||
| const [shadeSlider, shadeLabel] = this.saShadePicker.createElements({ | ||
| h: this.hue_, | ||
| s: this.saturation_, | ||
| v: this.brightness_ / 255, | ||
| }); | ||
| this.saShadePicker.addEventListener("change", (e) => { | ||
| const { s, v } = e.detail; | ||
| this.saturation_ = s; | ||
| this.brightness_ = 255 * v; | ||
| this.setValue(Blockly.utils.colour.hsvToHex(this.hue_, this.saturation_, this.brightness_), true); | ||
| }); | ||
|
|
||
| this.saturationSlider_.classList.add("sa-2dcolor-hidden"); | ||
| this.saturationSlider_.previousSibling.classList.add("sa-2dcolor-hidden"); | ||
| this.brightnessSlider_.classList.add("sa-2dcolor-hidden"); | ||
| this.brightnessSlider_.previousSibling.classList.add("sa-2dcolor-hidden"); | ||
| this.hueSlider_.insertAdjacentElement("afterend", shadeSlider); | ||
| this.hueSlider_.insertAdjacentElement("afterend", shadeLabel); | ||
| }; | ||
|
|
||
| const oldUpdateDom = Blockly.FieldColourSlider.prototype.updateDom_; | ||
| Blockly.FieldColourSlider.prototype.updateDom_ = function (...args) { | ||
| oldUpdateDom.call(this, ...args); | ||
| if (this.saShadePicker) { | ||
| this.saShadePicker.setColor({ | ||
| h: this.hue_, | ||
| s: this.saturation_, | ||
| v: this.brightness_ / 255, | ||
| }); | ||
| } | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,253 +1,67 @@ | ||
| // this script was happily stolen from the color-picker addon, developed by Richie Bendall and apple502j | ||
|
|
||
| // import required libraries | ||
| import { normalizeHex } from "../../libraries/common/cs/normalize-color.js"; | ||
| import RateLimiter from "../../libraries/common/cs/rate-limiter.js"; | ||
| import ShadePicker from "./shade-picker.js"; | ||
|
|
||
| export default async ({ addon, console, msg }) => { | ||
| let prevEventHandler; | ||
| // 250-ms rate limit | ||
| const rateLimiter = new RateLimiter(250); | ||
| let pickerContainer; | ||
| let setPickerState; | ||
|
|
||
| // get the color from scratch | ||
| const getColor = (element) => { | ||
| let fillOrStroke; | ||
| const state = addon.tab.redux.state; | ||
| if (state.scratchPaint.modals.fillColor) { | ||
| fillOrStroke = "fill"; | ||
| } else if (state.scratchPaint.modals.strokeColor) { | ||
| fillOrStroke = "stroke"; | ||
| } else { | ||
| return; | ||
| } | ||
| const colorType = state.scratchPaint.fillMode.colorIndex; | ||
| const primaryOrSecondary = ["primary", "secondary"][colorType]; | ||
| const color = state.scratchPaint.color[`${fillOrStroke}Color`][primaryOrSecondary]; | ||
| if (color === null || color === "scratch-paint/style-path/mixed") return; | ||
| // This value can be arbitrary - it can be HEX, RGB, etc. | ||
| // Use tinycolor to convert them. | ||
| return tinycolor(color).toHex(); | ||
| }; | ||
|
|
||
| // load the new color to scratch | ||
| const setColor = (hex, element) => { | ||
| hex = normalizeHex(hex); | ||
| if (!addon.tab.redux.state || !addon.tab.redux.state.scratchPaint) return; | ||
| // The only way to reliably set color is to invoke eye dropper via click() | ||
| // then faking that the eye dropper reported the value. | ||
| const onEyeDropperOpened = ({ detail }) => { | ||
| if (detail.action.type !== "scratch-paint/eye-dropper/ACTIVATE_COLOR_PICKER") return; | ||
| addon.tab.redux.removeEventListener("statechanged", onEyeDropperOpened); | ||
| setTimeout(() => { | ||
| const previousTool = addon.tab.redux.state.scratchPaint.color.eyeDropper.previousTool; | ||
| if (previousTool) previousTool.activate(); | ||
| addon.tab.redux.state.scratchPaint.color.eyeDropper.callback(hex); | ||
| addon.tab.redux.dispatch({ | ||
| type: "scratch-paint/eye-dropper/DEACTIVATE_COLOR_PICKER", | ||
| }); | ||
| }, 50); | ||
| const getColor = () => { | ||
| return { | ||
| h: (pickerContainer.state.hue / 100) * 360, | ||
| s: pickerContainer.state.saturation / 100, | ||
| v: pickerContainer.state.brightness / 100, | ||
| }; | ||
| addon.tab.redux.addEventListener("statechanged", onEyeDropperOpened); | ||
| element.children[1].children[0].click(); | ||
| }; | ||
|
|
||
| // for the color picker's background color | ||
| const convertToGeneralColor = (hex) => { | ||
| let h = tinycolor(hex).toHsv(); | ||
| h.s = 1; | ||
| h.v = 1; | ||
| return tinycolor(h).toHex(); | ||
| }; | ||
|
|
||
| // le loop | ||
| while (true) { | ||
| // wait for color dialog box appearance | ||
| const element = await addon.tab.waitForElement('[class*="color-picker_swatch-row_"]', { | ||
| const swatchRow = await addon.tab.waitForElement('[class*="color-picker_swatch-row_"]', { | ||
| markAsSeen: true, | ||
| reduxCondition: (state) => state.scratchGui.editorTab.activeTabIndex === 1 && !state.scratchGui.mode.isPlayerOnly, | ||
| }); | ||
| rateLimiter.abort(false); | ||
| const colorPicker = swatchRow.parentElement; | ||
| const internalKey = addon.tab.traps.getInternalKey(colorPicker); | ||
| let internalInstance = colorPicker[internalKey]; | ||
| while (!internalInstance.stateNode?.props?.onChangeColor) { | ||
| internalInstance = internalInstance.return; | ||
| } | ||
| pickerContainer = internalInstance.stateNode; | ||
|
|
||
| if (!("colorIndex" in addon.tab.redux.state.scratchPaint.fillMode)) { | ||
| console.error("Detected new paint editor; this will be supported in future versions."); | ||
| return; | ||
| } | ||
|
|
||
| // update the bg color of the picker | ||
| function updateColor() { | ||
| rateLimiter.limit(() => { | ||
| let c = getColor(element); | ||
| let chsv = tinycolor(c).toHsv(); | ||
| updateHandleFinal(chsv.s, chsv.v); | ||
| saColorPicker.style.background = "#" + convertToGeneralColor(getColor(element)); | ||
| }); | ||
| shadePicker.setColor(getColor()); | ||
| } | ||
|
|
||
| // redux stuff | ||
| addon.tab.redux.initialize(); | ||
| addon.tab.redux.addEventListener("statechanged", (e) => | ||
| e.detail.action.type === "scratch-paint/fill-style/CHANGE_FILL_COLOR" || | ||
| e.detail.action.type === "scratch-paint/fill-style/CHANGE_FILL_COLOR_2" || | ||
| e.detail.action.type === "scratch-paint/stroke-style/CHANGE_STROKE_COLOR" || | ||
| e.detail.action.type === "scratch-paint/stroke-style/CHANGE_STROKE_COLOR_2" | ||
| ? updateColor() | ||
| : 0 | ||
| ); | ||
| if (addon.tab.redux && typeof prevEventHandler === "function") { | ||
| addon.tab.redux.removeEventListener("statechanged", prevEventHandler); | ||
| prevEventHandler = null; | ||
| } | ||
|
|
||
| // get the color | ||
| if (addon.tab.editorMode !== "editor") continue; | ||
| let defaultColor = getColor(element); | ||
|
|
||
| // create the color picker element and all it's child elements | ||
| const saColorPicker = document.createElement("div"); | ||
| saColorPicker.className = "sa-2dcolor-picker"; | ||
| saColorPicker.style.background = "#" + convertToGeneralColor(defaultColor || "ff0000"); | ||
|
|
||
| const saColorPickerImage = Object.assign(document.createElement("img"), { | ||
| className: "sa-2dcolor-picker-image", | ||
| src: addon.self.dir + "/assets/sv-gr.png", | ||
| draggable: false, | ||
| }); | ||
| const saColorPickerHandle = Object.assign(document.createElement("div"), { | ||
| className: addon.tab.scratchClass("slider_handle"), | ||
| }); | ||
| saColorPickerHandle.style.pointerEvents = "none"; | ||
|
|
||
| // create the label | ||
| const saColorLabel = document.createElement("div"); | ||
| saColorLabel.className = addon.tab.scratchClass("color-picker_row-header", { others: "sa-2dcolor-label" }); | ||
| const saColorLabelName = document.createElement("span"); | ||
| saColorLabelName.className = addon.tab.scratchClass("color-picker_label-name", { others: "sa-2dcolor-label-name" }); | ||
| saColorLabelName.innerText = msg("shade"); | ||
| const saColorLabelVal = document.createElement("span"); | ||
| saColorLabelVal.className = addon.tab.scratchClass("color-picker_label-readout", { | ||
| others: "sa-2dcolor-label-val", | ||
| }); | ||
| saColorLabel.appendChild(saColorLabelName); | ||
| saColorLabel.appendChild(saColorLabelVal); | ||
|
|
||
| let keyPressed = null; | ||
| let originalPos = { x: 0, y: 0 }; | ||
| window.addEventListener("keydown", (e) => (keyPressed = e.key)); | ||
| window.addEventListener("keyup", () => (keyPressed = null)); | ||
|
|
||
| let origHue = 0; | ||
| let el = null; | ||
|
|
||
| let mousemovefunc = function (e) { | ||
| updateHandle(e, keyPressed, originalPos); | ||
| return false; | ||
| }; | ||
|
|
||
| let mouseupfunc = function (e) { | ||
| updateFinal(e, keyPressed, originalPos); | ||
| setPickerState = pickerContainer.setState.bind(pickerContainer); | ||
| pickerContainer.setState = function (state, callback) { | ||
| setPickerState(state, (...args) => { | ||
| if (typeof callback === "function") callback(...args); | ||
| updateColor(); | ||
| }); | ||
| }; | ||
|
|
||
| function updateHandle(e, keyPressed, originalPos) { | ||
| let cx = Math.min(Math.max(e.clientX - saColorPicker.getBoundingClientRect().x, 0), 150); | ||
| let cy = Math.min(Math.max(e.clientY - saColorPicker.getBoundingClientRect().y, 0), 150); | ||
| if (keyPressed === "Shift") { | ||
| if (Math.abs(cx - originalPos.x) > Math.abs(cy - originalPos.y)) cy = originalPos.y; | ||
| else cx = originalPos.x; | ||
| } | ||
| saColorPickerHandle.style.left = cx - 8 + "px"; | ||
| saColorPickerHandle.style.top = cy - 8 + "px"; | ||
| saColorLabelVal.innerText = `${Math.round((cx / 150) * 100)}, ${100 - Math.round((cy / 150) * 100)}`; | ||
|
|
||
| //update color in real-time (i only bothered to do that for solid colors) | ||
| if ( | ||
| (!addon.tab.redux.state.scratchPaint.fillMode.gradientType || | ||
| addon.tab.redux.state.scratchPaint.fillMode.gradientType === "SOLID") && | ||
| el | ||
| ) { | ||
| let c = tinycolor({ h: origHue, s: cx / 150, v: 1 - cy / 150 }).toHex(); | ||
| if (c.startsWith("#")) el.style.background = c; | ||
| else el.style.background = "#" + c; | ||
| } | ||
| } | ||
|
|
||
| function updateHandleFinal(s, v) { | ||
| saColorPickerHandle.style.left = s * 150 - 8 + "px"; | ||
| saColorPickerHandle.style.top = (1 - v) * 150 - 8 + "px"; | ||
| saColorLabelVal.innerText = `${Math.round(s * 100)}, ${Math.round(v * 100)}`; | ||
| } | ||
|
|
||
| function updateFinal(e, keyPressed, originalPos) { | ||
| rateLimiter.limit(() => { | ||
| let ox = Math.min(Math.max(e.clientX - saColorPicker.getBoundingClientRect().x, 0), 150); | ||
| let oy = Math.min(Math.max(e.clientY - saColorPicker.getBoundingClientRect().y, 0), 150); | ||
| if (keyPressed === "Shift") { | ||
| if (Math.abs(ox - originalPos.x) > Math.abs(oy - originalPos.y)) oy = originalPos.y; | ||
| else ox = originalPos.x; | ||
| } | ||
|
|
||
| let color = tinycolor(getColor(element)).toHsv(); | ||
| let s = ox / 150; | ||
| let v = 1 - oy / 150; | ||
| let newColor = tinycolor({ h: color.h, s: s, v: v }).toHex(); | ||
| setColor(newColor, element); | ||
| updateHandleFinal(s, v); | ||
| let defaultColor = getColor(); | ||
| const shadePicker = new ShadePicker(addon, msg); | ||
| const [shadeSlider, shadeLabel] = shadePicker.createElements(defaultColor); | ||
| shadePicker.addEventListener("change", (e) => { | ||
| const { s, v } = e.detail; | ||
| setPickerState({ saturation: 100 * s, brightness: 100 * v }, () => { | ||
| pickerContainer.handleColorChange(); | ||
| }); | ||
|
|
||
| window.removeEventListener("pointermove", mousemovefunc); | ||
| window.removeEventListener("pointerup", mouseupfunc); | ||
| } | ||
|
|
||
| if (defaultColor) { | ||
| let defaultHexColor = tinycolor(defaultColor).toHsv(); | ||
| updateHandleFinal(defaultHexColor.s, defaultHexColor.v); | ||
| } else updateHandleFinal(1, 1); | ||
|
|
||
| saColorPicker.addEventListener("pointerdown", (e) => { | ||
| e.preventDefault(); | ||
|
|
||
| originalPos = { | ||
| x: parseFloat(saColorPickerHandle.style.left) + 8, | ||
| y: parseFloat(saColorPickerHandle.style.top) + 8, | ||
| }; | ||
|
|
||
| let fillOrStroke; | ||
| const state = addon.tab.redux.state; | ||
| if (state.scratchPaint.modals.fillColor) { | ||
| fillOrStroke = "fill"; | ||
| } else if (state.scratchPaint.modals.strokeColor) { | ||
| fillOrStroke = "stroke"; | ||
| } else { | ||
| fillOrStroke = "wh"; | ||
| } | ||
|
|
||
| el = null; | ||
| if (fillOrStroke === "fill") | ||
| el = document.getElementsByClassName(addon.tab.scratchClass("color-button_color-button-swatch"))[0]; | ||
| else if (fillOrStroke === "stroke") | ||
| el = document.getElementsByClassName(addon.tab.scratchClass("color-button_color-button-swatch"))[1]; | ||
| if (el) origHue = tinycolor(el.style.background).toHsv().h; | ||
|
|
||
| updateHandle(e); | ||
|
|
||
| window.addEventListener("pointermove", mousemovefunc); | ||
| window.addEventListener("pointerup", mouseupfunc); | ||
| }); | ||
| prevEventHandler = ({ detail }) => { | ||
| if (detail.action.type === "scratch-paint/color-index/CHANGE_COLOR_INDEX") { | ||
| setTimeout(() => { | ||
| updateColor(); | ||
| }, 100); | ||
| } | ||
| }; | ||
| addon.tab.redux.addEventListener("statechanged", prevEventHandler); | ||
| saColorPicker.appendChild(saColorPickerImage); | ||
| saColorPicker.appendChild(saColorPickerHandle); | ||
|
|
||
| const [colorSlider, saturationSlider, brightnessSlider] = [ | ||
| ...element.parentElement.querySelectorAll('[class*="color-picker_row-header_"]'), | ||
| ...colorPicker.querySelectorAll('[class*="color-picker_row-header_"]'), | ||
| ].map((i) => i.parentElement); | ||
| saturationSlider.style.display = "none"; | ||
| brightnessSlider.style.display = "none"; | ||
| colorSlider.insertAdjacentElement("afterend", saColorPicker); | ||
| colorSlider.insertAdjacentElement("afterend", saColorLabel); | ||
| saturationSlider.classList.add("sa-2dcolor-hidden"); | ||
| brightnessSlider.classList.add("sa-2dcolor-hidden"); | ||
| colorSlider.insertAdjacentElement("afterend", shadeSlider); | ||
| colorSlider.insertAdjacentElement("afterend", shadeLabel); | ||
| } | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
You can’t perform that action at this time.

There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wasn't sure if I should add the
codeEditortag. The hex color picker addon doesn't have it.