MCPcopy Create free account
hub / github.com/32comic/image2pixel-web / parseJsonPalette

Function parseJsonPalette

web/js/main.js:696–755  ·  view source on GitHub ↗
(text, name)

Source from the content-addressed store, hash-verified

694}
695
696function parseJsonPalette(text, name) {
697 let data;
698 try {
699 data = JSON.parse(text);
700 } catch {
701 throw new Error('Invalid JSON format');
702 }
703
704 let colors = [];
705 let paletteName = name.replace(/\.[^.]+$/, '');
706
707 // Array of palette objects: [{id, colors}, ...]
708 if (Array.isArray(data) && data[0] && Array.isArray(data[0].colors)) {
709 data = data[0];
710 }
711
712 // Single palette object
713 if (data.id) paletteName = data.id;
714 if (data.name) paletteName = data.name;
715 if (data.displayName) paletteName = data.displayName;
716
717 if (Array.isArray(data.colors)) {
718 const first = data.colors[0];
719 if (Array.isArray(first) && first.length >= 3) {
720 colors = data.colors.map(c => [
721 Math.min(255, Math.max(0, parseInt(c[0]) || 0)),
722 Math.min(255, Math.max(0, parseInt(c[1]) || 0)),
723 Math.min(255, Math.max(0, parseInt(c[2]) || 0)),
724 ]);
725 } else if (typeof first === 'string') {
726 for (const hex of data.colors) {
727 const rgb = hexToRgb(hex);
728 if (rgb) colors.push(rgb);
729 }
730 } else if (first && typeof first === 'object') {
731 colors = data.colors.map(c => [
732 Math.min(255, Math.max(0, parseInt(c.r ?? c.red ?? c[0]) || 0)),
733 Math.min(255, Math.max(0, parseInt(c.g ?? c.green ?? c[1]) || 0)),
734 Math.min(255, Math.max(0, parseInt(c.b ?? c.blue ?? c[2]) || 0)),
735 ]);
736 }
737 } else if (Array.isArray(data) && data.length > 0) {
738 const first = data[0];
739 if (Array.isArray(first) && first.length >= 3) {
740 colors = data.map(c => [
741 Math.min(255, Math.max(0, parseInt(c[0]) || 0)),
742 Math.min(255, Math.max(0, parseInt(c[1]) || 0)),
743 Math.min(255, Math.max(0, parseInt(c[2]) || 0)),
744 ]);
745 } else if (typeof first === 'string') {
746 for (const hex of data) {
747 const rgb = hexToRgb(hex);
748 if (rgb) colors.push(rgb);
749 }
750 }
751 }
752
753 if (colors.length < 2) throw new Error('Palette must contain at least 2 colors');

Callers 1

parsePaletteFileFunction · 0.85

Calls 1

hexToRgbFunction · 0.85

Tested by

no test coverage detected