Merge pull request 'Edit prebake in settings' (#1958) from JohnBjrk/strudel:edit-prebake-in-settings into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1958
This commit is contained in:
commit
6f108f7f28
18 changed files with 338 additions and 119 deletions
|
|
@ -17,6 +17,11 @@
|
|||
"@astrojs/react": "^4.1.6",
|
||||
"@astrojs/rss": "^4.0.11",
|
||||
"@astrojs/tailwind": "^5.1.5",
|
||||
"@codemirror/commands": "catalog:",
|
||||
"@codemirror/language": "catalog:",
|
||||
"@codemirror/lang-javascript": "catalog:",
|
||||
"@codemirror/state": "catalog:",
|
||||
"@codemirror/view": "catalog:",
|
||||
"@docsearch/css": "^3.8.3",
|
||||
"@docsearch/react": "^3.8.3",
|
||||
"@headlessui/react": "^2.2.0",
|
||||
|
|
|
|||
|
|
@ -10,50 +10,50 @@
|
|||
opacity: 0.5;
|
||||
}
|
||||
|
||||
#code .cm-scroller {
|
||||
.code-container .cm-scroller {
|
||||
padding-top: 10px !important;
|
||||
height: 100%;
|
||||
font-family: inherit;
|
||||
}
|
||||
#code .cm-content {
|
||||
.code-container .cm-content {
|
||||
padding-bottom: 50vh;
|
||||
}
|
||||
#code .cm-line > * {
|
||||
.code-container .cm-line > * {
|
||||
background: var(--lineBackground);
|
||||
}
|
||||
|
||||
#code .cm-editor {
|
||||
.code-container .cm-editor {
|
||||
background-color: transparent !important;
|
||||
height: 100%;
|
||||
z-index: 11;
|
||||
}
|
||||
|
||||
#code .cm-theme {
|
||||
.code-container .cm-theme {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
#code .cm-theme-light {
|
||||
.code-container .cm-theme-light {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#code .cm-cursorLayer {
|
||||
.code-container .cm-cursorLayer {
|
||||
animation-name: inherit !important;
|
||||
}
|
||||
|
||||
#code .cm-cursor {
|
||||
.code-container .cm-cursor {
|
||||
border-left: 2px solid currentcolor !important;
|
||||
}
|
||||
|
||||
#code .cm-foldGutter {
|
||||
.code-container .cm-foldGutter {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
#code .cm-focused {
|
||||
.code-container .cm-focused {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#code .cm-matchingBracket {
|
||||
.code-container .cm-matchingBracket {
|
||||
text-decoration: underline 0.18rem;
|
||||
text-underline-offset: 0.22rem;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,7 @@ export function Code(Props) {
|
|||
|
||||
return (
|
||||
<section
|
||||
className={'text-gray-100 cursor-text pb-0 overflow-auto grow z-10'}
|
||||
id="code"
|
||||
className={'code-container text-gray-100 cursor-text pb-0 overflow-auto grow z-10'}
|
||||
ref={(el) => {
|
||||
containerRef.current = el;
|
||||
if (!editorRef.current) {
|
||||
|
|
|
|||
|
|
@ -8,31 +8,3 @@ export function ActionButton({ children, label, labelIsHidden, className, ...but
|
|||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function SpecialActionButton(props) {
|
||||
const { className, ...buttonProps } = props;
|
||||
|
||||
return (
|
||||
<ActionButton {...buttonProps} className={cx('bg-background p-2 max-w-[300px] hover:opacity-50', className)} />
|
||||
);
|
||||
}
|
||||
|
||||
export function ActionInput({ label, className, ...props }) {
|
||||
return (
|
||||
<label className={cx('inline-flex items-center cursor-pointer ', className)}>
|
||||
<input {...props} className="sr-only peer" />
|
||||
|
||||
<span className="inline-flex items-center peer-hover:opacity-50">{label}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function SpecialActionInput({ className, ...props }) {
|
||||
return (
|
||||
<ActionInput
|
||||
{...props}
|
||||
className={className}
|
||||
label={<span className="bg-background p-2 max-w-[300px]">{props.label}</span>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,42 +1,50 @@
|
|||
import { errorLogger } from '@strudel/core';
|
||||
import { useSettings, storePrebakeScript } from '../../../settings.mjs';
|
||||
import { SpecialActionInput } from '../button/action-button';
|
||||
import { confirmDialog, SETTING_CHANGE_RELOAD_MSG } from '@src/repl/util.mjs';
|
||||
import { storePrebakeScript } from '../../../settings.mjs';
|
||||
import { confirmDialog } from '@src/repl/util.mjs';
|
||||
|
||||
async function importScript(script) {
|
||||
async function importScript(script, updateEditor) {
|
||||
const reader = new FileReader();
|
||||
reader.readAsText(script);
|
||||
|
||||
reader.onload = () => {
|
||||
const text = reader.result;
|
||||
storePrebakeScript(text);
|
||||
updateEditor && updateEditor(text);
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
errorLogger(new Error('failed to import prebake script'), 'importScript');
|
||||
};
|
||||
}
|
||||
export function ImportPrebakeScriptButton() {
|
||||
const settings = useSettings();
|
||||
|
||||
export async function exportScript(script) {
|
||||
const blob = new Blob([script], { type: 'application/javascript' });
|
||||
const downloadLink = document.createElement('a');
|
||||
downloadLink.href = window.URL.createObjectURL(blob);
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
downloadLink.download = `prebake_${date}.strudel`;
|
||||
document.body.appendChild(downloadLink);
|
||||
downloadLink.click();
|
||||
document.body.removeChild(downloadLink);
|
||||
}
|
||||
|
||||
export function ImportPrebakeScriptButton({ updateEditor }) {
|
||||
const handleChange = async (e) => {
|
||||
const file = e.target.files[0];
|
||||
const confirmed = await confirmDialog('Warning: This will overwrite the current prebake.\nContinue?');
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await importScript(file, updateEditor);
|
||||
} catch (e) {
|
||||
errorLogger(e);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<SpecialActionInput
|
||||
type="file"
|
||||
label="import prebake script"
|
||||
accept=".strudel"
|
||||
onChange={async (e) => {
|
||||
const file = e.target.files[0];
|
||||
const confirmed = await confirmDialog(SETTING_CHANGE_RELOAD_MSG);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await importScript(file);
|
||||
window.location.reload();
|
||||
} catch (e) {
|
||||
errorLogger(e);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<label className="space-x-1 inline-flex items-center cursor-pointer">
|
||||
<input type="file" accept=".strudel,.js" className="sr-only peer" onChange={handleChange} />
|
||||
<span className="inline-flex items-center peer-hover:opacity-50 text-xs max-w-[300px]">import</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,18 +1,16 @@
|
|||
import { defaultSettings, settingsMap, useSettings } from '../../../settings.mjs';
|
||||
import { defaultSettings, settingsMap, useSettings, storePrebakeScript, setSettingsTab } from '../../../settings.mjs';
|
||||
import { themes } from '@strudel/codemirror';
|
||||
import { PrebakeCodeMirror } from '../../../repl/prebakeCodeMirror.mjs';
|
||||
import { confirmAndReloadPage, isUdels } from '../../util.mjs';
|
||||
import { ButtonGroup } from './Forms.jsx';
|
||||
import { AudioDeviceSelector } from './AudioDeviceSelector.jsx';
|
||||
import { AudioEngineTargetSelector } from './AudioEngineTargetSelector.jsx';
|
||||
import { confirmDialog } from '../../util.mjs';
|
||||
import { DEFAULT_MAX_POLYPHONY, setMaxPolyphony, setMultiChannelOrbits } from '@strudel/webaudio';
|
||||
import { SpecialActionButton } from '../button/action-button.jsx';
|
||||
import { ImportPrebakeScriptButton } from './ImportPrebakeScriptButton.jsx';
|
||||
|
||||
function cx(...classes) {
|
||||
// : Array<string | undefined>
|
||||
return classes.filter(Boolean).join(' ');
|
||||
}
|
||||
import { ActionButton } from '../button/action-button.jsx';
|
||||
import { exportScript, ImportPrebakeScriptButton } from './ImportPrebakeScriptButton.jsx';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import cx from '@src/cx.mjs';
|
||||
|
||||
const inputClass =
|
||||
'bg-background text-xs h-8 max-h-8 border border-box rounded-0 text-foreground border-muted placeholder-muted focus:outline-none focus:ring-0 focus:border-foreground';
|
||||
|
|
@ -123,7 +121,7 @@ const fontFamilyOptions = {
|
|||
galactico: 'galactico',
|
||||
};
|
||||
|
||||
export function SettingsTab({ started }) {
|
||||
function MainSettingsContent({ started }) {
|
||||
const {
|
||||
theme,
|
||||
keybindings,
|
||||
|
|
@ -149,13 +147,12 @@ export function SettingsTab({ started }) {
|
|||
isTabIndentationEnabled,
|
||||
isMultiCursorEnabled,
|
||||
patternAutoStart,
|
||||
includePrebakeScriptInShare,
|
||||
isBlockBasedEvalEnabled,
|
||||
} = useSettings();
|
||||
const shouldAlwaysSync = isUdels();
|
||||
const canChangeAudioDevice = AudioContext.prototype.setSinkId != null;
|
||||
return (
|
||||
<div className="p-4 text-foreground space-y-4 w-full" style={{ fontFamily }}>
|
||||
<div className="p-4 text-foreground space-y-4 w-full overflow-auto" style={{ fontFamily }}>
|
||||
{canChangeAudioDevice && (
|
||||
<FormItem label="Audio Output Device">
|
||||
<AudioDeviceSelector
|
||||
|
|
@ -233,14 +230,6 @@ export function SettingsTab({ started }) {
|
|||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
<FormItem label="Prebake">
|
||||
<ImportPrebakeScriptButton />
|
||||
<Checkbox
|
||||
label="Include prebake script in share"
|
||||
onChange={(cbEvent) => settingsMap.setKey('includePrebakeScriptInShare', cbEvent.target.checked)}
|
||||
value={includePrebakeScriptInShare}
|
||||
/>
|
||||
</FormItem>
|
||||
|
||||
<FormItem label="Keybindings">
|
||||
<ButtonGroup
|
||||
|
|
@ -346,7 +335,7 @@ export function SettingsTab({ started }) {
|
|||
</FormItem>
|
||||
<FormItem label="Zen Mode">Try clicking the logo in the top left!</FormItem>
|
||||
<FormItem label="Reset Settings">
|
||||
<SpecialActionButton
|
||||
<ActionButton
|
||||
onClick={() => {
|
||||
confirmDialog('Sure?').then((r) => {
|
||||
if (r) {
|
||||
|
|
@ -355,10 +344,70 @@ export function SettingsTab({ started }) {
|
|||
}
|
||||
});
|
||||
}}
|
||||
className="bg-background p-2 max-w-[300px] hover:opacity-50"
|
||||
>
|
||||
restore default settings
|
||||
</SpecialActionButton>
|
||||
</ActionButton>
|
||||
</FormItem>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PrebakeSettingsContent() {
|
||||
const { fontFamily, includePrebakeScriptInShare, prebakeScript } = useSettings();
|
||||
const editorRef = useRef();
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
editorRef.current?.cleanup();
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full text-foreground w-full overflow-auto" style={{ fontFamily }}>
|
||||
<div className="flex flex-col grow overflow-hidden h-full bg-background">
|
||||
<section
|
||||
className="pb-0 overflow-auto grow z-10 code-container"
|
||||
ref={(el) => {
|
||||
if (editorRef.current) {
|
||||
return;
|
||||
}
|
||||
editorRef.current = new PrebakeCodeMirror(prebakeScript, (code) => storePrebakeScript(code), el);
|
||||
}}
|
||||
></section>
|
||||
</div>
|
||||
<div className="flex justify-between items-center border-t border-muted px-4 whitespace-nowrap">
|
||||
<Checkbox
|
||||
label="share with patterns"
|
||||
className="whitespace-nowrap max-w-[200px]"
|
||||
onChange={(cbEvent) => settingsMap.setKey('includePrebakeScriptInShare', cbEvent.target.checked)}
|
||||
value={includePrebakeScriptInShare}
|
||||
/>
|
||||
<div className="py-2 flex flex-row items-center space-x-3 ">
|
||||
<ImportPrebakeScriptButton updateEditor={(code) => editorRef?.current.setCode(code)} />
|
||||
<ActionButton onClick={() => exportScript(prebakeScript)}>export</ActionButton>
|
||||
<ActionButton onClick={() => editorRef.current?.savePrebake()}>save</ActionButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function SettingsTab({ started }) {
|
||||
const { settingsTab } = useSettings();
|
||||
return (
|
||||
<div className="w-full h-full text-foreground flex flex-col overflow-hidden">
|
||||
<div className="px-2 shrink-0 h-8 space-x-4 flex max-w-full overflow-x-auto border-b border-muted">
|
||||
<ButtonGroup
|
||||
wrap
|
||||
value={settingsTab}
|
||||
onChange={(value) => setSettingsTab(value)}
|
||||
items={{
|
||||
settings: 'settings',
|
||||
prebake: 'prebake',
|
||||
}}
|
||||
></ButtonGroup>
|
||||
</div>
|
||||
{settingsTab === 'settings' && <MainSettingsContent started={started} />}
|
||||
{settingsTab === 'prebake' && <PrebakeSettingsContent />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
115
website/src/repl/prebakeCodeMirror.mjs
Normal file
115
website/src/repl/prebakeCodeMirror.mjs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import { toggleLineComment } from '@codemirror/commands';
|
||||
import { javascript, javascriptLanguage } from '@codemirror/lang-javascript';
|
||||
import { defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
|
||||
import { Compartment, EditorState, Prec } from '@codemirror/state';
|
||||
import { drawSelection, EditorView, keymap } from '@codemirror/view';
|
||||
import { logger } from '@strudel/core';
|
||||
import { basicSetup, flash, initTheme, extensions, parseBooleans, codemirrorSettings } from '@strudel/codemirror';
|
||||
import { evaluate } from '@strudel/transpiler';
|
||||
|
||||
export class PrebakeCodeMirror {
|
||||
constructor(initialCode, storePrebake, container) {
|
||||
const settings = codemirrorSettings.get();
|
||||
this.storePrebake = storePrebake;
|
||||
const compartments = Object.fromEntries(Object.keys(extensions).map((key) => [key, new Compartment()]));
|
||||
const initialSettings = Object.keys(compartments).map((key) =>
|
||||
compartments[key].of(extensions[key](parseBooleans(settings[key]))),
|
||||
);
|
||||
initTheme(settings.theme);
|
||||
let state = EditorState.create({
|
||||
doc: initialCode,
|
||||
extensions: [
|
||||
...initialSettings,
|
||||
basicSetup,
|
||||
javascript(),
|
||||
javascriptLanguage.data.of({
|
||||
closeBrackets: { brackets: ['(', '[', '{', "'", '"', '<'] },
|
||||
bracketMatching: { brackets: ['(', '[', '{', "'", '"', '<'] },
|
||||
}),
|
||||
syntaxHighlighting(defaultHighlightStyle),
|
||||
EditorView.updateListener.of((v) => {
|
||||
if (v.docChanged) {
|
||||
this.code = v.state.doc.toString();
|
||||
}
|
||||
}),
|
||||
drawSelection({ cursorBlinkRate: 0 }),
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
{
|
||||
mac: 'Meta-Enter',
|
||||
run: () => {
|
||||
this.savePrebake();
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Ctrl-Enter',
|
||||
run: () => {
|
||||
this.savePrebake();
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Alt-Enter',
|
||||
run: () => {
|
||||
this.savePrebake();
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
this.code = initialCode;
|
||||
this.view = new EditorView({
|
||||
state,
|
||||
parent: container,
|
||||
});
|
||||
|
||||
const handleSaveEvent = async (e) => {
|
||||
if (e.detail.view !== this.view) {
|
||||
return; // ignore events from other editors
|
||||
}
|
||||
await this.savePrebake();
|
||||
e?.cancelable && e.preventDefault?.();
|
||||
};
|
||||
const handleToggleComment = (e) => {
|
||||
if (e.detail.view !== this.view) {
|
||||
return; // ignore events from other editors
|
||||
}
|
||||
this.toggleComment();
|
||||
e?.cancelable && e.preventDefault?.();
|
||||
};
|
||||
|
||||
document.addEventListener('repl-evaluate', handleSaveEvent);
|
||||
document.addEventListener('repl-toggle-comment', handleToggleComment);
|
||||
this.cleanup = () => {
|
||||
document.removeEventListener('prebake-evaluate', handleSaveEvent);
|
||||
document.removeEventListener('prebake-toggle-comment', handleToggleComment);
|
||||
};
|
||||
}
|
||||
|
||||
async savePrebake() {
|
||||
flash(this.view);
|
||||
this.storePrebake(this.code);
|
||||
evaluate(this.code, { addReturn: false }); // run prebake
|
||||
logger('[prebake] prebake saved');
|
||||
}
|
||||
|
||||
toggleComment() {
|
||||
try {
|
||||
// Honor selections; toggleLineComment handles both selections and
|
||||
// single line
|
||||
toggleLineComment(this.view);
|
||||
} catch (err) {
|
||||
console.error('Error handling repl-toggle-comment event', err);
|
||||
}
|
||||
}
|
||||
|
||||
setCode(code) {
|
||||
const changes = {
|
||||
from: 0,
|
||||
to: this.view.state.doc.length,
|
||||
insert: code,
|
||||
};
|
||||
this.view.dispatch({ changes });
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th
|
|||
|
||||
import { code2hash, getPerformanceTimeSeconds, logger, silence } from '@strudel/core';
|
||||
import { getDrawContext } from '@strudel/draw';
|
||||
import { evaluate, transpiler } from '@strudel/transpiler';
|
||||
import { transpiler, evaluate } from '@strudel/transpiler';
|
||||
import {
|
||||
getAudioContextCurrentTime,
|
||||
renderPatternAudio,
|
||||
|
|
@ -87,12 +87,12 @@ export function useReplContext() {
|
|||
pattern: silence,
|
||||
drawTime,
|
||||
drawContext,
|
||||
prebake: async () =>
|
||||
Promise.all([modulesLoading, presets]).then(() => {
|
||||
if (prebakeScript?.length) {
|
||||
return evaluate(prebakeScript ?? '');
|
||||
}
|
||||
}),
|
||||
prebake: async () => {
|
||||
await Promise.all([modulesLoading, presets]);
|
||||
if (prebakeScript) {
|
||||
return evaluate(prebakeScript, { addReturn: false });
|
||||
}
|
||||
},
|
||||
onUpdateState: (state) => {
|
||||
setReplState({ ...state });
|
||||
},
|
||||
|
|
|
|||
|
|
@ -108,6 +108,7 @@ export function confirmDialog(msg) {
|
|||
});
|
||||
}
|
||||
export const SETTING_CHANGE_RELOAD_MSG = 'Changing this setting requires the window to reload itself. OK?';
|
||||
|
||||
export function confirmAndReloadPage(onSuccess) {
|
||||
confirmDialog(SETTING_CHANGE_RELOAD_MSG).then((r) => {
|
||||
if (r == true) {
|
||||
|
|
|
|||
|
|
@ -18,6 +18,20 @@ export const soundFilterType = {
|
|||
ALL: 'all',
|
||||
};
|
||||
|
||||
const initialPrebakeScript = `// Prebake script
|
||||
//
|
||||
// This is code that is loaded before your pattern is run.
|
||||
// You can use it to define custom functions to use in any pattern.
|
||||
//
|
||||
// This is an initial example script. You can edit it to add
|
||||
// your own funtions.
|
||||
//
|
||||
// To use a script shared by some other user you can use
|
||||
// the import-button or paste the script in this editor.
|
||||
|
||||
const ratchet = register('ratchet', (pat) => pat.sometimes(ply(2)))
|
||||
`;
|
||||
|
||||
export const defaultSettings = {
|
||||
activeFooter: 'intro',
|
||||
keybindings: 'codemirror',
|
||||
|
|
@ -47,13 +61,14 @@ export const defaultSettings = {
|
|||
isPanelPinned: false,
|
||||
isPanelOpen: true,
|
||||
userPatterns: '{}',
|
||||
prebakeScript: '',
|
||||
prebakeScript: initialPrebakeScript,
|
||||
audioEngineTarget: audioEngineTargets.webaudio,
|
||||
isButtonRowHidden: false,
|
||||
isCSSAnimationDisabled: false,
|
||||
maxPolyphony: 128,
|
||||
multiChannelOrbits: false,
|
||||
includePrebakeScriptInShare: true,
|
||||
settingsTab: 'settings',
|
||||
};
|
||||
|
||||
let search = null;
|
||||
|
|
@ -115,6 +130,7 @@ export function useSettings() {
|
|||
export const setActiveFooter = (tab) => settingsMap.setKey('activeFooter', tab);
|
||||
export const setPanelPinned = (bool) => settingsMap.setKey('isPanelPinned', bool);
|
||||
export const setIsPanelOpened = (bool) => settingsMap.setKey('isPanelOpen', bool);
|
||||
export const setSettingsTab = (tab) => settingsMap.setKey('settingsTab', tab);
|
||||
|
||||
export const storePrebakeScript = (script) => settingsMap.setKey('prebakeScript', script);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue