├── .npmrc ├── .eslintignore ├── ColorPaletteDemo.png ├── .editorconfig ├── .gitignore ├── manifest.json ├── documentation ├── index.md ├── Colors.md ├── Settings.md ├── Commands.md └── PaletteSettings.md ├── tsconfig.json ├── version-bump.mjs ├── .eslintrc ├── package.json ├── versions.json ├── esbuild.config.mjs ├── src ├── utils │ ├── EventEmitter.ts │ ├── generateUtils.ts │ ├── editorUtils.ts │ ├── imageUtils.ts │ ├── basicUtils.ts │ ├── canvasUtils.ts │ └── dragDropUtils.ts ├── components │ ├── GenerateModal.ts │ ├── ReorderModal.ts │ ├── PaletteMenu.ts │ ├── PaletteItem.ts │ ├── PaletteMRC.ts │ ├── Palette.ts │ └── EditorModal.ts ├── main.ts └── settings.ts ├── README.md ├── styles.css └── LICENSE /.npmrc: -------------------------------------------------------------------------------- 1 | tag-version-prefix="" -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | 3 | main.js 4 | -------------------------------------------------------------------------------- /ColorPaletteDemo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ALegendsTale/obsidian-color-palette/HEAD/ColorPaletteDemo.png -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | indent_style = tab 9 | indent_size = 4 10 | tab_width = 4 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # vscode 2 | .vscode 3 | 4 | # Intellij 5 | *.iml 6 | .idea 7 | 8 | # npm 9 | node_modules 10 | 11 | # Don't include the compiled main.js file in the repo. 12 | # They should be uploaded to GitHub releases instead. 13 | main.js 14 | 15 | # Exclude sourcemaps 16 | *.map 17 | 18 | # obsidian 19 | data.json 20 | 21 | # Exclude macOS Finder (System Explorer) View States 22 | .DS_Store 23 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "color-palette", 3 | "name": "Color Palette", 4 | "version": "2.15.0", 5 | "minAppVersion": "0.15.0", 6 | "description": "Create and insert color palettes into your notes.", 7 | "author": "ALegendsTale", 8 | "authorUrl": "https://github.com/ALegendsTale", 9 | "fundingUrl": { 10 | "GitHub Sponsor": "https://github.com/sponsors/ALegendsTale", 11 | "PayPal": "https://www.paypal.com/donate/?hosted_button_id=BHHFMGX822K4S" 12 | }, 13 | "isDesktopOnly": false 14 | } -------------------------------------------------------------------------------- /documentation/index.md: -------------------------------------------------------------------------------- 1 | # Obsidian Color Palette Documentation 2 | 3 | ## Plugin 4 | 5 | There are default settings which can be modified in the Obsidian settings modal. 6 | There are also commands which can be opened using the command palette hotkey (defaults to CTRL + P). 7 | 8 | - [Settings](./Settings.md) 9 | - [Commands](./Commands.md) 10 | 11 | ## Palette 12 | 13 | Palettes can be formed using colors & settings. 14 | 15 | - [Colors](./Colors.md) 16 | - [Palette Settings](./PaletteSettings.md) 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "src", 4 | "inlineSourceMap": true, 5 | "inlineSources": true, 6 | "module": "ESNext", 7 | "target": "ES2018", 8 | "allowJs": true, 9 | "noImplicitAny": true, 10 | "moduleResolution": "node", 11 | "importHelpers": true, 12 | "isolatedModules": true, 13 | "resolveJsonModule": true, 14 | "esModuleInterop": true, 15 | "strictNullChecks": true, 16 | "lib": [ 17 | "DOM", 18 | "ES5", 19 | "ES6", 20 | "ES7" 21 | ] 22 | }, 23 | "include": [ 24 | "**/*.ts" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /version-bump.mjs: -------------------------------------------------------------------------------- 1 | import { readFileSync, writeFileSync } from "fs"; 2 | 3 | const targetVersion = process.env.npm_package_version; 4 | 5 | // read minAppVersion from manifest.json and bump version to target version 6 | let manifest = JSON.parse(readFileSync("manifest.json", "utf8")); 7 | const { minAppVersion } = manifest; 8 | manifest.version = targetVersion; 9 | writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t")); 10 | 11 | // update versions.json with target version and minAppVersion from manifest.json 12 | let versions = JSON.parse(readFileSync("versions.json", "utf8")); 13 | versions[targetVersion] = minAppVersion; 14 | writeFileSync("versions.json", JSON.stringify(versions, null, "\t")); 15 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "env": { "node": true }, 5 | "plugins": [ 6 | "@typescript-eslint" 7 | ], 8 | "extends": [ 9 | "eslint:recommended", 10 | "plugin:@typescript-eslint/eslint-recommended", 11 | "plugin:@typescript-eslint/recommended" 12 | ], 13 | "parserOptions": { 14 | "sourceType": "module" 15 | }, 16 | "rules": { 17 | "no-unused-vars": "off", 18 | "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }], 19 | "@typescript-eslint/ban-ts-comment": "off", 20 | "no-prototype-builtins": "off", 21 | "@typescript-eslint/no-empty-function": "off" 22 | } 23 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "color-palette", 3 | "version": "2.15.0", 4 | "description": "Create and insert color palettes into your notes.", 5 | "main": "src/main.js", 6 | "scripts": { 7 | "dev": "node esbuild.config.mjs", 8 | "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", 9 | "version": "node version-bump.mjs && git add manifest.json versions.json" 10 | }, 11 | "keywords": [], 12 | "author": "ALegendsTale", 13 | "license": "GNU GPLv3", 14 | "dependencies": { 15 | "colorsea": "^1.2.2", 16 | "quantize": "^1.0.2", 17 | "validate-color": "^2.2.4" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^16.11.6", 21 | "@types/quantize": "^1.0.2", 22 | "@typescript-eslint/eslint-plugin": "5.29.0", 23 | "@typescript-eslint/parser": "5.29.0", 24 | "builtin-modules": "3.3.0", 25 | "esbuild": "0.17.3", 26 | "obsidian": "latest", 27 | "tslib": "^2.4.0", 28 | "typescript": "latest" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /versions.json: -------------------------------------------------------------------------------- 1 | { 2 | "1.0.0": "0.15.0", 3 | "1.0.1": "0.15.0", 4 | "1.1.0": "0.15.0", 5 | "1.1.1": "0.15.0", 6 | "1.2.0": "0.15.0", 7 | "2.0.0": "0.15.0", 8 | "2.0.1": "0.15.0", 9 | "2.1.0": "0.15.0", 10 | "2.1.1": "0.15.0", 11 | "2.2.0": "0.15.0", 12 | "2.3.0": "0.15.0", 13 | "2.4.0": "0.15.0", 14 | "2.5.0": "0.15.0", 15 | "2.5.1": "0.15.0", 16 | "2.5.2": "0.15.0", 17 | "2.5.3": "0.15.0", 18 | "2.5.4": "0.15.0", 19 | "2.6.0": "0.15.0", 20 | "2.7.0": "0.15.0", 21 | "2.7.1": "0.15.0", 22 | "2.8.0": "0.15.0", 23 | "2.9.0": "0.15.0", 24 | "2.9.1": "0.15.0", 25 | "2.9.2": "0.15.0", 26 | "2.10.0": "0.15.0", 27 | "2.11.0": "0.15.0", 28 | "2.12.0": "0.15.0", 29 | "2.12.1": "0.15.0", 30 | "2.12.2": "0.15.0", 31 | "2.13.0": "0.15.0", 32 | "2.13.1": "0.15.0", 33 | "2.13.2": "0.15.0", 34 | "2.13.3": "0.15.0", 35 | "2.13.4": "0.15.0", 36 | "2.13.5": "0.15.0", 37 | "2.13.6": "0.15.0", 38 | "2.13.7": "0.15.0", 39 | "2.14.0": "0.15.0", 40 | "2.15.0": "0.15.0" 41 | } -------------------------------------------------------------------------------- /esbuild.config.mjs: -------------------------------------------------------------------------------- 1 | import esbuild from "esbuild"; 2 | import process from "process"; 3 | import builtins from "builtin-modules"; 4 | 5 | const banner = 6 | `/* 7 | THIS IS A GENERATED/BUNDLED FILE BY ESBUILD 8 | if you want to view the source, please visit the github repository of this plugin 9 | */ 10 | `; 11 | 12 | const prod = (process.argv[2] === "production"); 13 | 14 | const context = await esbuild.context({ 15 | banner: { 16 | js: banner, 17 | }, 18 | entryPoints: ["src/main.ts"], 19 | bundle: true, 20 | external: [ 21 | "obsidian", 22 | "electron", 23 | "@codemirror/autocomplete", 24 | "@codemirror/collab", 25 | "@codemirror/commands", 26 | "@codemirror/language", 27 | "@codemirror/lint", 28 | "@codemirror/search", 29 | "@codemirror/state", 30 | "@codemirror/view", 31 | "@lezer/common", 32 | "@lezer/highlight", 33 | "@lezer/lr", 34 | ...builtins], 35 | format: "cjs", 36 | target: "es2018", 37 | logLevel: "info", 38 | sourcemap: prod ? false : "inline", 39 | treeShaking: true, 40 | outfile: "main.js", 41 | }); 42 | 43 | if (prod) { 44 | await context.rebuild(); 45 | process.exit(0); 46 | } else { 47 | await context.watch(); 48 | } -------------------------------------------------------------------------------- /src/utils/EventEmitter.ts: -------------------------------------------------------------------------------- 1 | export type Listener> = (...args: T) => void; 2 | 3 | export class EventEmitter>> { 4 | private eventListeners: { [K in keyof EventMap]?: Set>} = {}; 5 | 6 | public on(eventName: K, listener: Listener) { 7 | const listeners = this.eventListeners[eventName] ?? new Set(); 8 | listeners.add(listener); 9 | this.eventListeners[eventName] = listeners; 10 | } 11 | 12 | public off(eventName: K, listener: Listener) { 13 | const listeners = this.eventListeners[eventName] ?? new Set(); 14 | listeners.delete(listener); 15 | this.eventListeners[eventName] = listeners; 16 | } 17 | 18 | public emit(eventName: K, ...args: EventMap[K]) { 19 | const listeners = this.eventListeners[eventName] ?? new Set(); 20 | for(const listener of listeners) { 21 | listener(...args); 22 | } 23 | } 24 | 25 | public clear() { 26 | this.eventListeners = {}; 27 | } 28 | } -------------------------------------------------------------------------------- /documentation/Colors.md: -------------------------------------------------------------------------------- 1 | # Colors 2 | 3 | ## Color Formats 4 | 5 | There are three primarily supported color formats. 6 | These are **HEX**, **RGB**, and **HSL**. **Named colors** & **URL** can also be used. 7 | 8 | ### HEX 9 | 10 | 3, 4, 6, or 8 character HEX codes are all accepted. 11 | HEX are delimited by commas. 12 | 13 |
14 | ```palette
15 | #434
16 | #f6f7d7
17 | ```
18 | 
19 | 20 | ### RGB 21 | 22 | RGB can be specified in both RGB and RGBA formats. 23 | 24 |
25 | ```palette
26 | rgb(123, 555, 777)
27 | rgba(122, 222, 772, .7)
28 | ```
29 | 
30 | 31 | ### HSL 32 | 33 |
34 | ```palette
35 | hsl(5, 20%, 70%)
36 | hsl(5, 70%, 70%)
37 | ```
38 | 
39 | 40 | ### Named Colors 41 | 42 | Named CSS colors are also supported. 43 | 44 |
45 | ```palette
46 | grey
47 | pink
48 | ```
49 | 
50 | 51 | ### URLs 52 | 53 | > URLs are currently limited to & . 54 | 55 |
56 | ```palette
57 | https://colorhunt.co/palette/3ec1d3f6f7d7ff9a00ff165d
58 | ```
59 | 
60 | 61 | ## Delimiters 62 | 63 | Colors can be specified when creating palettes in many different ways. 64 | The main delimiters include **newline**, **comma**, and **semicolon**. 65 | 66 | ### Newline 67 | 68 | Newline is the preferred delimiter for all formats. 69 | 70 |
71 | ```palette
72 | #434
73 | #f6f7d7
74 | ```
75 | 
76 | 77 | ### Comma 78 | 79 |
80 | ```palette
81 | #434, #f6f7d7, #3EC1D3, #FF165D, #FF9A00, #f6f7d7
82 | ```
83 | 
84 | 85 | ### Semicolon 86 | 87 | Semicolon delimiters can be used with the `RGB` and `HSL` formats. 88 | 89 |
90 | ```palette
91 | rgb(123, 555, 777); rgb(122, 222, 772);
92 | ```
93 | 
94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Color Palette 2 | 3 | Create beautiful & functional color palettes that enhance the appearance of your notes. 4 | 5 | ![Color Palette Demo](ColorPaletteDemo.png) 6 | 7 | ## Key Features 8 | 9 | - Supports most CSS color formats (including Hex, RGB, HSL, etc.) 10 | - Create color palettes from popular palette websites like coolors & colorhunt. 11 | - Style like a pro with gorgeous gradients. 12 | - Easily copy color codes by selecting them. 13 | 14 | ## Full Documentation 15 | 16 | [Documentation](/documentation/index.md) 17 | 18 | ## Quick Start 19 | 20 | Palettes can be created manually by adding a codeblock with the color codes desired. 21 | 22 |
23 | ```palette
24 | #ffffff, #000
25 | ```
26 | 
27 | 28 |
29 | ```palette
30 | rgb(125, 255, 255);
31 | rgb(255, 255, 125);
32 | ```
33 | 
34 | 35 | Palettes can also be created from links.\ 36 | *Only URLs from & are currently supported.* 37 | 38 |
39 | ```palette
40 | https://colorhunt.co/ffffff
41 | ```
42 | 
43 | 44 | Optional settings can be applied to each palette within the codeblock. 45 |
46 | ```palette
47 | #fff, #000fff00
48 | {"gradient": true, "aliases": ["white", "black"]}
49 | ```
50 | 
51 | 52 | ### Palette Settings 53 | 54 | - height (number) 55 | - width (number) 56 | - direction (row/column) 57 | - gradient (true/false) 58 | - hover (true/false) 59 | - hideText (true/false) 60 | - override (true/false) 61 | - aliases (string array) 62 | 63 | > Caution - using width might cause palettes to display incorrectly. 64 | 65 | ### Commands 66 | 67 | Commands can be bound to a hotkey in settings. 68 | 69 | - Create - Advanced palette editor 70 | - Convert link - Converts a selected URL to a palette 71 | - Convert codeblock link to hex 72 | - Generate random palette - Creates a new random palette based on color theory combinations 73 | -------------------------------------------------------------------------------- /documentation/Settings.md: -------------------------------------------------------------------------------- 1 | # Settings 2 | 3 | Plugin settings can be specified in the settings modal in Obsidian. 4 | 5 | ## Primary Settings 6 | 7 | ### Palette Error Pulse 8 | 9 | > Default: True 10 | 11 | Toggle which affects whether the affected palette will pulse when encountering an error. 12 | 13 | ### Notice Duration 14 | 15 | > Default: 5 16 | 17 | `number` which affects how long error messages are shown for in seconds (0 for indefinite). 18 | 19 | ### Alias Mode 20 | 21 | > Default: Both 22 | 23 | Dropdown which has `Both` and `Prefer Alias` options. 24 | 25 | - When `Both` is selected, both the color format & alias will show at the same time. 26 | - When `Prefer Alias` is selected, only the alias will show. 27 | 28 | ### Palette Corners 29 | 30 | > Default: True 31 | 32 | Purely aesthetic change which toggles whether the corners on palettes are rounded. 33 | 34 | ### Stability While Editing 35 | 36 | > Default: True 37 | 38 | Keeps the palette from moving while in edit mode. 39 | 40 | ### Reload Delay 41 | 42 | > Default: 5 43 | 44 | Modifies the speed at which the palette will reload when resizing or changing. 45 | Smaller values means the palette will be more responsive, but require more processing. 46 | It is recommended to keep this value between 0 - 1000. 47 | 48 | ### Copy Format 49 | 50 | > Default: Raw 51 | 52 | Changes the format that colors are copied in. `Raw` format copies the entire color as show. 53 | `Value` format copies only the value contained within a color. 54 | Example: `RGBA(12, 200, 50);` Only `12, 200, 50` is copied. 55 | 56 | ## Palette Defaults 57 | 58 | The default values of [Palette Settings](./PaletteSettings.md) if the user does not directly modify them. 59 | 60 | ### Height 61 | 62 | > Default: 150 63 | 64 | ### Width 65 | 66 | > Default: 700 67 | 68 | ### Direction 69 | 70 | > Default: Column 71 | 72 | ### Gradient 73 | 74 | > Default: False 75 | 76 | ### Hover 77 | 78 | > Default: True 79 | 80 | ### Hide Text 81 | 82 | > Default: False 83 | 84 | ### Override 85 | 86 | > Default: False 87 | -------------------------------------------------------------------------------- /documentation/Commands.md: -------------------------------------------------------------------------------- 1 | # Commands 2 | 3 | ## Create 4 | 5 | Launches the palette editor to create a new palette. 6 | The editor will always initially launch with random palette colors. 7 | 8 | The editor has tabs which can be swapped between to add colors. 9 | These tabs are **Color Picker**, **Generate**, **Image**, and **URL**. 10 | 11 | ### Colors 12 | 13 | #### Color Picker 14 | 15 | Simply open the color picker, select a color, then select the editor again to add a color. 16 | 17 | #### Generate 18 | 19 | The Generate tab comes with a dropdown where the preferred color theory can be chosen. 20 | Next to the dropdown is a color picker which can be used to choose a base color for whichever color theory was chosen. 21 | 22 | #### Image 23 | 24 | The Image tab can accept a URL or the user can select the button to choose a file to use. 25 | 26 | When a file is selected, the image preview will be unhidden and it will generate colors based on the image. 27 | The user can change the `Count` slider to a value they prefer for generating colors. 28 | Alternatively, colors can be picked directly from the image. 29 | 30 | #### URL 31 | 32 | The palette can be created from a URL. 33 | 34 | > URLs are currently limited to & . 35 | 36 | ### Settings 37 | 38 | [Palette Settings](./PaletteSettings.md) can be modified here. 39 | They will affect the palette preview so that the appearance can be determined before creating it. 40 | 41 | ## Convert link 42 | 43 | This command can be used by selecting a URL or by using one copied from the clipboard. 44 | It will create a palette from that URL. 45 | 46 | ## Convert codeblock link to hex 47 | 48 | > This command is mostly deprecated. Please use the right click menu instead. 49 | 50 | This command takes a selected codeblock with a link inside and converts the link within into hex. 51 | 52 | Converts 53 |
54 | ```palette
55 | https://colorhunt.co/palette/3ec1d3f6f7d7ff9a00ff165d
56 | ```
57 | 
58 | 59 | into 60 | 61 |
62 | ```palette
63 | #3ec1d3
64 | #f6f7d7
65 | #ff9a00
66 | #ff165d
67 | ```
68 | 
69 | 70 | ## Generate random palette 71 | 72 | Generates a random palette based on which color theory is selected in the suggestion modal. 73 | -------------------------------------------------------------------------------- /src/components/GenerateModal.ts: -------------------------------------------------------------------------------- 1 | import { App, Editor, Notice, SuggestModal } from "obsidian"; 2 | import { PaletteSettings } from "./Palette"; 3 | import { ColorPaletteSettings } from "settings"; 4 | import { Combination, generateColors } from "utils/generateUtils"; 5 | import validateColor from "validate-color"; 6 | import colorsea from "colorsea"; 7 | import EditorUtils from "utils/editorUtils"; 8 | import { createPaletteBlock, getModifiedSettings, pluginToPaletteSettings } from "utils/basicUtils"; 9 | 10 | export class GenerateModal extends SuggestModal { 11 | editor: Editor; 12 | settings: PaletteSettings 13 | 14 | constructor(app: App, editor: Editor, pluginSettings: ColorPaletteSettings) { 15 | super(app); 16 | this.editor = editor; 17 | this.settings = pluginToPaletteSettings(pluginSettings); 18 | } 19 | 20 | // Returns all available suggestions. 21 | getSuggestions(query: string): Combination[] { 22 | return Object.keys(Combination).filter((combination) => 23 | combination.toLowerCase().includes(query.toLowerCase()) 24 | ) as Combination[]; 25 | } 26 | 27 | // Renders each suggestion item. 28 | renderSuggestion(combination: Combination, el: HTMLElement) { 29 | el.createEl("span", { text: combination }); 30 | } 31 | 32 | // Perform action on the selected suggestion. 33 | onChooseSuggestion(combination: Combination, evt: MouseEvent | KeyboardEvent) { 34 | try { 35 | const selTextOrLine = this.editor.somethingSelected() ? this.editor.getSelection() : this.editor.getLine(this.editor.getCursor().line); 36 | const isLineEmpty = this.editor.getLine(this.editor.getCursor().line).length === 0; 37 | const isColor = validateColor(selTextOrLine); 38 | const { colors, settings } = isColor ? generateColors(combination, { baseColor: colorsea(selTextOrLine), settings: this.settings }) : generateColors(combination, { settings: this.settings }); 39 | const newBlock = createPaletteBlock({ colors, settings: settings ? getModifiedSettings(settings) : undefined }); 40 | const editorUtils = new EditorUtils(this.editor); 41 | editorUtils.insertContent(newBlock, !isColor && !isLineEmpty); 42 | } 43 | catch (error) { 44 | new Notice(error); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /src/components/ReorderModal.ts: -------------------------------------------------------------------------------- 1 | import colorsea from "colorsea"; 2 | import { App, SuggestModal } from "obsidian"; 3 | import { Palette, PaletteSettings } from "./Palette"; 4 | import { getModifiedSettings } from "utils/basicUtils"; 5 | 6 | enum Reorder { 7 | Hue = 'Hue', 8 | Saturation = 'Saturation', 9 | Lightness = 'Lightness', 10 | Red = 'Red', 11 | Green = 'Green', 12 | Blue = 'Blue', 13 | Alpha = 'Alpha' 14 | } 15 | 16 | export class ReorderModal extends SuggestModal{ 17 | palette: Palette; 18 | onSubmit: (colors: string[], settings: Partial | undefined) => void; 19 | 20 | constructor(app: App, palette: Palette, onSubmit: (colors: string[], settings: Partial | undefined) => void) { 21 | super(app); 22 | this.palette = palette; 23 | this.onSubmit = onSubmit; 24 | } 25 | 26 | // Returns all available suggestions. 27 | getSuggestions(query: string): Reorder[] { 28 | return Object.keys(Reorder).filter((combination) => 29 | combination.toLowerCase().includes(query.toLowerCase()) 30 | ) as Reorder[]; 31 | } 32 | 33 | renderSuggestion(order: Reorder, el: HTMLElement) { 34 | el.createEl("span", { text: order }); 35 | } 36 | 37 | onChooseSuggestion(item: Reorder, evt: MouseEvent | KeyboardEvent) { 38 | // Create colorsea array 39 | const csColors = this.palette.colors.map((color) => { 40 | return colorsea(color); 41 | }) 42 | let colors: string[] = [] 43 | switch(item){ 44 | case Reorder.Hue: 45 | colors = csColors.sort((a, b) => a.hue() - b.hue()).map((color) => color.hex()); 46 | break; 47 | case Reorder.Saturation: 48 | colors = csColors.sort((a, b) => a.saturation() - b.saturation()).map((color) => color.hex()); 49 | break; 50 | case Reorder.Lightness: 51 | colors = csColors.sort((a, b) => a.lightness() - b.lightness()).map((color) => color.hex()); 52 | break; 53 | case Reorder.Red: 54 | colors = csColors.sort((a, b) => a.red() - b.red()).map((color) => color.hex()); 55 | break; 56 | case Reorder.Green: 57 | colors = csColors.sort((a, b) => a.green() - b.green()).map((color) => color.hex()); 58 | break; 59 | case Reorder.Blue: 60 | colors = csColors.sort((a, b) => a.blue() - b.blue()).map((color) => color.hex()); 61 | break; 62 | case Reorder.Alpha: 63 | colors = csColors.sort((a, b) => a.alpha() - b.alpha()).map((color) => color.hex()); 64 | break; 65 | } 66 | 67 | // Submit 68 | this.onSubmit( colors, getModifiedSettings(this.palette.settings)); 69 | } 70 | } -------------------------------------------------------------------------------- /documentation/PaletteSettings.md: -------------------------------------------------------------------------------- 1 | # Palette Settings 2 | 3 | **Palette Settings** are settings which are directly specified in the palette codeblock. 4 |
  5 | ```palette
  6 | #000
  7 | {  } 🠨 Specify palette settings here
  8 | ```
  9 | 
10 | They can be used to modify height, width, direction, gradient, hover, override, and aliases. 11 | 12 | ## Height 13 | 14 | Height can be set to modify how tall the palette is. 15 | 16 | Example: 17 | 18 |
 19 | ```palette
 20 | #f6f7d7
 21 | #3EC1D3
 22 | #FF165D
 23 | #FF9A00
 24 | #f6f7d7
 25 | { "height": 300 }
 26 | ```
 27 | 
 28 | 
29 | 30 | ## Width 31 | 32 | Width can be set to modify how wide the palette is. 33 | Be cautious when using this setting, as it can sometimes cause palettes to appear deformed. 34 | 35 |
 36 | ```palette
 37 | #999
 38 | #222
 39 | { "width": 400 }
 40 | ```
 41 | 
42 | 43 | ## Direction 44 | 45 | Direction can be set to change which direction the palette colors face. 46 | `column` is the default and appears vertically. `row` causes horizontal colors. 47 | 48 |
 49 | ```palette
 50 | #afc
 51 | #b31
 52 | { "direction": "row" }
 53 | ```
 54 | 
55 | 56 | ## Gradient 57 | 58 | The gradient setting toggles whether palette colors will appear as a gradient. 59 | 60 |
 61 | ```palette
 62 | #3ec1d3
 63 | #f6f7d7
 64 | #ff9a00
 65 | #ff165d
 66 | { "gradient": true }
 67 | ```
 68 | 
69 | 70 | ## Hover 71 | 72 | Hover controls whether palettes have any effect when hovered over with the mouse cursor. 73 | It also controls this on mobile when touching palettes. 74 | When disabled, color / alias text will show by default unless Hide Text is enabled. 75 | 76 |
 77 | ```palette
 78 | #8ec178
 79 | #25136d
 80 | { "hover": false }
 81 | ```
 82 | 
83 | 84 | ## Hide Text 85 | 86 | Hide Text toggles whether palettes display color / alias text. 87 | 88 |
 89 | ```palette
 90 | #8ec178
 91 | #25136d
 92 | { "hideText": true }
 93 | ```
 94 | 
95 | 96 | ## Override 97 | 98 | The override setting defaults to false. 99 | When set to true, it disables color validation. 100 | This is useful for creating palettes with atypical inputs (css variables for example). 101 | The [Obsidian Color Documentation](https://docs.obsidian.md/Reference/CSS+variables/Foundations/Colors) is a great source for finding colors that match Obsidian. 102 | 103 | Example: 104 | Ordinarily using CSS variables would not be permitted. 105 | When override is set to true, the palette will render. 106 | 107 |
108 | ```palette
109 | var(--color-orange)
110 | { "override": true }
111 | ```
112 | 
113 | 114 | Advanced Example: 115 | Using RGBA with a RGB CSS variable can allow the opacity to be set. 116 | 117 |
118 | ```palette
119 | rgba(var(--color-green-rgb), .5)
120 | { "override": true }
121 | ```
122 | 
123 | 124 | ## Aliases 125 | 126 | Aliases are names which accompany colors. 127 | They can be set in an array format. 128 | Each color has its own spot in the array. 129 | Skipping colors is possible by using empty quotes "". 130 | 131 |
132 | ```palette
133 | #444
134 | #222
135 | #322
136 | { "aliases": ["grey","black","brown"] }
137 | ```
138 | 
139 | -------------------------------------------------------------------------------- /src/utils/generateUtils.ts: -------------------------------------------------------------------------------- 1 | import colorsea from "colorsea"; 2 | import { PaletteSettings } from "components/Palette"; 3 | 4 | export enum Combination { 5 | Complimentary = "Complimentary", 6 | Monochromatic = "Monochromatic", 7 | Analogous = "Analogous", 8 | Triadic = "Triadic", 9 | Tetradic = "Tetradic", 10 | Random = "Random" 11 | } 12 | 13 | type OptionalParams = { 14 | baseColor?: ReturnType 15 | settings?: PaletteSettings 16 | } 17 | 18 | /** 19 | * Generate colors based on color theory 20 | * @param baseColor Initial color to generate the rest from 21 | * @param combination The type of color theory combination to use 22 | * @param settings The settings for the palette 23 | * @returns Generated colors & settings 24 | */ 25 | export function generateColors(combination: Combination, optional: OptionalParams = { baseColor: colorsea.random() }) { 26 | let { baseColor, settings } = optional; 27 | // Never called because baseColor is set by default in parameters 28 | if(!baseColor) baseColor = colorsea.random(); 29 | let colors: string[] = []; 30 | 31 | switch(combination) { 32 | case Combination.Complimentary: 33 | colors = [baseColor.hex(), baseColor.complement().hex()]; 34 | if(settings) settings.aliases = ['Base', 'Complimentary Color']; 35 | break; 36 | case Combination.Monochromatic: 37 | const lightest = baseColor.lighten(20); 38 | const lighter = baseColor.lighten(10); 39 | const darker = baseColor.darken(10); 40 | const darkest = baseColor.darken(20); 41 | colors = [lightest.hex(), lighter.hex(), baseColor.hex(), darker.hex(), darkest.hex()]; 42 | if(settings) settings.aliases = ['Lightest', 'Lighter', 'Base', 'Darker', 'Darkest']; 43 | break; 44 | case Combination.Analogous: 45 | const east = baseColor.adjustHue(-25); 46 | const west = baseColor.adjustHue(25); 47 | colors = [east.hex(), baseColor.hex(), west.hex()]; 48 | if(settings) settings.aliases = ['Analogous East', 'Base', 'Analogous West']; 49 | break; 50 | case Combination.Triadic: 51 | const hex120 = baseColor.spin(120); 52 | const hex240 = baseColor.spin(240); 53 | colors = [baseColor.hex(), hex120.hex(), hex240.hex()]; 54 | if(settings) settings.aliases = ['Triadic First', 'Base', 'Triadic Third']; 55 | break; 56 | case Combination.Tetradic: 57 | const hex90 = baseColor.spin(90); 58 | const hex180 = baseColor.spin(180); 59 | const hex270 = baseColor.spin(270); 60 | colors = [baseColor.hex(), hex90.hex(), hex180.hex(), hex270.hex()]; 61 | if(settings) settings.aliases = ['Base', 'Tetradic Second', 'Tetradic Third', 'Tetradic Fourth']; 62 | break; 63 | case Combination.Random: 64 | // Clamp to a minimum value of 2 65 | const randomNumber = Math.max(Math.round(Math.random() * 10), 2); 66 | let randomColors: string[] = []; 67 | for(let i = 0; i < randomNumber; i++){ 68 | randomColors.push(colorsea.random().hex()); 69 | } 70 | colors = randomColors; 71 | if(settings) settings.aliases = []; 72 | break; 73 | } 74 | 75 | return { colors, settings }; 76 | } -------------------------------------------------------------------------------- /src/utils/editorUtils.ts: -------------------------------------------------------------------------------- 1 | import { Editor } from "obsidian" 2 | 3 | type Options = { 4 | line?: number, 5 | offset?: number 6 | } 7 | 8 | export default class EditorUtils { 9 | editor: Editor 10 | 11 | constructor(editor: Editor) { 12 | this.editor = editor; 13 | } 14 | 15 | /** 16 | * Replaces selection or text at the cursor 17 | * @param content The content to be inserted 18 | * @param insertAfter Inserts the content after the current line 19 | */ 20 | public insertContent(content: string, insertAfter = false): void { 21 | this.setCursorPostCallback((line) => { 22 | this.editor.somethingSelected() ? 23 | this.editor.replaceSelection(content) 24 | : 25 | insertAfter ? 26 | this.insertLine(content, 'after') 27 | : 28 | this.replaceLine(content, line); 29 | }); 30 | } 31 | 32 | /** 33 | * Sets the cursor to a position after callback editor changes 34 | * @param callback Changes to perform to the editor 35 | * @param options.line Defaults to the current cursor line 36 | * @param options.offset The number of lines to offset (calculates during function unless user specified) 37 | */ 38 | public setCursorPostCallback(callback: ( line: number ) => void, { line = this.editor.getCursor().line, offset }: Options = {}) { 39 | // Number of lines before adding content 40 | const preLinesCount = this.editor.lineCount(); 41 | 42 | callback(line); 43 | 44 | // Number of lines after adding content 45 | const postLinesCount = this.editor.lineCount() - preLinesCount; 46 | 47 | // Set offset to postLinesCount if not specified 48 | offset = offset || postLinesCount; 49 | 50 | this.editor.setCursor({ ch: 0, line: line + offset }); 51 | } 52 | 53 | /** 54 | * 55 | * @param options.line The line to retrieve the last character index from 56 | * @param options.offset The offset used from the line (for example, 1 could be used to get the last character index on the line below the cursor) 57 | * @returns The last character's index on the line 58 | */ 59 | public getLastCh({ line = this.editor.getCursor().line, offset = 0 }: Options = {}): number { 60 | return this.editor.getLine(line + offset).length; 61 | } 62 | 63 | /** 64 | * Replaces a single line 65 | * @param content The content to replace the line with 66 | * @param line The line to replace 67 | */ 68 | public replaceLine(content: string, line: number) { 69 | const lineContent = this.editor.getLine(line); 70 | this.editor.replaceRange(content, { line: line, ch: 0 }, { line: line, ch: lineContent.length}); 71 | } 72 | 73 | /** 74 | * Inserts content into editor before or after the line 75 | * @param content The content to insert 76 | * @param location Where to insert the content, before or after the line 77 | * @param options.line Defaults to cursor line 78 | * @param options.ch Defaults to 0 79 | */ 80 | public insertLine(content: string, location: 'before' | 'after' = 'before', { line = this.editor.getCursor().line, ch = 0 } = {}) { 81 | if(location === 'before') { 82 | this.editor.replaceRange(content, { line, ch }); 83 | } 84 | if(location === 'after') { 85 | // If last line, add a newline before adding content 86 | this.editor.replaceRange( 87 | this.editor.lastLine() === line ? '\n' + content : content + '\n', 88 | { line: line + 1, ch } 89 | ) 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /src/utils/imageUtils.ts: -------------------------------------------------------------------------------- 1 | import quantize, { RgbPixel } from "quantize"; 2 | import { Canvas } from "./canvasUtils"; 3 | 4 | export default class CanvasImage extends Canvas { 5 | image: HTMLImageElement; 6 | private loading: boolean; 7 | width: number; 8 | height: number; 9 | 10 | constructor(container: HTMLElement, imageURL?: string, smoothing = false) { 11 | super(container); 12 | this.canvas.addClass('image'); 13 | this.loading = true; 14 | this.image = new Image(); 15 | // Allows CORS requests for images from different domains 16 | this.image.crossOrigin = 'anonymous'; 17 | if(imageURL) this.image.src = imageURL; 18 | this.image.addEventListener('load', (e) => this.loading = false); 19 | this.image.addEventListener('error', (e) => { 20 | throw new Error('The URL provided could not be loaded.'); 21 | }) 22 | this.context.imageSmoothingEnabled = smoothing; 23 | } 24 | 25 | /** 26 | * Updates & loads the canvas image. 27 | * Attempts to preserve aspect ratio based on width. 28 | * @param width The canvas width 29 | * @param height The canvas height 30 | */ 31 | public update(imageURL: string, width: number, height: number) { 32 | // Set URL 33 | this.image.src = imageURL; 34 | 35 | // Wait for image to load before calculating dimensions & drawing image to canvas 36 | this.waitForLoading().then(() => { 37 | // Calculate the new height based on the aspect ratio 38 | const aspectRatio = this.image.naturalHeight / this.image.naturalWidth; 39 | 40 | let newWidth = width; 41 | let newHeight = newWidth * aspectRatio; 42 | 43 | // Ensure the new height fits within the canvas height 44 | if (newHeight > height) { 45 | // Adjust width if height exceeds canvas height 46 | newWidth = height / aspectRatio; 47 | newHeight = height; 48 | } 49 | 50 | this.width = this.canvas.width = newWidth; 51 | this.height = this.canvas.height = newHeight; 52 | this.context.drawImage(this.image, 0, 0, newWidth, newHeight); 53 | }) 54 | } 55 | 56 | /** 57 | * Gets the most frequent colors in an image 58 | * @param numColors Number of colors to return 59 | * @param quality Artificially reduce number of pixels (higher = less accurate but faster) 60 | * @returns Most frequent colors 61 | */ 62 | public async getPalette(numColors = 7, quality = 10) { 63 | /* 64 | Quantize has an issue with number of colors which has been addressed here https://github.com/olivierlesnicki/quantize/issues/9 65 | `nColors` is a simple fix for this. 66 | */ 67 | const nColors = numColors <= 7 ? numColors : numColors + 1; 68 | 69 | // Wait for image to load 70 | await this.waitForLoading(); 71 | 72 | // Get an array of pixels 73 | const pixels = await this.createPixelArray(quality); 74 | if(!pixels) return null; 75 | 76 | // Reduce pixels array to a small number of the most common colors 77 | const colorMap = quantize(pixels, nColors); 78 | 79 | // Return palette 80 | return colorMap ? colorMap.palette() : []; 81 | } 82 | 83 | /** 84 | * Creates an array of pixels from the image 85 | * Inspired by colorthief 86 | * @param quality Artificially reduce number of pixels (higher = less accurate but faster) 87 | * @returns 88 | */ 89 | public async createPixelArray(quality: number) { 90 | await this.waitForLoading(); 91 | const pixelArray: number[][] = []; 92 | const imageData = (await this.getImageData())?.data; 93 | if(!imageData) return null; 94 | // Get number of pixels in image 95 | const pixelCount = this.height * this.width; 96 | 97 | for (let i = 0; i < pixelCount; i += quality) { 98 | // Offset to correct starting position of each pixel 99 | const offset = i * 4; 100 | const [r, g, b, a] = [imageData[offset + 0], imageData[offset + 1], imageData[offset + 2], imageData[offset + 3]]; 101 | 102 | // If pixel is mostly opaque and not white 103 | if (typeof a === 'undefined' || a >= 125) { 104 | if (!(r > 250 && g > 250 && b > 250)) { 105 | pixelArray.push([r, g, b]); 106 | } 107 | } 108 | } 109 | return pixelArray as RgbPixel[]; 110 | } 111 | 112 | /** 113 | * Gets the image data from the canvas 114 | */ 115 | public async getImageData(x = 0, y = 0) { 116 | try { 117 | await this.waitForLoading(); 118 | return this.context.getImageData(x, y, this.width, this.height); 119 | } 120 | catch(e) { 121 | throw new Error('Failed to get image data.'); 122 | } 123 | } 124 | 125 | /** 126 | * Waits for loading variable to equal true 127 | */ 128 | private waitForLoading = () => new Promise(resolve => { 129 | const checkLoading = setInterval(() => { 130 | if (!this.loading) { 131 | clearInterval(checkLoading); 132 | resolve(true); 133 | } 134 | }, 100); 135 | }) 136 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { Editor, MarkdownPostProcessorContext, Notice, Plugin } from 'obsidian' 2 | import { EditorModal } from 'components/EditorModal'; 3 | import { GenerateModal } from 'components/GenerateModal'; 4 | import { ColorPaletteSettings, defaultSettings, SettingsTab } from 'settings'; 5 | import { PaletteMRC } from 'components/PaletteMRC'; 6 | import { createPaletteBlock } from 'utils/basicUtils'; 7 | 8 | export const urlRegex = /(?:https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}(?:\.[a-zA-Z0-9]{2,})(?:\.[a-zA-Z0-9]{2,})?\/(?:palette\/)?([a-zA-Z0-9-]{2,})/ 9 | 10 | export default class ColorPalette extends Plugin { 11 | settings: ColorPaletteSettings; 12 | palettes?: PaletteMRC[]; 13 | 14 | async onload() { 15 | this.palettes = []; 16 | await this.loadSettings(); 17 | 18 | /** 19 | * Changes when text length is extended or shortened. 20 | * DOES NOT change when text length remains the same. 21 | * This means simply swapping characters, but having the same length won't update this function. 22 | */ 23 | this.registerMarkdownCodeBlockProcessor( 24 | 'palette', 25 | async (source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) => { 26 | ctx.addChild(new PaletteMRC(this, el, source.trim(), ctx)); 27 | } 28 | ) 29 | 30 | this.addCommand({ 31 | id: 'create', 32 | name: 'Create', 33 | editorCallback: (editor: Editor) => { 34 | new EditorModal(this.app, this.settings, (colors, settings) => { 35 | try { 36 | const result = createPaletteBlock({colors, settings}); 37 | const cursor = editor.getCursor(); 38 | editor.transaction({ 39 | changes: [{ from: cursor, text: result }] 40 | }) 41 | editor.setCursor({ 42 | line: cursor.line + result.split('\n').length, 43 | ch: 0 44 | }) 45 | new Notice(`Added ${result}`); 46 | } 47 | catch (error) { 48 | new Notice(error); 49 | } 50 | }) 51 | .open(); 52 | } 53 | }) 54 | 55 | this.addCommand({ 56 | id: 'convert-link', 57 | name: 'Convert link', 58 | editorCallback: async (editor: Editor) => { 59 | try { 60 | let link = ''; 61 | const editorSelection = editor.getSelection(); 62 | const clipboardText = await navigator.clipboard.readText(); 63 | 64 | // Check if selection text matches regex 65 | if(editorSelection.match(`^${urlRegex.source}$`)) link = editorSelection; 66 | // Check if clipboard text matches regex 67 | else if(clipboardText.match(`^${urlRegex.source}$`)) link = clipboardText; 68 | // Throw error if selection & clipboard don't match URL regex 69 | else throw new Error('Failed to convert link. Please select or copy a link, then try again.'); 70 | 71 | const codeBlock = createPaletteBlock(link); 72 | const cursor = editor.getCursor(); 73 | editor.replaceSelection(codeBlock); 74 | editor.setCursor({ 75 | line: cursor.line + codeBlock.split('\n').length, 76 | ch: 0 77 | }); 78 | new Notice(`Converted ${editorSelection || clipboardText}`); 79 | } 80 | catch (error) { 81 | new Notice(error); 82 | } 83 | } 84 | }) 85 | 86 | this.addCommand({ 87 | id: 'convert-codeblock-link-to-hex', 88 | name: 'Convert codeblock link to hex', 89 | editorCallback: (editor: Editor) => { 90 | try { 91 | const codeBlock = editor.getSelection(); 92 | const multiReg = RegExp(/(?:\`{3}palette)\n(?.*)(?:\n(?.+))?\n\`{3}/, 'g'); 93 | const content = [...codeBlock.matchAll(multiReg)]?.[0]?.slice(1); 94 | const url = content?.[0]; 95 | if(!url) throw new Error('Selected text is not a codeblock with a link.'); 96 | let colors: string[] = []; 97 | // Check if link & contains dashes (coolor url) 98 | url.match(urlRegex) && url.includes('-') ? 99 | colors = url.substring(url.lastIndexOf('/') + 1).split('-').map(i => '#' + i) 100 | : 101 | // Check if link (colorhunt) 102 | url.match(urlRegex) ? 103 | colors = url.substring(url.lastIndexOf('/') + 1).match(/.{1,6}/g)?.map(i => '#' + i) || ['Invalid Palette'] 104 | : 105 | colors = ['Invalid Palette'] 106 | 107 | if(colors[0] === 'Invalid Palette') throw new Error('Selected codeblock can not be converted to hex.'); 108 | 109 | let newBlock; 110 | 111 | // Check if settings were specified 112 | if(!content?.[1]) { 113 | // Create palette without settings 114 | newBlock = createPaletteBlock({ colors }); 115 | } 116 | else { 117 | const settings = JSON.parse(content[1]); 118 | // Create palette with settings 119 | createPaletteBlock({ colors, settings }); 120 | } 121 | 122 | if(newBlock) { 123 | editor.replaceSelection(newBlock); 124 | new Notice(`Converted codeblock link to hex`); 125 | } 126 | else throw new Error('Selected codeblock can not be converted to hex.'); 127 | } 128 | catch (error) { 129 | new Notice(error); 130 | } 131 | } 132 | }) 133 | 134 | this.addCommand({ 135 | id: 'generate-random-palette', 136 | name: 'Generate random palette', 137 | editorCallback: (editor: Editor) => { 138 | new GenerateModal(this.app, editor, this.settings).open(); 139 | } 140 | }) 141 | 142 | this.addSettingTab(new SettingsTab(this.app, this)); 143 | } 144 | 145 | async loadSettings() { 146 | this.settings = Object.assign({}, defaultSettings, await this.loadData()); 147 | } 148 | 149 | async saveSettings() { 150 | await this.saveData(this.settings); 151 | } 152 | } -------------------------------------------------------------------------------- /src/utils/basicUtils.ts: -------------------------------------------------------------------------------- 1 | import colorsea from "colorsea"; 2 | import { PaletteSettings } from "components/Palette"; 3 | import { Notice } from "obsidian"; 4 | import { ColorPaletteSettings, CopyFormat, defaultSettings } from "settings"; 5 | 6 | /** 7 | * Get settings without their default values 8 | */ 9 | export function getModifiedSettings (settings: PaletteSettings) { 10 | let newSettings: Partial = {}; 11 | 12 | for(const [key, value] of Object.entries(settings)) { 13 | const defaultVal = defaultSettings[key as keyof ColorPaletteSettings]; 14 | 15 | // Check if setting is a key in defaultSettings 16 | if(key in defaultSettings) { 17 | // Check if setting is equal to default & keep setting if not equal 18 | if(value !== defaultVal) newSettings = { ...newSettings, [key]: value}; 19 | } 20 | // Add all other settings not defined in defaults 21 | else { 22 | // Break if empty array 23 | if(value instanceof Array && value.length === 0) break; 24 | // Add setting 25 | else newSettings = { ...newSettings, [key]: value }; 26 | } 27 | } 28 | 29 | // Return null if newSettings is empty 30 | return Object.keys(newSettings).length !== 0 ? newSettings : undefined; 31 | } 32 | 33 | /** 34 | * Checks if all settings are set to their default values 35 | */ 36 | export function areSettingsDefault (settings: PaletteSettings | ColorPaletteSettings) { 37 | for(const [key, value] of Object.entries(settings)) { 38 | // Ignore settings that don't have a default counterpart 39 | if(!(key in defaultSettings)) return true; 40 | // Check if any settings are not default 41 | if(value !== defaultSettings[key as keyof ColorPaletteSettings]) { 42 | return false; 43 | } 44 | } 45 | return true; 46 | } 47 | 48 | /** 49 | * Gets the modified settings as a string 50 | */ 51 | export function getModifiedSettingsAsString (settings: PaletteSettings) { 52 | const moddedSettings = getModifiedSettings(settings); 53 | if(moddedSettings) return JSON.stringify(moddedSettings); 54 | } 55 | 56 | export function convertStringSettings(settings: PaletteSettings) { 57 | return JSON.parse( 58 | `{ 59 | "height": ${settings.height}, 60 | "direction": "${settings.direction}", 61 | "gradient": ${settings.gradient}, 62 | "hover": ${settings.hover}, 63 | "hideText": ${settings.hideText}, 64 | "override": ${settings.override}, 65 | "aliases": ${JSON.stringify(settings.aliases)} 66 | }` 67 | ) 68 | } 69 | 70 | /** 71 | * Parse input url & extract colors 72 | * @param url URL from color input 73 | * @returns Array of colors 74 | */ 75 | export function parseUrl(url: string) { 76 | // Check if url colors contain dashes in-between 77 | if(url.includes('-')) { 78 | // Replace dashes with hexes (colorhunt) 79 | return url.substring(url.lastIndexOf('/') + 1).split('-').map(i => '#' + i); 80 | } 81 | // Add hex between URL path colors (coolors) 82 | else return url.substring(url.lastIndexOf('/') + 1).match(/.{1,6}/g)?.map(i => '#' + i) || []; 83 | } 84 | 85 | /** 86 | * Converts ColorPalette plugin settings to Palette settings 87 | */ 88 | export function pluginToPaletteSettings(pluginSettings: ColorPaletteSettings): PaletteSettings { 89 | return { 90 | height: pluginSettings.height, 91 | width: pluginSettings.width, 92 | direction: pluginSettings.direction, 93 | gradient: pluginSettings.gradient, 94 | hover: pluginSettings.hover, 95 | hideText: pluginSettings.hideText, 96 | override: pluginSettings.override, 97 | aliases: [] 98 | }; 99 | } 100 | 101 | /** 102 | * Creates a codeblock palette 103 | * @param input Either palette input or colors & settings object 104 | * @returns palette block string 105 | */ 106 | export function createPaletteBlock(input: { colors: string[],settings?: Partial } | string): string { 107 | if(typeof input === 'string') return `\`\`\`palette\n${input}\n\`\`\`\n`; 108 | else return input.settings ? `\`\`\`palette\n${toNString(input.colors)}\n${JSON.stringify(input.settings)}\n\`\`\`\n` : `\`\`\`palette\n${toNString(input.colors)}\n\`\`\`\n`; 109 | } 110 | 111 | /** 112 | * Gets the appropriate foreground contrast color 113 | */ 114 | export function getForegroundColor(color: ReturnType): string { 115 | return (color.rgb()[0]*0.299 + color.rgb()[1]*0.587 + color.rgb()[2]*0.114) > 186 ? '#000000' : '#ffffff'; 116 | } 117 | 118 | /** 119 | * Converts string array to newline separated string 120 | */ 121 | export function toNString(array: string[]) { 122 | let result = ''; 123 | for (const string of array) { 124 | result += string + '\n'; 125 | } 126 | return result.trim(); 127 | } 128 | 129 | export async function copyToClipboard(text: string, copyFormat?: CopyFormat) { 130 | let copiedText = text; 131 | 132 | // Copy only color value if CopyFormat is set to value & when not a codeblock 133 | if(copyFormat === CopyFormat.Value && !text.includes('`')) { 134 | if(copiedText.includes('#')) copiedText = copiedText.split('#')[1]; 135 | else if(copiedText.includes('(')) copiedText = copiedText.split('(')[1].split(')')[0]; 136 | } 137 | new Notice(`Copied ${copiedText}`); 138 | await navigator.clipboard.writeText(copiedText); 139 | } -------------------------------------------------------------------------------- /src/utils/canvasUtils.ts: -------------------------------------------------------------------------------- 1 | import { Direction } from "settings"; 2 | import colorsea from "colorsea"; 3 | import validateColor from "validate-color"; 4 | import { EventEmitter } from "./EventEmitter"; 5 | 6 | type EventMap = { 7 | click: [hex: string], 8 | } 9 | 10 | export class Canvas { 11 | container: HTMLElement; 12 | canvas: HTMLCanvasElement; 13 | tooltip: HTMLElement; 14 | tooltipText: HTMLSpanElement; 15 | context: CanvasRenderingContext2D; 16 | emitter: EventEmitter; 17 | 18 | constructor(container: HTMLElement) { 19 | this.container = container; 20 | this.container.addClass('palette-canvas'); 21 | this.canvas = container.appendChild(document.createElement('canvas')); 22 | this.tooltip = container.appendChild(document.createElement('section')); 23 | // tooltip is an Obsidian class 24 | this.tooltip.addClasses(['tooltip', 'palette-tooltip']); 25 | this.tooltipText = this.tooltip.appendChild(document.createElement('span')); 26 | // Non-null asserted context 27 | this.context = this.canvas.getContext('2d', {willReadFrequently: true, alpha: true})!; 28 | this.emitter = new EventEmitter(); 29 | 30 | // Check if touch device & add the event listener to the element to track position for the tooltip 31 | if(!this.isTouchEnabled()) this.canvas.addEventListener("mousemove", (e) => this.setTooltipPosition(e.clientX, e.clientY)); 32 | else this.canvas.addEventListener("touchmove", (e) => this.setTooltipPosition(e.touches[0].clientX, e.touches[0].clientY)); 33 | 34 | this.canvas.addEventListener('click', (e) => this.emitter.emit('click', this.getCanvasHex(e.clientX, e.clientY))); 35 | } 36 | 37 | /** 38 | * Creates a new gradient canvas 39 | * @param colors 40 | * @param width 41 | * @param height 42 | * @param direction 43 | * @param onClick canvas click callback 44 | */ 45 | public createGradient(colors: string[], width: number, height: number, direction: Direction) { 46 | this.canvas.width = width; 47 | this.canvas.height = height; 48 | 49 | let gradient = direction === Direction.Column ? this.context.createLinearGradient(0, 0, width, 0) : this.context.createLinearGradient(0, 0, 0, height); 50 | 51 | let colorStops: string[] = []; 52 | for(const[i, color] of colors.entries()){ 53 | // Skip non-colors, even with override enabled. This prevents errors, especially dealing with css-variables which cannot be parsed at run-time. 54 | if(validateColor(color)) { 55 | gradient.addColorStop(i / (colors.length - 1), color); 56 | colorStops.push(color); 57 | } 58 | } 59 | 60 | if(colorStops.length <= 1) throw new Error('There are not enough valid color stops to create the gradient.'); 61 | 62 | this.context.fillStyle = gradient || '#000'; 63 | this.context.fillRect(0, 0, width, height); 64 | 65 | this.canvas.toggleClass('gradient', true); 66 | this.canvas.style.setProperty('--palette-column-flex-basis', (height / colors.length / 2).toString() + 'px'); 67 | } 68 | 69 | // Retrieves the hex from the mouse position 70 | public getCanvasHex(clientX: number, clientY: number) { 71 | const canvasBounds = this.canvas.getBoundingClientRect(); 72 | let x = clientX - canvasBounds.left; 73 | let y = clientY - canvasBounds.top; 74 | let [r, g, b, a] = this.context.getImageData(x, y, 1, 1).data; 75 | // Convert alpha from 0-255 to 0-1 76 | const alpha = Math.round((a/255) * 100); 77 | // Hide alpha value if not an alpha color 78 | let hex = alpha !== 255 ? colorsea([r, g, b, alpha]).hex() : colorsea([r, g, b]).hex(); 79 | return hex; 80 | } 81 | 82 | /** 83 | * Sets the tooltip position based on current cursor or touch position 84 | */ 85 | public setTooltipPosition(clientX: number, clientY: number) { 86 | // Canvas bounds 87 | const rect = this.canvas.getBoundingClientRect(); 88 | 89 | // Get tooltip bounds 90 | let tooltipWidth = this.tooltip.offsetWidth; 91 | let tooltipHeight = this.tooltip.offsetHeight; 92 | 93 | // Set tooltip position left or right side of mouse based on whether cursor is halfway 94 | let leftPosition = clientX - rect.left > rect.width / 2 ? (clientX - rect.left - 56) : (clientX - rect.left + 64); 95 | let halfTooltipWidth = tooltipWidth / 2; 96 | // Clamp to left edge 97 | if (leftPosition < 0 + halfTooltipWidth) leftPosition = 0 + halfTooltipWidth; 98 | else if (leftPosition + tooltipWidth > rect.width + halfTooltipWidth) leftPosition = rect.width - tooltipWidth + halfTooltipWidth; 99 | this.tooltip.style.left = leftPosition + "px"; 100 | 101 | // Get cursor position & align tooltip centered to cursor (1/4 tooltip height) 102 | let topPosition = clientY - rect.top - (tooltipHeight / 4); 103 | // Clamp to top edge 104 | if (topPosition < 0) topPosition = 0; 105 | // Clamp to bottom edge 106 | else if (topPosition + tooltipHeight > rect.height) topPosition = rect.height - tooltipHeight; 107 | this.tooltip.style.top = topPosition + "px"; 108 | 109 | const hex = this.getCanvasHex(clientX, clientY); 110 | this.tooltipText.setText(hex.toUpperCase()); 111 | } 112 | 113 | /** 114 | * Checks for touch device 115 | */ 116 | public isTouchEnabled() { 117 | return ( 'ontouchstart' in window ) || ( navigator.maxTouchPoints > 0 ); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/utils/dragDropUtils.ts: -------------------------------------------------------------------------------- 1 | interface Result { 2 | beforeElement: Element | null 3 | insertedElement: Element | null 4 | afterElement: Element | null 5 | order: Element[] 6 | } 7 | 8 | export class DragDrop { 9 | dropzones: Element[]; 10 | draggables: Element[]; 11 | result: Result; 12 | onDrop: (e: DragEvent, res: Result) => void; 13 | 14 | constructor(dropzones: Element[], draggables: Element[], onDrop: (e: DragEvent, res: Result) => void) { 15 | this.dropzones = dropzones; 16 | this.draggables = draggables; 17 | this.result = { beforeElement: null, insertedElement: null, afterElement: null, order: this.draggables }; 18 | this.onDrop = onDrop; 19 | 20 | this.load(); 21 | } 22 | 23 | private dragStart(draggable: Element, e: DragEvent) { 24 | draggable.toggleClass('is-dragging', true); 25 | } 26 | 27 | private dragOver(dropzone: Element, e: DragEvent) { 28 | if(e.dataTransfer) { 29 | const hasElement = Array.from(e.dataTransfer.items).some((item) => { 30 | return item.kind !== 'element'; 31 | }); 32 | // Return early if element being dragged is not an element 33 | if(hasElement) return; 34 | } 35 | 36 | e.preventDefault(); 37 | this.result.beforeElement = this.getDragBeforeElement(e.clientX); 38 | this.result.insertedElement = this.getDraggingElement(); 39 | this.result.afterElement = this.getDragAfterElement(e.clientX); 40 | 41 | const insertedIndex = this.draggables.indexOf(this.result.insertedElement); 42 | 43 | // If at the end of draggables 44 | if (this.result.afterElement === null) { 45 | // Append element 46 | dropzone.appendChild(this.result.insertedElement); 47 | // Remove element from order 48 | this.result.order.splice(insertedIndex, 1); 49 | // Add to end of order 50 | this.result.order.push(this.result.insertedElement); 51 | } 52 | else { 53 | // Place element between 54 | dropzone.insertBefore(this.result.insertedElement, this.result.afterElement); 55 | // Remove element from order 56 | this.result.order.splice(insertedIndex, 1); 57 | // Get the after index, post element removal 58 | const afterIndex = this.draggables.indexOf(this.result.afterElement); 59 | // Insert the element before the after index 60 | this.result.order.splice(afterIndex, 0, this.result.insertedElement); 61 | } 62 | } 63 | 64 | private dragEnd(draggable: Element, e: DragEvent) { 65 | draggable.toggleClass('is-dragging', false); 66 | this.onDrop(e, this.result); 67 | this.result = { beforeElement: null, insertedElement: null, afterElement: null, order: this.draggables }; 68 | } 69 | 70 | public load() { 71 | for(let draggable of this.draggables) { 72 | // Important, so that all types of elements can be dragged, including divs & spans 73 | draggable.setAttribute('draggable', "true"); 74 | 75 | draggable.addEventListener("dragstart", (e: DragEvent) => this.dragStart(draggable, e)); 76 | draggable.addEventListener("dragend", (e: DragEvent) => this.dragEnd(draggable, e)); 77 | } 78 | 79 | for(let dropzone of this.dropzones) { 80 | dropzone.addEventListener("dragover", (e: DragEvent) => this.dragOver(dropzone, e)); 81 | } 82 | } 83 | 84 | public unload() { 85 | for(let draggable of this.draggables) { 86 | draggable.removeEventListener('dragstart', (e: DragEvent) => this.dragStart(draggable, e)); 87 | draggable.removeEventListener('dragend', (e: DragEvent) => this.dragEnd(draggable, e)); 88 | } 89 | 90 | for(let dropzone of this.dropzones) { 91 | dropzone.removeEventListener('dragover', (e: DragEvent) => this.dragOver(dropzone, e)); 92 | } 93 | } 94 | 95 | /** 96 | * @returns The element which is being dragged 97 | */ 98 | public getDraggingElement() { 99 | return this.draggables.filter((draggable) => draggable.hasClass('is-dragging'))[0]; 100 | } 101 | 102 | /** 103 | * @returns All draggable elements not being dragged 104 | */ 105 | public getDraggableElements() { 106 | return this.draggables.filter((draggable) => !draggable.hasClass('is-dragging')); 107 | } 108 | 109 | /** 110 | * Gets the closest element before the dragged element 111 | */ 112 | private getDragBeforeElement(x: number) { 113 | return this.getDraggableElements().reduce((closest, child) => { 114 | const rect = child.getBoundingClientRect(); 115 | const leftPosition = x - rect.left; 116 | const halfChildWidth = rect.width / 2; 117 | 118 | const offset = leftPosition - halfChildWidth; 119 | 120 | // Return the closest element to the right of the cursor 121 | if (offset > 0 && offset < closest.offset) return { offset, element: child } 122 | else return closest; 123 | }, 124 | // Initial closest value 125 | { offset: Number.POSITIVE_INFINITY, element: null } 126 | ) 127 | .element; 128 | } 129 | 130 | /** 131 | * Gets the closest element after the dragged element 132 | */ 133 | private getDragAfterElement(x: number) { 134 | return this.getDraggableElements().reduce((closest, child) => { 135 | const rect = child.getBoundingClientRect(); 136 | const leftPosition = x - rect.left; 137 | const halfChildWidth = rect.width / 2; 138 | 139 | const offset = leftPosition - halfChildWidth; 140 | 141 | // Return the closest element to the left of the cursor 142 | if (offset < 0 && offset > closest.offset) return { offset, element: child } 143 | else return closest; 144 | }, 145 | // Initial closest value 146 | { offset: Number.NEGATIVE_INFINITY, element: null } 147 | ) 148 | .element; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/components/PaletteMenu.ts: -------------------------------------------------------------------------------- 1 | import { EditorModal } from "./EditorModal"; 2 | import { ReorderModal } from "./ReorderModal"; 3 | import colorsea from "colorsea"; 4 | import { App, MarkdownPostProcessorContext, Menu, Notice } from "obsidian"; 5 | import { Palette, PaletteSettings } from "./Palette"; 6 | import { Direction } from "settings"; 7 | import { copyToClipboard, createPaletteBlock, getModifiedSettings } from "utils/basicUtils"; 8 | 9 | export class PaletteMenu extends Menu { 10 | app: App; 11 | context: MarkdownPostProcessorContext; 12 | palette: Palette; 13 | private onChange: (colors: string[] | undefined, settings: Partial | undefined) => void; 14 | 15 | constructor(app: App, context: MarkdownPostProcessorContext, palette: Palette, onChange: (colors: string[] | undefined, settings: Partial | undefined) => void) { 16 | super(); 17 | this.app = app; 18 | this.context = context; 19 | this.palette = palette; 20 | this.onChange = onChange; 21 | 22 | this.createMenu(); 23 | } 24 | 25 | private createMenu() { 26 | this.addItem((item) => { 27 | item 28 | .setTitle("Reorder") 29 | .setIcon("arrow-left-right") 30 | .onClick(() => { 31 | const modal = new ReorderModal(this.app, this.palette, (colors, settings) => this.onChange(colors, settings)); 32 | modal.open(); 33 | modal.setInstructions([ 34 | { command: '↑↓', purpose: 'to navigate' }, 35 | { command: '↵', purpose: 'to use'}, 36 | { command: 'esc', purpose: 'to dismiss'}, 37 | ]); 38 | modal.setPlaceholder('Choose a space to reorder palette'); 39 | }) 40 | }) 41 | 42 | this.addItem((item) => { 43 | item 44 | .setTitle("Edit Mode") 45 | .setIcon('palette') 46 | .onClick(async () => { 47 | new EditorModal(this.app, this.palette.pluginSettings, (colors, settings) => { 48 | try { 49 | const paletteSection = this.context.getSectionInfo(this.palette.containerEl); 50 | if(paletteSection) { 51 | this.onChange(colors, settings); 52 | } 53 | } 54 | catch (error) { 55 | new Notice(error); 56 | } 57 | }, this.palette) 58 | .open(); 59 | }) 60 | }); 61 | 62 | // Only show toggle edit mode option when palette is not a gradient or columns 63 | if(!this.palette.settings.gradient && this.palette.settings.direction !== Direction.Row) { 64 | this.addItem((item) => { 65 | item 66 | .setTitle("Quick Edit") 67 | .setIcon('brush') 68 | .setChecked(this.palette.getEditMode()) 69 | .onClick(async () => { 70 | // Toggle palette edit mode 71 | this.palette.setEditMode(!this.palette.getEditMode()); 72 | this.palette.reload(); 73 | }) 74 | }); 75 | } 76 | 77 | this.addSeparator(); 78 | 79 | this.addItem((item) => { 80 | item 81 | .setTitle("Convert to RGB") 82 | .setIcon("droplets") 83 | .onClick(() => { 84 | const colors = this.palette.colors.map((color) => { 85 | const rgbColor = colorsea(color).rgb(); 86 | return `rgb(${rgbColor[0]}, ${rgbColor[1]}, ${rgbColor[2]})` 87 | }) 88 | this.onChange(colors, getModifiedSettings(this.palette.settings)); 89 | }) 90 | }); 91 | 92 | this.addItem((item) => { 93 | item 94 | .setTitle("Convert to HSL") 95 | .setIcon("droplets") 96 | .onClick(() => { 97 | const colors = this.palette.colors.map((color) => { 98 | const hslColor = colorsea(color).hsl(); 99 | return `hsl(${hslColor[0]} ${hslColor[1]}% ${hslColor[2]}%)` 100 | }) 101 | this.onChange(colors, getModifiedSettings(this.palette.settings)); 102 | }) 103 | }); 104 | 105 | this.addItem((item) => { 106 | item 107 | .setTitle("Convert to HEX") 108 | .setIcon("droplets") 109 | .onClick(() => { 110 | const colors = this.palette.colors.map((color) => { 111 | return colorsea(color).hex(2); 112 | }) 113 | this.onChange(colors, getModifiedSettings(this.palette.settings)); 114 | }) 115 | }); 116 | 117 | this.addSeparator(); 118 | 119 | const input = createPaletteBlock({ colors: this.palette.colors, settings: getModifiedSettings(this.palette.settings) }); 120 | 121 | this.addItem((item) => { 122 | item 123 | .setTitle("Cut") 124 | .setIcon("scissors") 125 | .onClick(async () => { 126 | // Copy palette to clipboard 127 | await copyToClipboard(input, this.palette.pluginSettings.copyFormat); 128 | // Remove palette 129 | this.onChange(undefined, undefined); 130 | }) 131 | }); 132 | 133 | this.addItem((item) => { 134 | item 135 | .setTitle("Copy") 136 | .setIcon("copy") 137 | .onClick(async () => { 138 | // Copy palette to clipboard 139 | await copyToClipboard(input, this.palette.pluginSettings.copyFormat); 140 | }) 141 | }); 142 | } 143 | } -------------------------------------------------------------------------------- /src/components/PaletteItem.ts: -------------------------------------------------------------------------------- 1 | import colorsea from "colorsea"; 2 | import { ButtonComponent } from "obsidian"; 3 | import { AliasMode, Direction } from "settings"; 4 | import { getForegroundColor } from "utils/basicUtils"; 5 | import { EventEmitter } from "utils/EventEmitter"; 6 | 7 | type PaletteItemSettings = { 8 | aliasMode: AliasMode, 9 | stabilityWhileEditing: boolean, 10 | height: number, 11 | direction: Direction, 12 | hover: boolean, 13 | hideText: boolean, 14 | alias: string, 15 | editMode: boolean, 16 | colorCount: number, 17 | } 18 | 19 | type EventMap = { 20 | click: [e: MouseEvent]; 21 | trash: [e: MouseEvent]; 22 | alias: [alias: string]; 23 | } 24 | 25 | export class PaletteItem { 26 | container: HTMLDivElement; 27 | color: string; 28 | settings: PaletteItemSettings; 29 | public emitter: EventEmitter 30 | 31 | constructor(container: HTMLElement, color: string, settings: PaletteItemSettings){ 32 | this.container = container.createEl('div'); 33 | this.color = color.trim(); 34 | this.settings = settings; 35 | this.emitter = new EventEmitter; 36 | 37 | this.load(); 38 | } 39 | 40 | private load() { 41 | const csColor = colorsea(this.color); 42 | 43 | // set background color 44 | this.container.style.setProperty('--palette-background-color', this.color); 45 | // set width 46 | this.container.style.setProperty('--palette-column-flex-basis', (this.settings.height / this.settings.colorCount / 2).toString() + 'px'); 47 | 48 | 49 | const incompatibleSettings = this.settings.direction === Direction.Row; 50 | // Create if edit mode is active & if there are incompatibleSettings 51 | if(this.settings.editMode && !incompatibleSettings) { 52 | new EditMode(this.container, this.color, this.settings, (e) => this.emitter.emit('trash', e), (alias) => this.emitter.emit('alias', alias)); 53 | } 54 | else { 55 | // Display hex if alias mode is set to both OR if alias is not set 56 | if(this.settings.aliasMode === AliasMode.Both || this.settings.alias == null || this.settings.alias.trim() === ''){ 57 | let childText = this.container.createEl('span', { text: this.color.toUpperCase() }); 58 | childText.style.setProperty('--palette-color', getForegroundColor(csColor)); 59 | } 60 | 61 | let childAlias = this.container.createEl('span', { text: this.settings.alias }); 62 | childAlias.style.setProperty('--palette-color', getForegroundColor(csColor)); 63 | } 64 | 65 | this.container.addEventListener('click', (e) => this.emitter.emit('click', e)); 66 | } 67 | 68 | /** 69 | * Removes listeners 70 | */ 71 | public unload() { 72 | this.emitter.clear(); 73 | } 74 | } 75 | 76 | class EditMode { 77 | container: HTMLDivElement; 78 | span: HTMLSpanElement; 79 | trash: ButtonComponent; 80 | storedAlias: string; 81 | color: string; 82 | settings: PaletteItemSettings; 83 | private onTrash: (e: MouseEvent) => void; 84 | private onAlias: (alias: string) => void; 85 | 86 | constructor(colorContainer: HTMLDivElement, color: string, settings: PaletteItemSettings, onTrash: (e: MouseEvent) => void, onAlias: (alias: string) => void) { 87 | this.color = color; 88 | this.settings = settings; 89 | this.onTrash = onTrash; 90 | this.onAlias = onAlias; 91 | 92 | const csColor = colorsea(color); 93 | const contrastColor = getForegroundColor(csColor); 94 | 95 | this.container = colorContainer.appendChild(createEl('div')); 96 | this.container.addClass('edit-container'); 97 | this.container.style.setProperty('--edit-background-color', color); 98 | this.container.style.setProperty('--edit-color', contrastColor); 99 | 100 | this.span = this.container.createEl('span'); 101 | this.span.setText(settings.alias || color.toUpperCase()); 102 | this.span.style.setProperty('--edit-font-size', `${this.getAdjustedFontSize(settings.colorCount)}px`); 103 | 104 | this.trash = new ButtonComponent(this.container) 105 | .setIcon('trash-2') 106 | .setTooltip('Remove') 107 | .onClick((e) => this.onTrash(e)) 108 | this.trash.buttonEl.addEventListener('mouseover', (e) => { 109 | this.trash.setCta(); 110 | }) 111 | this.trash.buttonEl.addEventListener('mouseout', (e) => { 112 | this.trash.removeCta(); 113 | }) 114 | 115 | // Focus color & allow for editing alias 116 | this.span.addEventListener('click', (e) => { 117 | e.stopPropagation(); 118 | this.setEditable(true); 119 | this.span.focus(); 120 | }) 121 | // Remove alias on right click 122 | this.span.addEventListener('contextmenu', (e) => { 123 | e.stopPropagation(); 124 | this.span.setText(this.color.toUpperCase()); 125 | this.settings.alias = ''; 126 | this.onAlias(this.settings.alias); 127 | }) 128 | this.span.addEventListener('keypress', (e) => { 129 | if(e.key === 'Enter') { 130 | this.setAlias(); 131 | this.setEditable(false); 132 | } 133 | }) 134 | // Set alias if changed & de-focus 135 | this.span.addEventListener('focusout', (e) => { 136 | this.setAlias(); 137 | this.setEditable(false); 138 | }) 139 | 140 | this.storedAlias = this.span.getText(); 141 | } 142 | 143 | setAlias() { 144 | // Reset span text to original if user left it empty 145 | if(this.span.getText().trim() === '') this.span.setText(this.storedAlias); 146 | // Set alias color if user modified text 147 | else if(this.span.getText() !== this.color) { 148 | this.settings.alias = this.span.getText(); 149 | this.onAlias(this.settings.alias); 150 | } 151 | } 152 | 153 | setEditable(editable: boolean) { 154 | if(editable === true) { 155 | this.storedAlias = this.span.getText(); 156 | this.span.setText(''); 157 | } 158 | this.span.contentEditable = `${editable}`; 159 | this.span.toggleClass('color-span-editable', editable); 160 | } 161 | 162 | /** 163 | * Calculate font size based on number of colors 164 | */ 165 | getAdjustedFontSize(colorsCount: number) { 166 | const minFontSize = 10; 167 | const baseFontSize = 16; 168 | return Math.max(minFontSize, baseFontSize - colorsCount); 169 | } 170 | } -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | /* Palette Container */ 2 | 3 | .palette-container { 4 | cursor: pointer; 5 | position: relative; 6 | } 7 | 8 | .palette-container.palette-scroll { 9 | overflow-x: auto; 10 | } 11 | 12 | /* Palette */ 13 | 14 | .palette { 15 | /* fallback vars */ 16 | --palette-height: 150px; 17 | --palette-width: 100%; 18 | --palette-direction: row; 19 | --not-palette-direction: row; 20 | --palette-background-color: transparent; 21 | --palette-color: #000; 22 | --palette-column-flex-basis: 20px; 23 | --notice-duration: 2.5s; 24 | --palette-corners: 5px; 25 | 26 | display: flex; 27 | flex-direction: var(--palette-direction); 28 | border-radius: var(--palette-corners); 29 | overflow: hidden; 30 | cursor: pointer; 31 | height: var(--palette-height); 32 | width: var(--palette-width); 33 | position: relative; 34 | } 35 | 36 | /* Palette Item */ 37 | 38 | .palette > div { 39 | display: flex; 40 | flex: 1; 41 | flex-basis: 0px; 42 | flex-direction: var(--not-palette-direction); 43 | justify-content: center; 44 | align-items: center; 45 | height: var(--palette-height); 46 | transition: all 0.1s ease-in-out; 47 | background-color: var(--palette-background-color); 48 | gap: 3%; 49 | } 50 | 51 | /* 52 | Canvas 53 | (HTML Canvas, NOT Obsidian.md canvas) 54 | */ 55 | 56 | .palette-canvas { 57 | position: relative; 58 | } 59 | 60 | .palette-canvas > canvas { 61 | transition: all 0.1s ease-in-out; 62 | object-fit: contain; 63 | } 64 | 65 | .palette-canvas > canvas.gradient { 66 | background: linear-gradient(to right, var(--palette-background-color)); 67 | } 68 | 69 | .palette-canvas > image { 70 | width: 100%; 71 | height: 100%; 72 | border-radius: 5px; 73 | } 74 | 75 | .palette-canvas > canvas.image:hover ~ .palette-tooltip { 76 | display: flex; 77 | align-items: center; 78 | justify-content: center; 79 | } 80 | 81 | /* Canvas Tooltip */ 82 | 83 | .palette-tooltip { 84 | position: absolute; 85 | display: none; 86 | background: #000000C0; 87 | width: max-content; 88 | min-width: 100px; 89 | height: 40px; 90 | text-align: center; 91 | vertical-align: middle; 92 | font-size: 100%; 93 | } 94 | 95 | .palette.palette-hover > canvas:hover ~ .palette-tooltip { 96 | display: flex; 97 | align-items: center; 98 | justify-content: center; 99 | } 100 | 101 | /* Palette Direction & Hover */ 102 | 103 | .palette.paletteColumn.palette-hover > div:hover { 104 | flex-basis: var(--palette-column-flex-basis); 105 | } 106 | 107 | .palette:not(.paletteColumn).palette-hover > div:hover { 108 | flex-basis: 80px; 109 | } 110 | 111 | /* Palette Item Text */ 112 | 113 | .palette > div > span { 114 | display: block; 115 | text-align: center; 116 | font-size: 100%; 117 | font-weight: bold; 118 | color: var(--palette-color); 119 | user-select: none; 120 | } 121 | 122 | .palette.palette-hover > div > span { 123 | display: none; 124 | } 125 | 126 | .palette.palette-hover > div:hover > span { 127 | display: block; 128 | } 129 | 130 | .palette.palette-hide-text > div > span { 131 | display: none; 132 | } 133 | 134 | .palette.palette-hide-text > div:hover > span { 135 | display: none; 136 | } 137 | 138 | /* Edit Mode */ 139 | 140 | .palette.edit-mode { 141 | overflow-x: auto; 142 | } 143 | 144 | .palette > div > .edit-container { 145 | --edit-background-color: #000000; 146 | --edit-color: #ffffff; 147 | display: flex; 148 | flex-direction: column; 149 | justify-content: flex-end; 150 | align-items: center; 151 | margin: 16px 0; 152 | gap: 16px; 153 | } 154 | 155 | .palette.palette-hide-text > div > .edit-container { 156 | display: none; 157 | } 158 | 159 | .palette.palette-hide-text > div:hover > .edit-container { 160 | display: flex; 161 | } 162 | 163 | .palette > div > .edit-container > span { 164 | --edit-font-size: 16px; 165 | color: var(--edit-color); 166 | font-weight: bold; 167 | font-size: var(--edit-font-size); 168 | user-select: none; 169 | } 170 | 171 | .palette > div > .edit-container > .color-span-editable { 172 | box-shadow: rgba(0, 0, 0, 0.35) 0px -50px 20px -28px inset; 173 | cursor: pointer; 174 | } 175 | 176 | /* Color Trash Button */ 177 | .palette > div > .edit-container > button { 178 | background-color: var(--edit-background-color); 179 | color: var(--edit-color); 180 | box-shadow: rgba(0, 0, 0, 0.35) 0px -50px 20px -28px inset; 181 | cursor: pointer; 182 | } 183 | 184 | /* Drag & Drop */ 185 | 186 | .palette > .is-dragging { 187 | opacity: 0; 188 | } 189 | 190 | /* Invalid Palette */ 191 | 192 | .palette > .invalid { 193 | position: absolute; 194 | display: flex; 195 | justify-content: center; 196 | align-items: center; 197 | height: var(--palette-height); 198 | width: var(--palette-width); 199 | background-color: #000000C0; 200 | border-radius: var(--palette-corners); 201 | } 202 | 203 | .palette > .invalid > span { 204 | display: flex; 205 | justify-content: center; 206 | align-items: center; 207 | color: white; 208 | background-color: #000; 209 | width: 100%; 210 | height: 30%; 211 | text-align: center; 212 | user-select: none; 213 | } 214 | 215 | /* Invalid Pulse */ 216 | 217 | .palette-pulse { 218 | animation: pulse var(--notice-duration) infinite; 219 | } 220 | 221 | .palette-pulse > .invalid { 222 | animation: pulse-shadow var(--notice-duration) infinite; 223 | } 224 | 225 | .palette-pulse > .invalid > span { 226 | /* 1px padding so that box-shadow can show in full on left / right */ 227 | margin: 0px 1px; 228 | } 229 | 230 | @keyframes pulse { 231 | 50% { 232 | background-color: #FFFF0080; 233 | } 234 | } 235 | 236 | @keyframes pulse-shadow { 237 | 50% { 238 | box-shadow: inset 0px 0px 0px 1px #FFFF0080; 239 | } 240 | } 241 | 242 | /* Tabs */ 243 | 244 | .palette-editor > section > .control-container { 245 | display: flex; 246 | justify-content: center; 247 | align-items: center; 248 | gap: 5%; 249 | padding: .75em 0; 250 | } 251 | 252 | .palette-editor > section > .control-container > button { 253 | cursor: pointer; 254 | } 255 | 256 | .palette-editor > section > .colors-container { 257 | padding: .75em 0 0 0; 258 | } 259 | 260 | /* Color Picker Mode */ 261 | 262 | .palette-editor > section > .select-color-picker > div > div { 263 | 264 | } 265 | 266 | /* Generate Mode */ 267 | 268 | .palette-editor > section > .select-generate > div > div > button { 269 | cursor: pointer; 270 | } 271 | 272 | /* Image Mode Add Colors */ 273 | 274 | .palette-editor > section > .select-image > .add-colors > .setting-item-control > div { 275 | display: flex; 276 | flex-direction: column; 277 | align-items: flex-end; 278 | justify-content: center; 279 | } 280 | 281 | .palette-editor > section > .select-image > .add-colors > .setting-item-control > div > div { 282 | display: flex; 283 | align-items: center; 284 | justify-content: center; 285 | gap: 5px; 286 | } 287 | 288 | .palette-editor > section > .select-image > .add-colors > .setting-item-control > div > div > button { 289 | cursor: pointer; 290 | } 291 | 292 | .palette-editor > section > .select-image > .add-colors > .setting-item-control > div > div > input[type="file"] { 293 | display: none; 294 | } 295 | 296 | .palette-editor> section > .select-image > .image-preview > .setting-item-info { 297 | display: none; 298 | } 299 | 300 | /* Image Mode Preview */ 301 | 302 | .palette-editor > section > .select-image > .image-preview > div { 303 | display: flex; 304 | justify-content: center; 305 | align-items: center; 306 | } 307 | 308 | .palette-editor > section > .select-image > .hide-image-preview { 309 | display: none; 310 | } 311 | 312 | /* URL Mode */ 313 | 314 | .palette-editor > section > .select-url > div > div > button { 315 | cursor: pointer; 316 | } 317 | 318 | /* Palette Preview */ 319 | 320 | .palette-editor > section > .palette-preview { 321 | 322 | } 323 | 324 | .color-palette-settings { 325 | & > h2 { 326 | font-size: 20px; 327 | } 328 | } 329 | 330 | .color-palette-donate { 331 | height: 100%; 332 | padding: 0; 333 | margin: 2%; 334 | } -------------------------------------------------------------------------------- /src/components/PaletteMRC.ts: -------------------------------------------------------------------------------- 1 | import { MarkdownPostProcessorContext, MarkdownRenderChild, MarkdownView, Notice } from "obsidian"; 2 | import ColorPalette, { urlRegex } from "main"; 3 | import { ColorPaletteSettings } from "settings"; 4 | import { Palette, PaletteSettings, Status } from "./Palette"; 5 | import { createPaletteBlock, getModifiedSettings, parseUrl, pluginToPaletteSettings } from "utils/basicUtils"; 6 | import validateColor from "validate-color"; 7 | import { PaletteMenu } from "./PaletteMenu"; 8 | 9 | export class PaletteMRC extends MarkdownRenderChild { 10 | plugin: ColorPalette; 11 | pluginSettings: ColorPaletteSettings; 12 | input: string; 13 | palette: Palette 14 | context: MarkdownPostProcessorContext; 15 | editModeChanges: { colors: string[], settings: Partial | undefined }; 16 | 17 | constructor(plugin: ColorPalette, containerEl: HTMLElement, input: string, context: MarkdownPostProcessorContext) { 18 | super(containerEl); 19 | this.plugin = plugin; 20 | this.pluginSettings = plugin.settings; 21 | this.input = input; 22 | this.context = context; 23 | } 24 | 25 | onload(): void { 26 | this.update(); 27 | // Add new palette to state 28 | this.plugin.palettes?.push(this); 29 | 30 | this.containerEl.addEventListener('contextmenu', (e) => { 31 | // Ensure palette is valid before creating a new menu 32 | if(this.palette.status === Status.VALID) { 33 | const paletteMenu = new PaletteMenu(this.plugin.app, this.context, this.palette, (colors, settings) => { 34 | if(colors == undefined) this.setPaletteInput(''); 35 | else this.setPaletteInput(createPaletteBlock({ colors, settings })); 36 | }); 37 | paletteMenu.showAtMouseEvent(e); 38 | } 39 | }) 40 | } 41 | 42 | unload(): void { 43 | // Remove palette listeners on unload 44 | this.palette.unload(); 45 | // Remove palette from state 46 | this.plugin.palettes?.remove(this); 47 | } 48 | 49 | /** 50 | * Updates the palette contents 51 | */ 52 | public update() { 53 | // Remove current palette 54 | this.containerEl.empty(); 55 | 56 | // Calculate colors & settings 57 | const { colors, settings } = this.calcColorsAndSettings(this.input); 58 | 59 | // Set editModeChanges initial values if valid 60 | if(typeof colors !== 'string' && typeof settings !== 'string') this.editModeChanges = {colors, settings}; 61 | 62 | // Create new palette 63 | this.palette = new Palette(colors, settings, this.containerEl, this.pluginSettings); 64 | this.palette.emitter.on('changed', (colors, settings) => { 65 | const modifiedSettings = getModifiedSettings(settings); 66 | // Save stored changes 67 | this.editModeChanges = { colors, settings: modifiedSettings }; 68 | }) 69 | this.palette.emitter.on('editMode', (editMode) => { 70 | if(!editMode) { 71 | // Set palette input to stored changes 72 | this.setPaletteInput(createPaletteBlock({ colors: this.editModeChanges.colors, settings: this.editModeChanges.settings })); 73 | } 74 | }) 75 | } 76 | 77 | /** 78 | * Parses input & extracts settings 79 | * @param input settings from codeblock 80 | * @returns PaletteSettings or Status if settings are not valid 81 | */ 82 | private parseSettings(input: string): PaletteSettings | Status { 83 | try { 84 | // Extract JSON settings from the palette 85 | return JSON.parse(input); 86 | } 87 | catch(error) { 88 | return Status.INVALID_SETTINGS; 89 | } 90 | } 91 | 92 | /** 93 | * Parses input & extracts colors based on color space or URL 94 | * @param input colors from codeblock 95 | * @returns Array of colors or Status if colors are not valid 96 | */ 97 | private parseColors(input: string[], override: boolean): string[] | Status { 98 | let colors = input.flatMap((color) => { 99 | // Split RGB / HSL delimited by semicolons 100 | if(color.includes('(')){ 101 | return color.split(';').flatMap((postSplitColor) => postSplitColor.trim()) 102 | // Remove whitespace elements from array 103 | .filter((color) => color !== ''); 104 | } 105 | // Split colors delimited by commas 106 | return color.split(',').flatMap((postSplitColor) => { 107 | return postSplitColor.trim(); 108 | }) 109 | // Remove semicolons 110 | }).flatMap((color) => color.trim().replace(';', '')); 111 | 112 | // Combine colors array into string 113 | const rawColors = colors.join(''); 114 | 115 | // If URL parse and return 116 | if(rawColors.match(urlRegex)) return parseUrl(rawColors); 117 | 118 | // Return status if colors are invalid 119 | if (!override) { 120 | for(let color of colors) { 121 | if(!validateColor(color)) return Status.INVALID_COLORS; 122 | } 123 | } 124 | 125 | // Return final colors array 126 | return colors; 127 | } 128 | 129 | /** 130 | * Calculates colors and settings based on codeblock contents 131 | */ 132 | private calcColorsAndSettings(input: string) { 133 | // Splits input by newline creating an array 134 | const split = input.split('\n') 135 | // Returns true if palette settings are defined 136 | const hasSettings = split.some((val) => val.includes(('{'))); 137 | 138 | // Remove and parse the last split index (settings are always defined on the last index) 139 | let settings = hasSettings ? this.parseSettings(split.pop() || '') : undefined; 140 | 141 | // Get PaletteSettings if valid or plugin defaults if invalid 142 | let settingsObj = typeof settings === 'object' ? settings : pluginToPaletteSettings(this.pluginSettings); 143 | 144 | return { colors: this.parseColors(split, settingsObj.override), settings: settings }; 145 | } 146 | 147 | /** 148 | * Gets the palette codeblock input 149 | */ 150 | public getPaletteInput() { 151 | let editor = this.plugin.app.workspace.getActiveViewOfType(MarkdownView)?.editor; 152 | // Palette line start & line end 153 | const paletteSection = this.context.getSectionInfo(this.palette.containerEl); 154 | if(paletteSection && editor) return { 155 | lines: { 156 | lineStart: paletteSection.lineStart, 157 | lineEnd: paletteSection.lineEnd 158 | }, 159 | input: editor.getRange( 160 | {line: paletteSection.lineStart, ch: 0}, 161 | {line: paletteSection.lineEnd + 1, ch: 0} 162 | ) 163 | } 164 | else { 165 | this.createNotice('The editor has not fully loaded yet.'); 166 | } 167 | } 168 | 169 | /** 170 | * Sets the palette codeblock input with `replacement` 171 | */ 172 | public setPaletteInput(replacement: string) { 173 | let editor = this.plugin.app.workspace.getActiveViewOfType(MarkdownView)?.editor; 174 | // Palette line start & line end 175 | const paletteSection = this.context.getSectionInfo(this.palette.containerEl); 176 | if(paletteSection && editor) { 177 | editor.replaceRange(replacement, {line: paletteSection.lineStart, ch: 0}, {line: paletteSection.lineEnd + 1, ch: 0}); 178 | return { 179 | lineStart: paletteSection.lineStart, 180 | lineEnd: paletteSection.lineEnd 181 | }; 182 | } 183 | else { 184 | this.createNotice('The editor has not fully loaded yet.'); 185 | } 186 | } 187 | 188 | /** 189 | * Creates a new notice using pre-set settings 190 | * @param message Message to display 191 | */ 192 | public createNotice(message: string) { 193 | new Notice(message, this.pluginSettings.noticeDuration); 194 | } 195 | } -------------------------------------------------------------------------------- /src/settings.ts: -------------------------------------------------------------------------------- 1 | import ColorPalette from "main"; 2 | import { App, Notice, PluginSettingTab, Setting } from "obsidian"; 3 | import { PaletteSettings } from "components/Palette"; 4 | import { pluginToPaletteSettings } from "utils/basicUtils"; 5 | 6 | export enum Direction { 7 | Row = 'row', 8 | Column = 'column' 9 | } 10 | 11 | export enum AliasMode { 12 | Both = 'Both', 13 | Alias = 'Prefer Alias' 14 | } 15 | 16 | export enum CopyFormat { 17 | Raw = 'Raw', 18 | Value = 'Value' 19 | } 20 | 21 | export interface ColorPaletteSettings { 22 | noticeDuration: number; 23 | errorPulse: boolean; 24 | aliasMode: AliasMode; 25 | corners: boolean; 26 | stabilityWhileEditing: boolean; 27 | reloadDelay: number; 28 | copyFormat: CopyFormat; 29 | height: number; 30 | width: number; 31 | direction: Direction, 32 | gradient: boolean, 33 | hover: boolean, 34 | hideText: boolean, 35 | override: boolean 36 | } 37 | 38 | export const defaultSettings: ColorPaletteSettings = { 39 | noticeDuration: 10000, 40 | errorPulse: true, 41 | aliasMode: AliasMode.Both, 42 | corners: true, 43 | stabilityWhileEditing: true, 44 | reloadDelay: 5, 45 | copyFormat: CopyFormat.Raw, 46 | height: 150, 47 | width: 700, 48 | direction: Direction.Column, 49 | gradient: false, 50 | hover: true, 51 | hideText: false, 52 | override: false 53 | }; 54 | 55 | export class SettingsTab extends PluginSettingTab { 56 | plugin: ColorPalette; 57 | settings: PaletteSettings; 58 | reloadDelay: number; 59 | 60 | constructor(app: App, plugin: ColorPalette) { 61 | super(app, plugin); 62 | this.plugin = plugin; 63 | } 64 | 65 | display() { 66 | const { containerEl } = this; 67 | let { settings } = this.plugin; 68 | this.settings = pluginToPaletteSettings(settings); 69 | this.reloadDelay = settings.reloadDelay; 70 | 71 | containerEl.empty(); 72 | 73 | containerEl.createEl('h2').setText('General'); 74 | containerEl.addClass('color-palette-settings'); 75 | 76 | new Setting(containerEl) 77 | .setName('Alias Mode') 78 | .setDesc('What will be shown when aliases option is set in local palette options. Defaults to showing both color and alias.') 79 | .addDropdown((dropdown) => { 80 | dropdown 81 | .addOption(AliasMode.Both, AliasMode.Both) 82 | .addOption(AliasMode.Alias, AliasMode.Alias) 83 | .setValue(this.plugin.settings.aliasMode) 84 | .onChange(async (value) => { 85 | settings.aliasMode = value as AliasMode; 86 | await this.plugin.saveSettings(); 87 | }) 88 | }) 89 | 90 | new Setting(containerEl) 91 | .setName("Palette Corners") 92 | .setDesc("Minor aesthetic change which toggles whether the corners on palettes are rounded.") 93 | .addToggle((toggle) => { 94 | toggle 95 | .setValue(settings.corners) 96 | .onChange(async (value) => { 97 | settings.corners = value; 98 | await this.plugin.saveSettings(); 99 | }) 100 | }) 101 | 102 | new Setting(containerEl) 103 | .setName("Stability While Editing") 104 | .setDesc("Keeps the palette from moving while in edit mode.") 105 | .addToggle((toggle) => { 106 | toggle 107 | .setValue(settings.stabilityWhileEditing) 108 | .onChange(async (value) => { 109 | settings.stabilityWhileEditing = value; 110 | await this.plugin.saveSettings(); 111 | }) 112 | }) 113 | 114 | new Setting(containerEl) 115 | .setName("Reload Delay") 116 | .setDesc("How long it takes in milliseconds for palettes to be updated after changes have been made (Larger values are less responsive).") 117 | .addText((text) => { 118 | text 119 | .setValue(settings.reloadDelay.toString()) 120 | .onChange(async (value) => { 121 | try { 122 | // Check if valid number 123 | if(!Number.isNaN(Number(value))) { 124 | settings.reloadDelay = Number(value); 125 | await this.plugin.saveSettings(); 126 | } 127 | else throw new Error('Please enter a number.'); 128 | } 129 | catch(e) { 130 | new Notice(e); 131 | } 132 | }); 133 | }); 134 | 135 | new Setting(containerEl) 136 | .setName('Copy Format') 137 | .setDesc('Choice of format when copying colors.') 138 | .addDropdown((dropdown) => { 139 | dropdown 140 | .addOption(CopyFormat.Raw, CopyFormat.Raw) 141 | .addOption(CopyFormat.Value, CopyFormat.Value) 142 | .setValue(this.plugin.settings.copyFormat) 143 | .onChange(async (value) => { 144 | settings.copyFormat = value as CopyFormat; 145 | await this.plugin.saveSettings(); 146 | }) 147 | }) 148 | 149 | containerEl.createEl('h2').setText('Defaults'); 150 | 151 | new Setting(containerEl) 152 | .setName('Height') 153 | .addText((text) => { 154 | text 155 | .setValue(settings.height.toString()) 156 | .onChange(async (value) => { 157 | try { 158 | // Check if valid number 159 | if(!Number.isNaN(Number(value))) { 160 | settings.height = Number(value); 161 | await this.plugin.saveSettings(); 162 | } 163 | else throw new Error('Please enter a number.'); 164 | } 165 | catch(e) { 166 | new Notice(e); 167 | } 168 | }) 169 | }) 170 | 171 | new Setting(containerEl) 172 | .setName('Width') 173 | .setDesc('Caution - Might cause palettes to display incorrectly.') 174 | .addText((text) => { 175 | text 176 | .setValue(settings.width.toString()) 177 | .onChange(async (value) => { 178 | try { 179 | // Check if valid number 180 | if(!Number.isNaN(Number(value))) { 181 | settings.width = Number(value); 182 | await this.plugin.saveSettings(); 183 | } 184 | else throw new Error('Please enter a number.'); 185 | } 186 | catch(e) { 187 | new Notice(e); 188 | } 189 | }) 190 | }) 191 | 192 | new Setting(containerEl) 193 | .setName('Direction') 194 | .addDropdown((dropdown) => { 195 | dropdown 196 | .addOption(Direction.Column, Direction.Column) 197 | .addOption(Direction.Row, Direction.Row) 198 | .setValue(this.plugin.settings.direction) 199 | .onChange(async (value) => { 200 | settings.direction = value as Direction 201 | await this.plugin.saveSettings(); 202 | }) 203 | }) 204 | 205 | new Setting(containerEl) 206 | .setName('Gradient') 207 | .addToggle((toggle) => { 208 | toggle 209 | .setValue(this.plugin.settings.gradient) 210 | .onChange(async (value) => { 211 | settings.gradient = value; 212 | await this.plugin.saveSettings(); 213 | }) 214 | }) 215 | 216 | new Setting(containerEl) 217 | .setName("Hover") 218 | .setDesc("Toggles whether palettes can be hovered") 219 | .addToggle((toggle) => { 220 | toggle 221 | .setValue(settings.hover) 222 | .onChange(async (value) => { 223 | settings.hover = value; 224 | await this.plugin.saveSettings(); 225 | }) 226 | }) 227 | 228 | new Setting(containerEl) 229 | .setName("Hide Text") 230 | .setDesc("Disables color and alias visibility") 231 | .addToggle((toggle) => { 232 | toggle 233 | .setValue(settings.hideText) 234 | .onChange(async (value) => { 235 | settings.hideText = value; 236 | await this.plugin.saveSettings(); 237 | }) 238 | }) 239 | 240 | new Setting(containerEl) 241 | .setName("Override") 242 | .setDesc("Disables color validation for full control (advanced)") 243 | .addToggle((toggle) => { 244 | toggle 245 | .setValue(settings.override) 246 | .onChange(async (value) => { 247 | settings.override = value; 248 | await this.plugin.saveSettings(); 249 | }) 250 | }) 251 | 252 | containerEl.createEl('h2').setText('Other'); 253 | 254 | new Setting(containerEl) 255 | .setName("Palette Error Pulse") 256 | .setDesc("Whether the affected palette should pulse when encountering an error.") 257 | .addToggle((toggle) => { 258 | toggle 259 | .setValue(settings.errorPulse) 260 | .onChange(async (value) => { 261 | settings.errorPulse = value; 262 | await this.plugin.saveSettings(); 263 | }) 264 | }) 265 | 266 | new Setting(containerEl) 267 | .setName("Notice Duration") 268 | .setDesc("How long palette error messages are show for in seconds (0 for indefinite).") 269 | .addText((text) => { 270 | text 271 | .setValue((settings.noticeDuration / 1000).toString()) 272 | .onChange(async (value) => { 273 | try { 274 | // Check if valid number 275 | if(!Number.isNaN(Number(value))) { 276 | settings.noticeDuration = Number(value) * 1000; 277 | await this.plugin.saveSettings(); 278 | } 279 | else throw new Error('Please enter a number.'); 280 | } 281 | catch(e) { 282 | new Notice(e); 283 | } 284 | }); 285 | }); 286 | 287 | new Setting(containerEl) 288 | .setName('Donate') 289 | .setDesc('If you like this plugin, consider donating to support continued development.') 290 | .addButton((button) => { 291 | button 292 | .onClick(() => open('https://github.com/sponsors/ALegendsTale')) 293 | .setClass('color-palette-donate') 294 | 295 | const image = button.buttonEl.appendChild(createEl('img')); 296 | image.src = 'https://img.shields.io/badge/Sponsor-%E2%9D%A4-%23EA4AAA?style=flat&logo=Github'; 297 | }) 298 | .addButton((button) => { 299 | button 300 | .onClick(() => open('https://www.paypal.com/donate/?hosted_button_id=BHHFMGX822K4S')) 301 | .setClass('color-palette-donate') 302 | 303 | const image = button.buttonEl.appendChild(createEl('img')); 304 | image.src = 'https://img.shields.io/badge/Paypal-%23003087?style=flat&logo=Paypal'; 305 | }) 306 | } 307 | 308 | // Called when settings are exited 309 | hide() { 310 | const settingsChanged = JSON.stringify(this.settings) !== JSON.stringify(pluginToPaletteSettings(this.plugin.settings)); 311 | const reloadDelayChanged = this.reloadDelay !== this.plugin.settings.reloadDelay; 312 | // Update palettes if PaletteSettings have changed 313 | if (this.plugin?.palettes && (settingsChanged || reloadDelayChanged)) { 314 | for (let paletteMRC of this.plugin.palettes) { 315 | paletteMRC.update(); 316 | } 317 | } 318 | } 319 | } 320 | -------------------------------------------------------------------------------- /src/components/Palette.ts: -------------------------------------------------------------------------------- 1 | import { Notice } from "obsidian"; 2 | import { Direction, AliasMode, ColorPaletteSettings, defaultSettings } from "settings"; 3 | import { copyToClipboard, pluginToPaletteSettings } from "utils/basicUtils"; 4 | import { PaletteItem } from "./PaletteItem"; 5 | import { DragDrop } from "utils/dragDropUtils"; 6 | import { Canvas } from "utils/canvasUtils"; 7 | import { EventEmitter } from "utils/EventEmitter"; 8 | 9 | export type PaletteSettings = { 10 | height: number 11 | width: number 12 | direction: Direction 13 | gradient: boolean 14 | hover: boolean 15 | hideText: boolean 16 | override: boolean 17 | aliases: string[] 18 | } 19 | 20 | export enum Status { 21 | VALID = 'Valid', 22 | INVALID_COLORS = 'Invalid Colors', 23 | INVALID_SETTINGS = 'Invalid Settings', 24 | INVALID_COLORS_AND_SETTINGS = 'Invalid Colors & Settings', 25 | INVALID_GRADIENT = 'Invalid Gradient' 26 | } 27 | 28 | type EventMap = { 29 | resized: [palette: ResizeObserverEntry], 30 | changed: [colors: string[], settings: PaletteSettings], 31 | editMode: [editMode: boolean] 32 | } 33 | 34 | export class Palette { 35 | containerEl: HTMLElement; 36 | pluginSettings: ColorPaletteSettings; 37 | colors: string[]; 38 | settings: PaletteSettings; 39 | status: Status 40 | showNotice: boolean 41 | private editMode: boolean; 42 | dragDrop: DragDrop | null; 43 | dropzone: HTMLDivElement; 44 | paletteItems: PaletteItem[]; 45 | paletteCanvas: Canvas | undefined; 46 | public emitter: EventEmitter; 47 | 48 | constructor(colors: string[] | Status, settings: PaletteSettings | Status | undefined, containerEl: HTMLElement, pluginSettings: ColorPaletteSettings, editMode = false) { 49 | this.containerEl = containerEl; 50 | this.containerEl.addClass('palette-container'); 51 | this.pluginSettings = pluginSettings; 52 | this.status = Status.VALID; 53 | this.showNotice = true; 54 | this.editMode = editMode; 55 | this.paletteItems = []; 56 | this.emitter = new EventEmitter; 57 | 58 | this.setDefaults(colors, settings); 59 | this.load(); 60 | 61 | let observerDebouncers = new WeakMap; 62 | 63 | // Refresh gradient palettes when Obsidian resizes 64 | const resizeObserver = new ResizeObserver((palettes) => { 65 | // There is only one palette 66 | palettes.forEach((palette) => { 67 | // Clear timeout on observerDebouncers palette 68 | clearTimeout(observerDebouncers.get(palette.target)); 69 | // Set a new timeout on palette & store in observerDebouncers 70 | observerDebouncers.set(palette.target, setTimeout(() => this.emitter.emit('resized', palette), this.pluginSettings.reloadDelay)); 71 | }) 72 | }) 73 | // Tracking containerEl (instead of dropzone) ensures resizeObserver persists through reloads 74 | resizeObserver.observe(this.containerEl); 75 | 76 | // Resized event after user has stopped dragging 77 | this.emitter.on('resized', (palette) => this.onResized(palette)); 78 | } 79 | 80 | /** 81 | * Sets the initial defaults 82 | */ 83 | public setDefaults(colors: string[] | Status, settings: PaletteSettings | Status | undefined) { 84 | // Settings are invalid 85 | if(typeof settings === 'string') { 86 | this.settings = pluginToPaletteSettings(this.pluginSettings); 87 | this.status = Status.INVALID_SETTINGS; 88 | } 89 | // Settings are valid 90 | if(typeof settings === 'object') { 91 | this.settings = {...pluginToPaletteSettings(this.pluginSettings), ...settings}; 92 | } 93 | // Settings were not set by user 94 | if(typeof settings === 'undefined') { 95 | this.settings = pluginToPaletteSettings(this.pluginSettings); 96 | } 97 | // Colors are invalid 98 | if(typeof colors === 'string') { 99 | this.colors = []; 100 | // Set status to Invalid Colors & Settings if colors were also invalid 101 | this.status = this.status === Status.INVALID_SETTINGS ? Status.INVALID_COLORS_AND_SETTINGS : Status.INVALID_COLORS; 102 | } 103 | // Colors are valid 104 | if(typeof colors === 'object') { 105 | this.colors = colors; 106 | } 107 | } 108 | 109 | /** 110 | * Loads the palette 111 | */ 112 | public load() { 113 | // Create new palette 114 | this.createPalette(this.colors, this.settings); 115 | 116 | // Adds Drag & Drop to palettes in edit mode which are not gradients 117 | if(this.editMode && !this.settings.gradient){ 118 | this.dropzone.toggleClass('palette-hover', !this.pluginSettings.stabilityWhileEditing); 119 | this.dropzone.toggleClass('palette-hide-text', !this.pluginSettings.stabilityWhileEditing); 120 | 121 | this.dragDrop = new DragDrop([this.dropzone], Array.from(this.dropzone.children), (e, res) => { 122 | // Sort palette items according to drop order 123 | this.paletteItems.sort((a, b) => { 124 | return res.order.indexOf(a.container) - res.order.indexOf(b.container); 125 | }); 126 | this.colors = this.paletteItems.map((item) => item.color); 127 | this.settings.aliases = this.paletteItems.map((item) => item.settings.alias); 128 | this.emitter.emit('changed', this.colors, this.settings); 129 | this.reload(); 130 | }); 131 | } 132 | 133 | // Add edit-mode class if set on load 134 | this.dropzone.toggleClass('edit-mode', this.editMode); 135 | } 136 | 137 | /** 138 | * Unloads the palette 139 | */ 140 | public unload(){ 141 | // Remove listeners 142 | this.emitter.clear(); 143 | // Remove paletteItem listeners 144 | this.paletteItems.forEach((item) => item.unload()); 145 | // Remove children 146 | this.containerEl.empty(); 147 | this.paletteItems = []; 148 | this.paletteCanvas = undefined; 149 | } 150 | 151 | /** 152 | * Reloads the palette contents 153 | * @param resize Whether the palette is reloading because of a resize (defaults to false) 154 | */ 155 | public reload(resize: { height: number, width: number } = {height: 0, width: 0}){ 156 | // Check if palette size is zero 157 | const isZero = resize.height === 0 && resize.width === 0; 158 | if(!isZero) { 159 | // Set width if size is not zero 160 | this.setWidth(this.getPaletteWidth(resize.width)); 161 | return; 162 | } 163 | // Only show notice on non-resize reloads 164 | this.showNotice = !resize; 165 | this.unload(); 166 | this.setDefaults(this.colors, this.settings); 167 | this.load(); 168 | this.showNotice = true; 169 | } 170 | 171 | private onResized(palette: ResizeObserverEntry) { 172 | const size = {height: palette.contentRect.height, width: palette.contentRect.width}; 173 | // Check if palette size is zero 174 | const isZero = size.height === 0 && size.width === 0; 175 | // Resize if size is not zero 176 | if (!isZero) this.reload({height: size.height, width: size.width}); 177 | } 178 | 179 | /** 180 | * Sets the width of the palette 181 | */ 182 | public setWidth(width: number) { 183 | // Create new gradient if canvas 184 | if(this.settings.gradient && this.paletteCanvas) this.paletteCanvas.createGradient(this.colors, width, this.settings.height, this.settings.direction); 185 | // Set palette width 186 | this.dropzone.style.setProperty('--palette-width', `${width}px`); 187 | this.containerEl.toggleClass('palette-scroll', width > defaultSettings.width); 188 | } 189 | 190 | /** 191 | * @returns `user` OR `auto` width based on which is more appropriate 192 | */ 193 | public getPaletteWidth(resizeOffset = 0) { 194 | const paletteOffset = resizeOffset !== 0 ? resizeOffset : this.dropzone.offsetWidth; 195 | // Set user-set width if it is greater than the default width 196 | if(this.settings.width > defaultSettings.width) return this.settings.width; 197 | // Automatically set width if offset is less than settings width 198 | if(paletteOffset < this.settings.width && paletteOffset > 0) return paletteOffset; 199 | // Set user-set width 200 | else return this.settings.width; 201 | } 202 | 203 | /** 204 | * Creates a new notice using pre-set settings 205 | * @param message Message to display 206 | */ 207 | public createNotice(message: string) { 208 | this.showNotice && new Notice(message, this.pluginSettings.noticeDuration); 209 | } 210 | 211 | public setEditMode(editMode: boolean) { 212 | this.editMode = editMode; 213 | this.emitter.emit('editMode', editMode); 214 | } 215 | 216 | public getEditMode(): boolean { 217 | return this.editMode; 218 | } 219 | 220 | /** 221 | * Create new palette contents based on colors & settings 222 | * @param colors 223 | * @param settings 224 | */ 225 | private createPalette(colors: string[], settings: PaletteSettings){ 226 | this.dropzone = this.containerEl.createEl('div'); 227 | this.dropzone.addClass('palette') 228 | // Set default corner style 229 | this.dropzone.style.setProperty('--palette-corners', this.pluginSettings.corners ? '5px' : '0px'); 230 | this.dropzone.style.setProperty('--palette-direction', settings.direction === Direction.Row ? Direction.Column : Direction.Row); 231 | this.dropzone.style.setProperty('--not-palette-direction', settings.direction); 232 | this.dropzone.style.setProperty('--palette-height', `${settings.height}px`); 233 | this.dropzone.toggleClass('palette-hover', settings.hover); 234 | this.dropzone.toggleClass('palette-hide-text', settings.hideText); 235 | 236 | try{ 237 | // Throw error & create Invalid Palette 238 | if(this.status !== Status.VALID) throw new PaletteError(this.status); 239 | this.settings.gradient ? 240 | this.createGradientPalette(this.dropzone, colors) 241 | : 242 | this.createColorPalette(this.dropzone, colors, settings); 243 | 244 | // Set width of palettes 245 | this.setWidth(this.getPaletteWidth()); 246 | } 247 | catch(err){ 248 | if(err instanceof PaletteError) this.createInvalidPalette(err.status, err.message); 249 | else this.createNotice(err); 250 | } 251 | } 252 | 253 | private createGradientPalette(container: HTMLElement, colors: string[]){ 254 | if(colors.length <= 1) throw new PaletteError(Status.INVALID_GRADIENT); 255 | 256 | this.paletteCanvas = new Canvas(container); 257 | this.paletteCanvas.emitter.on('click', async (color) => await copyToClipboard(color.toUpperCase(), this.pluginSettings.copyFormat)); 258 | } 259 | 260 | private createColorPalette(container: HTMLElement, colors: string[], settings: PaletteSettings){ 261 | for(const [i, color] of colors.entries()){ 262 | const paletteItem = new PaletteItem(container, color, 263 | { 264 | aliasMode: this.pluginSettings.aliasMode, 265 | editMode: this.editMode, 266 | stabilityWhileEditing: this.pluginSettings.stabilityWhileEditing, 267 | height: settings.height, 268 | direction: settings.direction, 269 | hover: settings.hover, 270 | hideText: settings.hideText, 271 | alias: settings.aliases?.[i] || '', 272 | colorCount: colors.length, 273 | } 274 | ); 275 | 276 | paletteItem.emitter.on('click', async (e: MouseEvent) => await copyToClipboard(color.toUpperCase(), this.pluginSettings.copyFormat)); 277 | 278 | paletteItem.emitter.on('trash', (e: MouseEvent) => { 279 | e.stopPropagation(); 280 | const deletedIndex = this.colors.indexOf(color); 281 | let colors = this.colors; 282 | let settings = this.settings; 283 | colors.splice(deletedIndex, 1); 284 | settings.aliases.splice(deletedIndex, 1); 285 | this.emitter.emit('changed', colors, settings); 286 | this.reload(); 287 | }) 288 | 289 | paletteItem.emitter.on('alias', (alias) => { 290 | // Get the index of the alias relative to the PaletteItem color 291 | const aliasIndex = this.colors.findIndex(val => val === color); 292 | for(let i = 0; i < aliasIndex; i++) { 293 | // Set empty strings to empty indexes 294 | if(!this.settings.aliases[i]) this.settings.aliases[i] = ''; 295 | } 296 | // Set modified alias index 297 | this.settings.aliases[aliasIndex] = alias; 298 | }) 299 | 300 | this.paletteItems.push(paletteItem); 301 | } 302 | } 303 | 304 | /** 305 | * Create invalid palette based on palette status 306 | * @param type Palette status type 307 | */ 308 | private createInvalidPalette(type: Status, message = ''){ 309 | this.status = type; 310 | this.dropzone.style.setProperty('--palette-height', '150px'); 311 | this.dropzone.style.setProperty('--palette-width', `100%`); 312 | const invalidSection = this.dropzone.createEl('section'); 313 | invalidSection.toggleClass('invalid', true); 314 | const invalidSpan = invalidSection.createEl('span'); 315 | 316 | let defaultMessage = 'Invalid palette'; 317 | switch(type) { 318 | case Status.INVALID_COLORS: 319 | invalidSpan.setText(Status.INVALID_COLORS); 320 | defaultMessage = 'Colors are defined incorrectly'; 321 | this.createNotice(`Palette:\n${message ? message : defaultMessage}`); 322 | break; 323 | case Status.INVALID_SETTINGS: 324 | invalidSpan.setText(Status.INVALID_SETTINGS); 325 | defaultMessage = 'Issues parsing settings'; 326 | this.createNotice(`Palette:\n${message ? message : defaultMessage}`); 327 | break; 328 | case Status.INVALID_COLORS_AND_SETTINGS: 329 | invalidSpan.setText(Status.INVALID_COLORS_AND_SETTINGS); 330 | defaultMessage = 'Colors and settings are defined incorrectly'; 331 | this.createNotice(`Palette:\n${message ? message : defaultMessage}`); 332 | break; 333 | case Status.INVALID_GRADIENT: 334 | invalidSpan.setText(Status.INVALID_GRADIENT); 335 | defaultMessage = 'Gradients require more than 1 color to display'; 336 | this.createNotice(`Palette:\n${message ? message : defaultMessage}`); 337 | break; 338 | } 339 | 340 | // Pulse the Invalid Palette to show its location 341 | if(this.pluginSettings.errorPulse){ 342 | this.dropzone.style.setProperty('--notice-duration', ((this.pluginSettings.noticeDuration / 1000) / 2).toString() + 's') 343 | this.dropzone.toggleClass('palette-pulse', true); 344 | setTimeout(() => this.dropzone.toggleClass('palette-pulse', false), this.pluginSettings.noticeDuration); 345 | } 346 | } 347 | } 348 | 349 | class PaletteError extends Error { 350 | status: Status; 351 | message: string; 352 | 353 | constructor(status: Status, message = '') { 354 | super(message); 355 | this.status = status; 356 | } 357 | } -------------------------------------------------------------------------------- /src/components/EditorModal.ts: -------------------------------------------------------------------------------- 1 | import { App, ButtonComponent, ColorComponent, DropdownComponent, Modal, Notice, Setting, SliderComponent, TextComponent } from "obsidian"; 2 | import { Palette, PaletteSettings } from "./Palette"; 3 | import { urlRegex } from "main"; 4 | import colorsea from "colorsea"; 5 | import { Direction, ColorPaletteSettings } from "settings"; 6 | import { Combination, generateColors } from "utils/generateUtils"; 7 | import { getModifiedSettings, parseUrl, pluginToPaletteSettings } from "utils/basicUtils"; 8 | import CanvasImage from "utils/imageUtils"; 9 | 10 | enum SelectedInput { 11 | Color_Picker = "Color Picker", 12 | Generate = "Generate", 13 | Image = "Image", 14 | URL = "URL", 15 | } 16 | 17 | export class EditorModal extends Modal { 18 | pluginSettings: ColorPaletteSettings 19 | settings: PaletteSettings 20 | colors: string[] 21 | selectedInput: SelectedInput 22 | combination: Combination 23 | onSubmit: (colors: string[], settings: Partial | undefined) => void 24 | baseColor?: ReturnType 25 | palette?: Palette; 26 | modalRect: DOMRect; 27 | 28 | constructor(app: App, pluginSettings: ColorPaletteSettings, onSubmit: (colors: string[], settings: Partial | undefined) => void, palette?: Palette) { 29 | super(app); 30 | this.onSubmit = onSubmit; 31 | this.pluginSettings = pluginSettings; 32 | this.settings = pluginToPaletteSettings(pluginSettings); 33 | this.colors = [] 34 | this.selectedInput = SelectedInput.Color_Picker; 35 | this.combination = Combination.Random; 36 | this.baseColor = undefined; 37 | this.palette = palette; 38 | 39 | const resizeObserver = new ResizeObserver((modals) => { 40 | for (const modal of modals) { 41 | for (const child of Array.from(modal.target.children)) { 42 | if(child.hasClass('modal')) { 43 | for(const modalChild of Array.from(child.children)) { 44 | if(modalChild.hasClass('palette-editor')) { 45 | // Get modal bounding rect 46 | this.modalRect = modalChild.getBoundingClientRect(); 47 | } 48 | } 49 | } 50 | } 51 | } 52 | }) 53 | resizeObserver.observe(this.containerEl); 54 | } 55 | 56 | onOpen(): void { 57 | // Header 58 | this.contentEl.createEl('h1', { text: 'Editor' }) 59 | this.contentEl.addClass('palette-editor'); 60 | 61 | // Add Colors 62 | const colorsContainer = this.contentEl.createEl('section'); 63 | // Create header for colors section 64 | colorsContainer.createEl('h3').setText('Colors'); 65 | 66 | // Tabs 67 | let controlContainer = colorsContainer.appendChild(createDiv()); 68 | controlContainer.addClass('control-container'); 69 | 70 | // Preview 71 | const previewContainer = this.contentEl.createEl('section'); 72 | previewContainer.createEl('h3'); 73 | 74 | // Settings 75 | const settingsContainer = this.contentEl.createEl('section'); 76 | // Create header for settings section 77 | settingsContainer.createEl('h3').setText('Settings'); 78 | 79 | const colorPickerBtn = new ButtonComponent(controlContainer) 80 | .setIcon('pipette') 81 | .setTooltip('Color Picker') 82 | .onClick((e) => { 83 | changeSelectedInput(SelectedInput.Color_Picker); 84 | }) 85 | const generateBtn = new ButtonComponent(controlContainer) 86 | .setIcon('shuffle') 87 | .setTooltip('Generate') 88 | .onClick((e) => { 89 | changeSelectedInput(SelectedInput.Generate); 90 | }) 91 | const imageBtn = new ButtonComponent(controlContainer) 92 | .setIcon('image') 93 | .setTooltip('Image') 94 | .onClick((e) => { 95 | changeSelectedInput(SelectedInput.Image) 96 | }) 97 | const urlBtn = new ButtonComponent(controlContainer) 98 | .setIcon('link') 99 | .setTooltip('URL') 100 | .onClick((e) => { 101 | changeSelectedInput(SelectedInput.URL); 102 | }) 103 | 104 | let addColorsContainer = colorsContainer.appendChild(createEl('div')); 105 | addColorsContainer.addClass('colors-container'); 106 | 107 | function changeSelectedInput(selectedInput: SelectedInput) { 108 | resetStyle(); 109 | switch(selectedInput) { 110 | case SelectedInput.Color_Picker: 111 | colorPickerBtn.setCta(); 112 | addColorsContainer.empty(); 113 | createColorPicker(addColorsContainer); 114 | addColorsContainer.toggleClass('select-color-picker', true); 115 | break; 116 | case SelectedInput.Generate: 117 | generateBtn.setCta(); 118 | addColorsContainer.empty(); 119 | createGenerate(addColorsContainer); 120 | addColorsContainer.toggleClass('select-generate', true); 121 | break; 122 | case SelectedInput.Image: 123 | imageBtn.setCta(); 124 | addColorsContainer.empty(); 125 | createImage(addColorsContainer); 126 | addColorsContainer.toggleClass('select-image', true); 127 | break; 128 | case SelectedInput.URL: 129 | urlBtn.setCta(); 130 | addColorsContainer.empty(); 131 | createURL(addColorsContainer); 132 | addColorsContainer.toggleClass('select-url', true); 133 | break; 134 | } 135 | 136 | function resetStyle() { 137 | colorPickerBtn.removeCta(); 138 | generateBtn.removeCta(); 139 | imageBtn.removeCta(); 140 | urlBtn.removeCta(); 141 | addColorsContainer.toggleClass('select-color-picker', false); 142 | addColorsContainer.toggleClass('select-generate', false); 143 | addColorsContainer.toggleClass('select-image', false); 144 | addColorsContainer.toggleClass('select-url', false); 145 | } 146 | } 147 | 148 | const createColorPicker = (addColorsContainer: HTMLDivElement) => { 149 | let addColors = new Setting(addColorsContainer) 150 | .setName("Color Picker") 151 | .setDesc('Use handpicked colors') 152 | 153 | const colorPickerInput = new ColorComponent(addColors.controlEl) 154 | .onChange((value) => { 155 | this.colors.push(value); 156 | this.settings.aliases.push(''); 157 | updatePalettePreview(); 158 | }) 159 | } 160 | 161 | const createGenerate = (addColorsContainer: HTMLDivElement) => { 162 | let addColors = new Setting(addColorsContainer) 163 | .setName("Generate") 164 | .setDesc('Generate colors based on color theory') 165 | 166 | const dropdownInput = new DropdownComponent(addColors.controlEl) 167 | // Add dropdown options 168 | Object.keys(Combination).forEach((combination) => dropdownInput.addOption(combination, combination)) 169 | dropdownInput 170 | .setValue(this.combination) 171 | .onChange((value) => { 172 | this.combination = value as Combination; 173 | // Disable color picker if selected combination is random 174 | colorPickerInput.setDisabled(this.combination === Combination.Random ? true : false); 175 | }) 176 | 177 | const colorPickerInput = new ColorComponent(addColors.controlEl) 178 | .onChange((value) => { 179 | this.baseColor = colorsea(value); 180 | }) 181 | .setDisabled(this.combination === Combination.Random ? true : false); 182 | const colorPicker = Array.from(addColors.controlEl.children)[1] as HTMLInputElement 183 | colorPicker.addEventListener('contextmenu', (e) => { 184 | colorPickerInput.setValue(colorsea('#000').hex()); 185 | this.baseColor = undefined; 186 | }); 187 | 188 | const buttonInput = new ButtonComponent(addColors.controlEl) 189 | .setIcon('shuffle') 190 | .setTooltip('Loads the generated colors') 191 | .onClick((e) => { 192 | // Generate colors & settings 193 | const generated = generateColors(this.combination, { baseColor: this.baseColor, settings: this.settings }); 194 | this.colors = generated.colors; 195 | if(generated.settings) this.settings = generated.settings; 196 | updatePalettePreview(); 197 | }) 198 | } 199 | 200 | const createImage = (addColorsContainer: HTMLDivElement) => { 201 | // Represents both external & internal image URLs 202 | let fileURL = ''; 203 | 204 | let addColors = new Setting(addColorsContainer) 205 | .setClass('add-colors') 206 | .setName("Image") 207 | .setDesc('Convert image into palette') 208 | 209 | const inputContainer = addColors.controlEl.appendChild(createEl('div')); 210 | 211 | // Contains urlInput, loadButton, & fileInput 212 | const selectContainer = inputContainer.appendChild(createEl('div')); 213 | 214 | const urlInput = new TextComponent(selectContainer) 215 | .setPlaceholder('Enter URL or select file') 216 | .onChange((value) => fileURL = value) 217 | 218 | const loadButton = new ButtonComponent(selectContainer) 219 | .setIcon('arrow-up-to-line') 220 | .setTooltip('Right click to clear URL') 221 | .onClick(async (e) => { 222 | try { 223 | // Check if any text is present, otherwise prompt user to select image 224 | if(urlInput.getValue() !== '') { 225 | // Check if URL is valid 226 | if (URL.canParse(urlInput.getValue())) await updateImagePreview(urlInput.getValue()); 227 | else throw new Error('URL provided is not valid.'); 228 | } 229 | else fileInput.click(); 230 | } 231 | catch(e) { 232 | new Notice(e); 233 | } 234 | }) 235 | loadButton.buttonEl.addEventListener('contextmenu', () => urlInput.setValue('')); 236 | 237 | const fileSelector = new TextComponent(selectContainer); 238 | const fileInput = fileSelector.inputEl; 239 | fileInput.type = 'file'; 240 | fileInput.accept = 'image/*'; 241 | fileInput.addEventListener('change', (e) => { 242 | try { 243 | const reader = new FileReader(); 244 | const file = (e.target as HTMLInputElement).files?.[0]; 245 | if(file) reader.readAsDataURL(file); 246 | 247 | reader.addEventListener('load', async () => { 248 | if(typeof reader.result === 'string') { 249 | fileURL = reader.result; 250 | await updateImagePreview(fileURL); 251 | } 252 | }) 253 | reader.addEventListener('error', () => { 254 | throw new Error('Error processing image.'); 255 | }) 256 | } 257 | catch(e) { 258 | new Notice(e); 259 | } 260 | }) 261 | 262 | const sliderContainer = new Setting(addColorsContainer) 263 | .setName('Count') 264 | .setDesc('Set the number of colors to generate from the image.') 265 | 266 | const countInput = new SliderComponent(sliderContainer.controlEl) 267 | .setLimits(4, 12, 1) 268 | .setDynamicTooltip() 269 | .setValue(8) 270 | .onChange(async (value) => await updateImagePreview(fileURL)) 271 | 272 | const imageContainer = new Setting(addColorsContainer); 273 | imageContainer.setClass('image-preview'); 274 | imageContainer.setClass('hide-image-preview'); 275 | 276 | let hex: string; 277 | 278 | const canvasImage = new CanvasImage(imageContainer.controlEl); 279 | canvasImage.canvas.style.setProperty('border-radius', this.pluginSettings.corners ? '5px' : '0px'); 280 | canvasImage.canvas.addEventListener('mousemove', async (e) => { 281 | hex = canvasImage.getCanvasHex(e.clientX, e.clientY); 282 | }) 283 | canvasImage.canvas.addEventListener('click', (e) => { 284 | if(!hex) return; 285 | this.colors.push(hex); 286 | this.settings.aliases.push(''); 287 | updatePalettePreview(); 288 | }) 289 | canvasImage.image.addEventListener('load', () => { 290 | imageContainer.settingEl.toggleClass('hide-image-preview', false); 291 | }) 292 | canvasImage.image.addEventListener('error', (e) => { 293 | new Notice('The URL provided could not be loaded.'); 294 | }) 295 | 296 | /** 297 | * Updates the image mode preview 298 | */ 299 | const updateImagePreview = async (url: string) => { 300 | if(!url) return; 301 | 302 | canvasImage.update(url, this.modalRect.width, this.modalRect.height); 303 | 304 | const colors = await canvasImage.getPalette(countInput.getValue()); 305 | if(colors) { 306 | this.colors = colors.map((color) => colorsea(color).hex(0)); 307 | this.settings.aliases = []; 308 | updatePalettePreview(); 309 | } 310 | } 311 | } 312 | 313 | const createURL = (addColorsContainer: HTMLDivElement) => { 314 | let addColors = new Setting(addColorsContainer) 315 | .setName("URL") 316 | .setDesc('Only coolors.co & colorhunt.co are currently supported.') 317 | 318 | const textInput = new TextComponent(addColors.controlEl) 319 | .setPlaceholder('Enter URL'); 320 | 321 | const buttonInput = new ButtonComponent(addColors.controlEl) 322 | .setIcon('link') 323 | .setTooltip('Right click to clear URL') 324 | .onClick((e) => { 325 | try { 326 | const urlText = textInput.getValue(); 327 | if(!urlText.match(urlRegex)) throw new Error('URL provided is not valid.'); 328 | this.colors = parseUrl(urlText); 329 | this.settings.aliases = []; 330 | updatePalettePreview(); 331 | } 332 | catch(e) { 333 | new Notice(e); 334 | } 335 | }) 336 | buttonInput.buttonEl.addEventListener('contextmenu', () => { 337 | textInput.setValue(''); 338 | }) 339 | } 340 | 341 | // Set initial selectedInput 342 | changeSelectedInput(this.selectedInput); 343 | 344 | let palettePreview = previewContainer.appendChild(createDiv()); 345 | palettePreview.addClass('palette-preview'); 346 | 347 | const paletteContainer = palettePreview.appendChild(createDiv()); 348 | // Fill palette initially with random colors 349 | this.colors = this.palette ? this.palette.colors : generateColors(Combination.Random).colors; 350 | this.settings = this.palette ? this.palette.settings : this.settings; 351 | const palette = new Palette(this.colors, this.settings, paletteContainer, this.pluginSettings, true); 352 | palette.emitter.on('changed', (colors, settings) => { 353 | let modifiedSettings = getModifiedSettings(settings); 354 | this.colors = colors; 355 | if(modifiedSettings) this.settings = {...this.settings, ...modifiedSettings}; 356 | }) 357 | palettePreview.appendChild(palette.containerEl); 358 | 359 | /** 360 | * Updates the palette preview 361 | */ 362 | const updatePalettePreview = () => { 363 | palette.colors = this.colors; 364 | palette.settings = this.settings; 365 | palette.reload() 366 | } 367 | 368 | new Setting(settingsContainer) 369 | .setName("Height") 370 | .addText((text) => { 371 | text 372 | .setValue(this.settings.height.toString()) 373 | .onChange((value) => { 374 | try { 375 | // Check if valid number 376 | if(!Number.isNaN(Number(value))) { 377 | this.settings.height = Number(value); 378 | updatePalettePreview(); 379 | } 380 | else throw new Error('Please enter a number.'); 381 | } 382 | catch(e) { 383 | new Notice(e); 384 | } 385 | }) 386 | }) 387 | 388 | new Setting(settingsContainer) 389 | .setName("Width") 390 | .setDesc('Caution - Might cause palette to display incorrectly.') 391 | .addText((text) => { 392 | text 393 | .setValue(this.settings.width.toString()) 394 | .onChange((value) => { 395 | try { 396 | // Check if valid number 397 | if(!Number.isNaN(Number(value))) { 398 | this.settings.width = Number(value); 399 | updatePalettePreview(); 400 | } 401 | else throw new Error('Please enter a number.'); 402 | } 403 | catch(e) { 404 | new Notice(e); 405 | } 406 | }) 407 | }) 408 | 409 | new Setting(settingsContainer) 410 | .setName("Direction") 411 | .addDropdown((dropdown) => { 412 | dropdown 413 | .addOption(Direction.Column, Direction.Column) 414 | .addOption(Direction.Row, Direction.Row) 415 | .setValue(this.settings.direction.toString()) 416 | .onChange((value) => { 417 | this.settings.direction = value as Direction; 418 | updatePalettePreview(); 419 | }) 420 | }) 421 | 422 | new Setting(settingsContainer) 423 | .setName("Gradient") 424 | .addToggle((toggle) => { 425 | toggle 426 | .setValue(this.settings.gradient) 427 | .onChange((value) => { 428 | this.settings.gradient = value; 429 | updatePalettePreview(); 430 | }) 431 | }) 432 | 433 | new Setting(settingsContainer) 434 | .setName("Hover") 435 | .setDesc("Toggles whether palettes can be hovered") 436 | .addToggle((toggle) => { 437 | toggle 438 | .setValue(this.settings.hover) 439 | .onChange(async (value) => { 440 | this.settings.hover = value; 441 | updatePalettePreview(); 442 | }) 443 | }) 444 | 445 | new Setting(settingsContainer) 446 | .setName("Hide Text") 447 | .setDesc("Disables color and alias visibility") 448 | .addToggle((toggle) => { 449 | toggle 450 | .setValue(this.settings.hideText) 451 | .onChange(async (value) => { 452 | this.settings.hideText = value; 453 | updatePalettePreview(); 454 | }) 455 | }) 456 | 457 | new Setting(settingsContainer) 458 | .setName("Override") 459 | .setDesc("Disables color validation for full control (advanced)") 460 | .addToggle((toggle) => { 461 | toggle 462 | .setValue(this.settings.override) 463 | .onChange(async (value) => { 464 | this.settings.override = value; 465 | updatePalettePreview(); 466 | }) 467 | }) 468 | 469 | new Setting(settingsContainer) 470 | .addButton((button) => 471 | button 472 | .setButtonText("Create") 473 | .setCta() 474 | .onClick(() => { 475 | try{ 476 | // Generate random colors if none are provided 477 | if(this.colors.length === 0) this.colors = generateColors(Combination.Random).colors; 478 | this.onSubmit(this.colors, getModifiedSettings(this.settings)); 479 | this.close(); 480 | } 481 | catch(e){ 482 | new Notice(e); 483 | } 484 | }) 485 | ) 486 | } 487 | 488 | onClose(): void { 489 | // Clear palette listeners 490 | this.palette?.emitter.clear(); 491 | this.contentEl.empty(); 492 | } 493 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | obsidian-color-palette 635 | Copyright (C) 2023 ALegendsTale 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 2023 ALegendsTale 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------