UNPKG

@trap_stevo/legendarybuilderproreact-ui

Version:

The legendary UI & utility API that makes your application a legendary application. ~ Created by Steven Compton

317 lines 15 kB
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } import React, { createContext, useContext, useState, useEffect, useRef } from "react"; import colorNameList from "color-name-list"; import ColorHash from "color-hash"; import chroma from "chroma-js"; var ColorPaletteContext = /*#__PURE__*/createContext(); var getRandomColor = function getRandomColor() { return chroma.random().hex(); }; var getColorFromKeyword = function getColorFromKeyword(keyword) { var colorHash = new ColorHash(); var foundColor = colorNameList.find(function (color) { return color.name.toLowerCase() === keyword.toLowerCase(); }); return foundColor ? foundColor.hex : colorHash.hex(keyword); }; export var getRGB = function getRGB(color) { if (!color) { return null; } if (color.startsWith("#")) { var hex = color.replace("#", ""); if (hex.length === 3) { hex = hex.split("").map(function (c) { return c + c; }).join(""); } var bigint = parseInt(hex, 16); return [bigint >> 16 & 255, bigint >> 8 & 255, bigint & 255]; } var ctx = document.createElement("canvas").getContext("2d"); ctx.fillStyle = color; var computedColor = ctx.fillStyle; if (computedColor.startsWith("#")) { return getRGB(computedColor); } if (computedColor.startsWith("rgb")) { return computedColor.match(/\d+/g).map(Number); } return null; }; var fillerWords = new Set(["the", "with", "and", "be", "for", "to", "of", "a", "in", "on", "at", "by", "an", "as", "is", "it", "or", "that", "this", "these", "those", "which", "who", "whom", "whose", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "just", "but", "if", "now", "about", "above", "after", "again", "against", "along", "among", "around", "because", "before", "behind", "below", "beneath", "beside", "between", "beyond", "during", "except", "inside", "near", "outside", "over", "through", "under", "until", "up", "upon", "while", "into", "like", "since", "without", "can", "could", "shall", "should", "would", "will", "may", "might", "must"]); var parseSeedColors = function parseSeedColors(seedColor) { var knownColors = new Set(colorNameList.map(function (color) { return color.name.toLowerCase(); })); var colorPatterns = /rgba?\(([^)]+)\)|hsva?\(([^)]+)\)|#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/g; var parts = seedColor.split(/\s+/).filter(function (part) { return !fillerWords.has(part.toLowerCase()); }); var colors = []; var buffer = ""; parts.forEach(function (part) { var lowerPart = part.toLowerCase(); if (knownColors.has(lowerPart)) { if (buffer) { colors.push(getColorFromKeyword(buffer.trim())); buffer = ""; } colors.push(getColorFromKeyword(lowerPart)); } else if (colorPatterns.test(part)) { if (buffer) { colors.push(getColorFromKeyword(buffer.trim())); buffer = ""; } colors.push(part.match(colorPatterns)[0]); } else { buffer += " ".concat(part); } }); if (buffer) { colors.push(getColorFromKeyword(buffer.trim())); } return colors; }; var mutateColor = function mutateColor(color, step, range) { var currentHue = chroma(color).get("hsl.h"); var newHue = currentHue + step; if (newHue > range.max) { newHue = range.min + (newHue - range.max); } else if (newHue < range.min) { newHue = range.max - (range.min - newHue); } return chroma(color).set("hsl.h", newHue).hex(); }; var defaultPresets = { dark: function dark(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).brighten(0.5).hex(); }); return componentMapping; }, light: function light(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).darken(0.5).hex(); }); return componentMapping; }, ocean: function ocean(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).brighten(0.5).hex(); }); return componentMapping; }, forest: function forest(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).brighten(0.5).hex(); }); return componentMapping; }, sunset: function sunset(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).brighten(0.5).hex(); }); return componentMapping; }, modern: function modern(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).darken(0.2).hex(); }); return componentMapping; }, futuristic: function futuristic(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).saturate(1.5).hex(); }); return componentMapping; }, "default": function _default(colors) { var componentMapping = {}; colors.forEach(function (color, index) { componentMapping["color".concat(index + 1)] = color; componentMapping["hoverColor".concat(index + 1)] = chroma(color).brighten(0.5).hex(); }); return componentMapping; } }; export var adjustColor = function adjustColor(color) { var adjustments = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _options$space = options.space, space = _options$space === void 0 ? "hsl" : _options$space, _options$clamp = options.clamp, clamp = _options$clamp === void 0 ? true : _options$clamp; var adjustedColor = chroma(color); var alpha = adjustedColor.alpha(); Object.keys(adjustments).forEach(function (attr) { var value; if (attr === "a") { value = alpha + adjustments[attr]; if (clamp) { value = Math.max(0, Math.min(1, value)); } alpha = value; } else { value = adjustedColor.get("".concat(space, ".").concat(attr)); if (typeof adjustments[attr] !== "number") { throw new Error("Adjustment for ".concat(attr, " must be a number.")); } value += adjustments[attr]; if (clamp) { if (space === "rgb") { value = Math.max(0, Math.min(255, value)); } else if (space === "hsl" || space === "lab" || space === "lch") { if (attr === "h") { value = (value + 360) % 360; } else { value = Math.max(0, Math.min(1, value)); } } } adjustedColor = adjustedColor.set("".concat(space, ".").concat(attr), value); } }); return chroma(adjustedColor).alpha(alpha).css(); }; export var colorTransparency = function colorTransparency(color, alpha) { return chroma(color).alpha(alpha).css(); }; export var lightenColor = function lightenColor(hex, percent) { var num = parseInt(hex.slice(1), 16); var r = Math.min(255, Math.floor((num >> 16) + 255 * percent)); var g = Math.min(255, Math.floor((num >> 8 & 0x00ff) + 255 * percent)); var b = Math.min(255, Math.floor((num & 0x0000ff) + 255 * percent)); return "rgb(".concat(r, ", ").concat(g, ", ").concat(b, ")"); }; var paletteColor = function paletteColor(palette, key) { var loadingColor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "#cccccc"; var keys = key.split("."); var color = palette; var _iterator = _createForOfIteratorHelper(keys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var k = _step.value; if (color && color.hasOwnProperty(k)) { color = color[k]; } else { return loadingColor; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return color; }; export var HUDPaletteProvider = function HUDPaletteProvider(_ref) { var children = _ref.children, _ref$customPresets = _ref.customPresets, customPresets = _ref$customPresets === void 0 ? {} : _ref$customPresets; var paletteRef = useRef({}); var _useState = useState(paletteRef.current), _useState2 = _slicedToArray(_useState, 2), palette = _useState2[0], setPalette = _useState2[1]; var _useState3 = useState(false), _useState4 = _slicedToArray(_useState3, 2), paletteMutating = _useState4[0], setPaletteMutating = _useState4[1]; var colorMutationIntervalRef = useRef(null); var presets = _objectSpread(_objectSpread({}, defaultPresets), customPresets); var generatePalette = function generatePalette(n, inputColor, seedColor) { var lightMode = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; var theme = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "default"; var paletteName = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : "Interface"; var baseColors; if (inputColor) { baseColors = [inputColor]; } else if (seedColor) { baseColors = parseSeedColors(seedColor); } else { baseColors = [getRandomColor()]; } var colors = lightMode ? chroma.scale([].concat(_toConsumableArray(baseColors), ['white'])).mode('lab').colors(n) : chroma.scale([].concat(_toConsumableArray(baseColors), ['black'])).mode('lab').colors(n); var componentColors = presets[theme] ? presets[theme](colors) : presets["default"](colors); paletteRef.current = _objectSpread(_objectSpread({}, paletteRef.current), {}, _defineProperty({}, paletteName, componentColors)); syncPalette(); return; }; var startPaletteMutating = function startPaletteMutating() { var step = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; var colorsToMutate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var range = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { min: 0, max: 360 }; var paletteName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "Interface"; setPaletteMutating(true); var mutate = function mutate() { if (!paletteMutating) return; var mutatedPalette = _objectSpread({}, paletteRef.current[paletteName]); var keys = colorsToMutate || Object.keys(mutatedPalette); keys.forEach(function (key) { mutatedPalette[key] = mutateColor(mutatedPalette[key], step, range); }); paletteRef.current = _objectSpread(_objectSpread({}, paletteRef.current), {}, _defineProperty({}, paletteName, mutatedPalette)); syncPalette(); colorMutationIntervalRef.current = requestAnimationFrame(mutate); }; colorMutationIntervalRef.current = requestAnimationFrame(mutate); }; var stopPaletteMutating = function stopPaletteMutating() { setPaletteMutating(false); cancelAnimationFrame(colorMutationIntervalRef.current); }; var syncPalette = function syncPalette() { console.log("Syncing palette..."); setPalette(_objectSpread({}, paletteRef.current)); console.log("Synced palette!"); return; }; useEffect(function () { syncPalette(); return function () { return cancelAnimationFrame(colorMutationIntervalRef.current); }; }, []); return /*#__PURE__*/React.createElement(ColorPaletteContext.Provider, { value: { palette: palette, paletteColor: paletteColor, colorTransparency: colorTransparency, adjustColor: adjustColor, lightenColor: lightenColor, generatePalette: generatePalette, startPaletteMutating: startPaletteMutating, stopPaletteMutating: stopPaletteMutating, paletteMutating: paletteMutating } }, children); }; export var useHUDPalette = function useHUDPalette() { return useContext(ColorPaletteContext); };