mirror of
https://github.com/eliasstepanik/strudel-docker.git
synced 2026-01-11 21:58:31 +00:00
refactoring
This commit is contained in:
parent
f7fe44063a
commit
1ff7548b52
@ -16,18 +16,19 @@ import {
|
||||
setActivePattern,
|
||||
setLatestCode,
|
||||
settingsMap,
|
||||
updateUserCode,
|
||||
useSettings,
|
||||
getViewingPattern,
|
||||
setViewingPattern,
|
||||
getNextCloneName,
|
||||
createPatternID,
|
||||
userPattern,
|
||||
examplePattern,
|
||||
getNextCloneID,
|
||||
} from '../settings.mjs';
|
||||
import { Header } from './Header';
|
||||
import Loader from './Loader';
|
||||
import { Panel } from './panel/Panel';
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { prebake } from './prebake.mjs';
|
||||
import * as tunes from './tunes.mjs';
|
||||
import { getRandomTune, initCode, loadModules, shareCode } from './util.mjs';
|
||||
import PlayCircleIcon from '@heroicons/react/20/solid/PlayCircleIcon';
|
||||
import './Repl.css';
|
||||
@ -76,22 +77,26 @@ export function Repl({ embedded = false }) {
|
||||
},
|
||||
afterEval: ({ code }) => {
|
||||
setLatestCode(code);
|
||||
let pattern = getViewingPattern();
|
||||
const data = { code };
|
||||
let id = getViewingPattern();
|
||||
window.location.hash = '#' + code2hash(code);
|
||||
const isExamplePattern = !!tunes[pattern];
|
||||
const examplePatternData = examplePattern.getPatternData(id);
|
||||
const isExamplePattern = examplePatternData != null;
|
||||
|
||||
if (isExamplePattern) {
|
||||
const codeHasChanged = code !== tunes[pattern];
|
||||
const codeHasChanged = code !== examplePatternData.code;
|
||||
if (codeHasChanged) {
|
||||
// fork example
|
||||
pattern = getNextCloneName(pattern);
|
||||
setViewingPattern(pattern);
|
||||
updateUserCode(pattern, code);
|
||||
id = getNextCloneID(id);
|
||||
setViewingPattern(id);
|
||||
userPattern.update(id, data);
|
||||
}
|
||||
setActivePattern(pattern);
|
||||
setActivePattern(id);
|
||||
} else {
|
||||
setActivePattern(pattern);
|
||||
updateUserCode(pattern, code);
|
||||
id = id == null ? createPatternID() : id;
|
||||
setActivePattern(id);
|
||||
setViewingPattern(id);
|
||||
userPattern.update(id, data);
|
||||
}
|
||||
},
|
||||
bgFill: false,
|
||||
@ -159,21 +164,25 @@ export function Repl({ embedded = false }) {
|
||||
|
||||
// payload = {reset?: boolean, code?: string, evaluate?: boolean, pattern?: string }
|
||||
const handleUpdate = async (payload) => {
|
||||
const { reset = false, code = null, evaluate = true, pattern = null } = payload;
|
||||
const { id, code } = payload;
|
||||
setViewingPattern(id);
|
||||
editorRef.current.setCode(code);
|
||||
|
||||
if (reset) {
|
||||
clearCanvas();
|
||||
resetLoadedSounds();
|
||||
editorRef.current.repl.setCps(1);
|
||||
await prebake(); // declare default samples
|
||||
}
|
||||
if (code != null && pattern != null) {
|
||||
editorRef.current.setCode(code);
|
||||
setViewingPattern(pattern);
|
||||
}
|
||||
if (evaluate) {
|
||||
editorRef.current.evaluate();
|
||||
}
|
||||
// const { reset = false, code = null, evaluate = true, pattern = null } = payload;
|
||||
|
||||
// if (reset) {
|
||||
// clearCanvas();
|
||||
// resetLoadedSounds();
|
||||
// editorRef.current.repl.setCps(1);
|
||||
// await prebake(); // declare default samples
|
||||
// }
|
||||
// if (code != null && pattern != null) {
|
||||
// setViewingPattern(pattern);
|
||||
// editorRef.current.setCode(code);
|
||||
// }
|
||||
// if (evaluate) {
|
||||
// editorRef.current.evaluate();
|
||||
// }
|
||||
};
|
||||
const handleShuffle = async () => {
|
||||
// window.postMessage('strudel-shuffle');
|
||||
|
||||
@ -1,19 +1,15 @@
|
||||
import { DocumentDuplicateIcon, PencilSquareIcon, TrashIcon } from '@heroicons/react/20/solid';
|
||||
|
||||
import {
|
||||
clearUserPatterns,
|
||||
deletePattern,
|
||||
createDuplicatePattern,
|
||||
exportPatterns,
|
||||
addUserPattern,
|
||||
importPatterns,
|
||||
createNewUserPattern,
|
||||
renamePattern,
|
||||
useActivePattern,
|
||||
useViewingPattern,
|
||||
useSettings,
|
||||
userPattern,
|
||||
examplePattern,
|
||||
} from '../../settings.mjs';
|
||||
import * as tunes from '../tunes.mjs';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
function classNames(...classes) {
|
||||
return classes.filter(Boolean).join(' ');
|
||||
@ -34,16 +30,16 @@ function PatternButton({ showOutline, onClick, label, showHiglight }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PatternButtons({ patterns, activePattern, onClick, viewingPattern }) {
|
||||
function PatternButtons({ patterns, activePattern, onClick, viewingPattern, isExample = false }) {
|
||||
return (
|
||||
<div className="font-mono text-sm">
|
||||
{Object.entries(patterns).map(([key, data]) => (
|
||||
{Object.entries(patterns).map(([id]) => (
|
||||
<PatternButton
|
||||
key={key}
|
||||
label={key}
|
||||
showHiglight={key === viewingPattern}
|
||||
showOutline={key === activePattern}
|
||||
onClick={() => onClick(key, data)}
|
||||
key={id}
|
||||
label={id}
|
||||
showHiglight={id === viewingPattern}
|
||||
showOutline={id === activePattern}
|
||||
onClick={() => onClick(id, isExample)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@ -52,20 +48,20 @@ function PatternButtons({ patterns, activePattern, onClick, viewingPattern }) {
|
||||
|
||||
export function PatternsTab({ context }) {
|
||||
const { userPatterns } = useSettings();
|
||||
const examplePatterns = useMemo(() => examplePattern.getAll(), []);
|
||||
const activePattern = useActivePattern();
|
||||
const viewingPattern = useViewingPattern();
|
||||
const onPatternClick = (pattern, data) => {
|
||||
|
||||
const updateCodeWindow = (id, code) => {
|
||||
context.handleUpdate({ code, id, evaluate: false });
|
||||
};
|
||||
const onPatternBtnClick = (id, isExample) => {
|
||||
const code = isExample ? examplePatterns[id].code : userPatterns[id].code;
|
||||
|
||||
// display selected pattern code in the window
|
||||
context.handleUpdate({ pattern, code: data.code, evaluate: false });
|
||||
updateCodeWindow(id, code);
|
||||
};
|
||||
|
||||
const addPattern = ({ pattern, code }) => {
|
||||
addUserPattern(pattern, { code });
|
||||
context.handleUpdate({ code, pattern, evaluate: false });
|
||||
};
|
||||
|
||||
const examplePatterns = {};
|
||||
Object.entries(tunes).forEach(([key, code]) => (examplePatterns[key] = { code }));
|
||||
const isExample = examplePatterns[viewingPattern] != null;
|
||||
return (
|
||||
<div className="px-4 w-full dark:text-white text-stone-900 space-y-4 pb-4">
|
||||
@ -75,14 +71,27 @@ export function PatternsTab({ context }) {
|
||||
<h1 className="text-xl">{viewingPattern}</h1>
|
||||
<div className="space-x-4 flex w-min">
|
||||
{!isExample && (
|
||||
<button className="hover:opacity-50" onClick={() => renamePattern(viewingPattern)} title="Rename">
|
||||
<button
|
||||
className="hover:opacity-50"
|
||||
onClick={() => {
|
||||
const { id, data } = userPattern.rename(viewingPattern);
|
||||
updateCodeWindow(id, data.code);
|
||||
}}
|
||||
title="Rename"
|
||||
>
|
||||
<PencilSquareIcon className="w-5 h-5" />
|
||||
{/* <PencilIcon className="w-5 h-5" /> */}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="hover:opacity-50"
|
||||
onClick={() => addPattern(createDuplicatePattern(viewingPattern))}
|
||||
onClick={() => {
|
||||
const { id, data } = userPattern.duplicate(
|
||||
viewingPattern,
|
||||
userPatterns[viewingPattern]?.code ?? examplePatterns[viewingPattern]?.code,
|
||||
);
|
||||
updateCodeWindow(id, data.code);
|
||||
}}
|
||||
title="Duplicate"
|
||||
>
|
||||
<DocumentDuplicateIcon className="w-5 h-5" />
|
||||
@ -91,8 +100,9 @@ export function PatternsTab({ context }) {
|
||||
<button
|
||||
className="hover:opacity-50"
|
||||
onClick={() => {
|
||||
const { code, pattern } = deletePattern(viewingPattern);
|
||||
context.handleUpdate({ code, pattern, evaluate: false });
|
||||
const { id, data } = userPattern.delete(viewingPattern);
|
||||
console.log({ id, data });
|
||||
updateCodeWindow(id, data.code);
|
||||
}}
|
||||
title="Delete"
|
||||
>
|
||||
@ -103,7 +113,7 @@ export function PatternsTab({ context }) {
|
||||
</div>
|
||||
)}
|
||||
<PatternButtons
|
||||
onClick={onPatternClick}
|
||||
onClick={onPatternBtnClick}
|
||||
patterns={userPatterns}
|
||||
activePattern={activePattern}
|
||||
viewingPattern={viewingPattern}
|
||||
@ -112,12 +122,19 @@ export function PatternsTab({ context }) {
|
||||
<button
|
||||
className="hover:opacity-50"
|
||||
onClick={() => {
|
||||
addPattern(createNewUserPattern());
|
||||
const { id, data } = userPattern.create();
|
||||
updateCodeWindow(id, data.code);
|
||||
}}
|
||||
>
|
||||
new
|
||||
</button>
|
||||
<button className="hover:opacity-50" onClick={() => clearUserPatterns()}>
|
||||
<button
|
||||
className="hover:opacity-50"
|
||||
onClick={() => {
|
||||
const { id, data } = userPattern.clearAll();
|
||||
updateCodeWindow(id, data.code);
|
||||
}}
|
||||
>
|
||||
clear
|
||||
</button>
|
||||
<label className="hover:opacity-50 cursor-pointer">
|
||||
@ -138,7 +155,8 @@ export function PatternsTab({ context }) {
|
||||
<section>
|
||||
<h2 className="text-xl mb-2">Examples</h2>
|
||||
<PatternButtons
|
||||
onClick={onPatternClick}
|
||||
isExample={true}
|
||||
onClick={onPatternBtnClick}
|
||||
patterns={examplePatterns}
|
||||
activePattern={activePattern}
|
||||
viewingPattern={viewingPattern}
|
||||
|
||||
@ -3,6 +3,7 @@ import { useStore } from '@nanostores/react';
|
||||
import { register } from '@strudel.cycles/core';
|
||||
import { defaultAudioDeviceName } from './repl/panel/AudioDeviceSelector';
|
||||
import { logger } from '@strudel.cycles/core';
|
||||
import * as tunes from './repl/tunes.mjs';
|
||||
|
||||
export const defaultSettings = {
|
||||
activeFooter: 'intro',
|
||||
@ -27,6 +28,7 @@ export const defaultSettings = {
|
||||
|
||||
export const settingsMap = persistentMap('strudel-settings', defaultSettings);
|
||||
|
||||
const defaultCode = '';
|
||||
//pattern that the use is currently viewing in the window
|
||||
const $viewingPattern = persistentAtom('viewingPattern', '', { listen: false });
|
||||
export function setViewingPattern(key) {
|
||||
@ -54,7 +56,9 @@ export function useActivePattern() {
|
||||
export function initUserCode(code) {
|
||||
const userPatterns = getUserPatterns();
|
||||
const match = Object.entries(userPatterns).find(([_, pat]) => pat.code === code);
|
||||
setActivePattern(match?.[0] || '');
|
||||
const id = match?.[0] || '';
|
||||
setActivePattern(id);
|
||||
setViewingPattern(id);
|
||||
}
|
||||
|
||||
export function useSettings() {
|
||||
@ -105,128 +109,116 @@ function getSetting(key) {
|
||||
}
|
||||
|
||||
export function setUserPatterns(obj) {
|
||||
settingsMap.setKey('userPatterns', JSON.stringify(obj));
|
||||
return settingsMap.setKey('userPatterns', JSON.stringify(obj));
|
||||
}
|
||||
|
||||
export function addUserPattern(name, config) {
|
||||
if (typeof config !== 'object') {
|
||||
throw new Error('addUserPattern expected object as second param');
|
||||
}
|
||||
if (!config.code) {
|
||||
throw new Error('addUserPattern expected code as property of second param');
|
||||
}
|
||||
const userPatterns = getUserPatterns();
|
||||
setUserPatterns({ ...userPatterns, [name]: config });
|
||||
}
|
||||
|
||||
export function createNewUserPattern() {
|
||||
export const createPatternID = () => {
|
||||
const userPatterns = getUserPatterns();
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
const todays = Object.entries(userPatterns).filter(([name]) => name.startsWith(date));
|
||||
const num = String(todays.length + 1).padStart(3, '0');
|
||||
const pattern = date + '_' + num;
|
||||
const code = 's("hh")';
|
||||
return { pattern, code };
|
||||
}
|
||||
const id = date + '_' + num;
|
||||
return id;
|
||||
};
|
||||
|
||||
export function clearUserPatterns() {
|
||||
if (!confirm(`This will delete all your patterns. Are you really sure?`)) {
|
||||
return;
|
||||
}
|
||||
setUserPatterns({});
|
||||
}
|
||||
|
||||
export function getNextCloneName(key) {
|
||||
const userPatterns = getUserPatterns();
|
||||
const clones = Object.entries(userPatterns).filter(([name]) => name.startsWith(key));
|
||||
export const getNextCloneID = (id) => {
|
||||
const userPatterns = this.getAll();
|
||||
const clones = Object.entries(userPatterns).filter(([patID]) => patID.startsWith(id));
|
||||
const num = String(clones.length + 1).padStart(3, '0');
|
||||
return key + '_' + num;
|
||||
}
|
||||
const newID = id + '_' + num;
|
||||
return newID;
|
||||
};
|
||||
|
||||
export function getUserPattern(key) {
|
||||
const userPatterns = getUserPatterns();
|
||||
return userPatterns[key];
|
||||
}
|
||||
export const examplePattern = {
|
||||
getAll() {
|
||||
const examplePatterns = {};
|
||||
Object.entries(tunes).forEach(([key, code]) => (examplePatterns[key] = { code }));
|
||||
return examplePatterns;
|
||||
},
|
||||
getPatternData(id) {
|
||||
const userPatterns = this.getAll();
|
||||
return userPatterns[id];
|
||||
},
|
||||
};
|
||||
|
||||
export function renamePattern(pattern) {
|
||||
let userPatterns = getUserPatterns();
|
||||
if (!userPatterns[pattern]) {
|
||||
alert('Cannot rename examples');
|
||||
return;
|
||||
}
|
||||
const newName = prompt('Enter new name', pattern);
|
||||
if (newName === null) {
|
||||
// canceled
|
||||
return;
|
||||
}
|
||||
if (userPatterns[newName]) {
|
||||
alert('Name already taken!');
|
||||
return;
|
||||
}
|
||||
userPatterns[newName] = userPatterns[pattern]; // copy code
|
||||
delete userPatterns[pattern];
|
||||
setUserPatterns({ ...userPatterns });
|
||||
setViewingPattern(newName);
|
||||
}
|
||||
export const userPattern = {
|
||||
getAll() {
|
||||
return JSON.parse(settingsMap.get().userPatterns);
|
||||
},
|
||||
getPatternData(id) {
|
||||
const userPatterns = this.getAll();
|
||||
return userPatterns[id];
|
||||
},
|
||||
exists(id) {
|
||||
const userPatterns = this.getAll();
|
||||
return userPatterns[id] != null;
|
||||
},
|
||||
create() {
|
||||
const newID = createPatternID();
|
||||
const code = defaultCode;
|
||||
const data = { code };
|
||||
this.update(newID, data);
|
||||
return { id: newID, data };
|
||||
},
|
||||
update(id, data) {
|
||||
const userPatterns = this.getAll();
|
||||
setUserPatterns({ ...userPatterns, [id]: data });
|
||||
},
|
||||
duplicate(id, data) {
|
||||
const newID = getNextCloneID(id);
|
||||
this.update(newID, data);
|
||||
return { id: newID, data };
|
||||
},
|
||||
clearAll() {
|
||||
if (!confirm(`This will delete all your patterns. Are you really sure?`)) {
|
||||
return;
|
||||
}
|
||||
const viewingPattern = getViewingPattern();
|
||||
const examplePatternData = examplePattern.getPatternData(viewingPattern);
|
||||
setUserPatterns({});
|
||||
if (examplePatternData != null) {
|
||||
return { id: viewingPattern, data: examplePatternData };
|
||||
}
|
||||
setViewingPattern(null);
|
||||
setActivePattern(null);
|
||||
return { id: null, data: { code: '' } };
|
||||
},
|
||||
delete(id) {
|
||||
const userPatterns = this.getAll();
|
||||
const updatedPatterns = Object.fromEntries(Object.entries(userPatterns).filter(([key]) => key !== id));
|
||||
if (getActivePattern() === id) {
|
||||
setActivePattern(null);
|
||||
}
|
||||
setUserPatterns(updatedPatterns);
|
||||
const viewingPattern = getViewingPattern();
|
||||
if (viewingPattern === id) {
|
||||
return this.create();
|
||||
}
|
||||
return { id: viewingPattern, data: updatedPatterns[id] };
|
||||
},
|
||||
|
||||
export function updateUserCode(pattern, code) {
|
||||
const userPatterns = getUserPatterns();
|
||||
setUserPatterns({ ...userPatterns, [pattern]: { code } });
|
||||
}
|
||||
rename(id) {
|
||||
const userPatterns = this.getAll();
|
||||
const newID = prompt('Enter new name', id);
|
||||
if (newID === null) {
|
||||
// canceled
|
||||
return;
|
||||
}
|
||||
if (userPatterns[newID]) {
|
||||
alert('Name already taken!');
|
||||
return;
|
||||
}
|
||||
const data = userPatterns[id];
|
||||
userPatterns[newID] = data; // copy code
|
||||
delete userPatterns[id];
|
||||
|
||||
export function deletePattern(pattern) {
|
||||
if (!pattern) {
|
||||
console.warn('cannot delete: no pattern selected');
|
||||
return;
|
||||
}
|
||||
const userPatterns = getUserPatterns();
|
||||
if (!userPatterns[pattern]) {
|
||||
alert('Cannot delete examples');
|
||||
return;
|
||||
}
|
||||
if (!confirm(`Really delete the selected pattern "${pattern}"?`)) {
|
||||
return;
|
||||
}
|
||||
// const updatedPatterns = Object.fromEntries(Object.entries(userPatterns).filter(([key]) => key !== pattern));
|
||||
let patternsArray = Object.entries(userPatterns).sort((a, b) => a[0].localeCompare(b[0]));
|
||||
const deleteIndex = patternsArray.findIndex(([key]) => key === pattern);
|
||||
patternsArray.splice(deleteIndex, 1);
|
||||
const updatedPatterns = Object.fromEntries(patternsArray);
|
||||
|
||||
setUserPatterns(updatedPatterns);
|
||||
|
||||
//create new pattern if no other patterns
|
||||
if (!patternsArray.length) {
|
||||
return createNewUserPattern();
|
||||
}
|
||||
// // or default to active pattern
|
||||
// const activePatternID = getActivePattern();
|
||||
// const activePatternData = updatedPatterns[activePatternID];
|
||||
// if (activePatternData?.code != null) {
|
||||
// return { pattern: activePatternID, code: activePatternData.code };
|
||||
// }
|
||||
// or find pattern at next index
|
||||
|
||||
const next = patternsArray[deleteIndex];
|
||||
if (next != null) {
|
||||
const [pat, data] = next;
|
||||
return { pattern: pat, code: data.code };
|
||||
}
|
||||
// or find pattern at previous index
|
||||
const previous = patternsArray[deleteIndex - 1];
|
||||
const [pat, data] = previous;
|
||||
return { patttern: pat, code: data.code };
|
||||
}
|
||||
|
||||
export function createDuplicatePattern(pattern) {
|
||||
let latestCode = getSetting('latestCode');
|
||||
if (!pattern) {
|
||||
console.warn('cannot duplicate: no pattern selected');
|
||||
return;
|
||||
}
|
||||
const newPattern = getNextCloneName(pattern);
|
||||
return { pattern: newPattern, code: latestCode };
|
||||
}
|
||||
setUserPatterns({ ...userPatterns });
|
||||
if (id === getActivePattern()) {
|
||||
setActivePattern(newID);
|
||||
}
|
||||
return { id: newID, data };
|
||||
},
|
||||
};
|
||||
|
||||
export async function importPatterns(fileList) {
|
||||
const files = Array.from(fileList);
|
||||
@ -237,8 +229,8 @@ export async function importPatterns(fileList) {
|
||||
const userPatterns = getUserPatterns() || {};
|
||||
setUserPatterns({ ...userPatterns, ...JSON.parse(content) });
|
||||
} else if (file.type === 'text/plain') {
|
||||
const name = file.name.replace(/\.[^/.]+$/, '');
|
||||
addUserPattern(name, { code: content });
|
||||
const id = file.name.replace(/\.[^/.]+$/, '');
|
||||
userPattern.update(id, { code: content });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user