Skip to content

Commit

Permalink
remove sprig npm package as project dependency (hackclub#2196)
Browse files Browse the repository at this point in the history
  • Loading branch information
JosiasAurel authored Aug 20, 2024
1 parent 885622c commit 1682182
Show file tree
Hide file tree
Showing 15 changed files with 60 additions and 66 deletions.
18 changes: 9 additions & 9 deletions engine/src/web/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function webEngine(canvas: HTMLCanvasElement): {
cleanup(): void
} {
const { api, state } = baseEngine()

const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
Expand Down Expand Up @@ -71,19 +71,19 @@ export function webEngine(canvas: HTMLCanvasElement): {
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)

const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
textCanvas,
0,
0,
0,
canvas.width,
canvas.width,
canvas.height
)

Expand Down Expand Up @@ -155,7 +155,7 @@ export function webEngine(canvas: HTMLCanvasElement): {
api: {
...api,
setLegend,
onInput,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
"react-icons": "^4.7.1",
"rehype-external-links": "^2.0.1",
"sass": "^1.58.0",
"sprig": "^1.1.3",
"svelte": "^3.54.0",
"three": "^0.149.0",
"throttle-debounce": "^5.0.0",
Expand Down
4 changes: 2 additions & 2 deletions src/components/codemirror-widgets/swatch.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Rgba } from 'sprig'
import type { Rgba } from '../../../engine/src/api'
import styles from './swatch.module.css'

interface SwatchProps {
Expand All @@ -12,4 +12,4 @@ export default function Swatch(props: SwatchProps) {
style={{ backgroundColor: `rgba(${props.rgba.join(', ')})` }}
/>
)
}
}
4 changes: 2 additions & 2 deletions src/components/design-system/bitmap-preview.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useRef, useEffect } from 'preact/hooks'
import { bitmapTextToImageData } from 'sprig/image-data'
import { bitmapTextToImageData } from '../../../engine/src/image-data'
import styles from './bitmap-preview.module.css'

interface BitmapPreviewProps {
Expand Down Expand Up @@ -31,4 +31,4 @@ export default function BitmapPreview(props: BitmapPreviewProps) {
{props.text}
</canvas>
)
}
}
6 changes: 3 additions & 3 deletions src/components/subeditors/bitmap-editor-tools.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { IoArrowForward, IoBrush, IoColorFill, IoColorWand, IoEllipse, IoEyedrop, IoMove, IoReload, IoSquare, IoSwapHorizontal, IoSwapVertical, IoSync } from 'react-icons/io5'
import { type PaletteItem, transparent } from 'sprig/base'
import { type PaletteItem, transparent } from '../../../engine/src/base'

export type TempGrid = (PaletteItem | null)[][]
export type Vector = { x: number, y: number }
Expand Down Expand Up @@ -145,7 +145,7 @@ export const drawingTools = [
const dest = ctx.shiftKey
? snapDestToSquare(ctx.startPos, ctx.currentPos)
: ctx.currentPos

const min = { x: Math.min(src.x, dest.x) - 1, y: Math.min(src.y, dest.y) - 1 }
const max = { x: Math.max(src.x, dest.x) + 1, y: Math.max(src.y, dest.y) + 1 }
const [ cx, cy ] = [ (min.x + max.x) / 2, (min.y + max.y) / 2 ]
Expand Down Expand Up @@ -290,4 +290,4 @@ export const transformTools = [
return newGrid
}
}
]
]
10 changes: 5 additions & 5 deletions src/components/subeditors/bitmap-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import styles from './bitmap-editor.module.css'
import type { EditorProps } from '../../lib/state'
import type { IconType } from 'react-icons'
import { signal, useSignal, useSignalEffect } from '@preact/signals'
import { palette, type PaletteItem, rgbaToHex, transparent } from 'sprig/base'
import { palette, type PaletteItem, rgbaToHex, transparent } from '../../../engine/src/base'
import { transparentBgUrl } from '../../lib/utils/transparent-bg'
import { drawingTools, makeTempGrid, mirrorGrid, TempGrid, transformTools, Vector } from './bitmap-editor-tools'
import { useEffect, useRef } from 'preact/hooks'
Expand Down Expand Up @@ -45,7 +45,7 @@ interface ToolButtonProps {

function ToolButton(props: ToolButtonProps) {
const ref = useRef<HTMLButtonElement>(null)

useEffect(() => {
return props.shortcut ? tinykeys(window, {
[props.shortcut]: (event: KeyboardEvent) => {
Expand Down Expand Up @@ -139,7 +139,7 @@ export default function BitmapEditor(props: EditorProps) {
editState.value = null
}

const keydown = (event: KeyboardEvent) => { liveMirror.value = event.altKey }
const keydown = (event: KeyboardEvent) => { liveMirror.value = event.altKey }
const keyup = (event: KeyboardEvent) => { liveMirror.value = event.altKey }

window.addEventListener('mouseup', mouseup)
Expand Down Expand Up @@ -227,7 +227,7 @@ export default function BitmapEditor(props: EditorProps) {
{row.map((item, x) => {
const mirroredTempGrid = editState.value && (liveMirror.value ? mirrorGrid(editState.value.tempGrid) : editState.value.tempGrid)
if (mirroredTempGrid?.[y]![x]) item = mirroredTempGrid[y]![x]!

return (
<div
key={`${x},${y}`}
Expand Down Expand Up @@ -351,4 +351,4 @@ export default function BitmapEditor(props: EditorProps) {
</div>
</div>
)
}
}
4 changes: 2 additions & 2 deletions src/components/subeditors/color-picker.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import styles from './color-picker.module.css'
import { palette, rgbaToHex } from 'sprig/base'
import { palette, rgbaToHex } from '../../../engine/src/base'
import { transparentBgUrl } from '../../lib/utils/transparent-bg'
import type { EditorProps } from '../../lib/state'

Expand All @@ -22,4 +22,4 @@ export default function ColorPickerEditor(props: EditorProps) {
</div>
</div>
)
}
}
14 changes: 7 additions & 7 deletions src/components/subeditors/sequencer-utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { effect, Signal } from '@preact/signals'
import { type InstrumentType, tones, type Tune } from 'sprig'
import { playFrequency } from 'sprig/web'
import { type InstrumentType, tones, type Tune } from '../../../engine/src/api'
import { playFrequency } from '../../../engine/src/web'
import { lazy } from '../../lib/utils/lazy'

// Weird representations are used here:
Expand Down Expand Up @@ -55,7 +55,7 @@ export const tuneToCells = (tune: Tune) => {
const nonRestBeats = tune.filter(el => el.length > 1)
if (!nonRestBeats.length) return {}
const beatTime = nonRestBeats[0]![0]

const cells: Cells = {}
let x = 0
for (const [ duration, ...rest ] of tune) {
Expand Down Expand Up @@ -99,14 +99,14 @@ export const playNote = (symbol: string, duration: number, instrument: Instrumen

const playBeat = (beat: number, cells: Cells, bpm: number) => {
const notes: [number, InstrumentType][] = []

Object
.entries(cells)
.forEach(([ key, value ]) => {
const [ x, y ] = key.split('_').map(Number)
if (x === beat) notes.push([ y!, value ])
})

notes.forEach(([ y, instrument ]) => {
const note = yNoteMap[y]!
const duration = (1000*60) / bpm
Expand All @@ -128,10 +128,10 @@ export const play = (cells: Signal<Cells>, bpm: Signal<number>, beat: Signal<num
if (_timeout) clearTimeout(_timeout as number)
_timeout = setTimeout(go, ((1000 * 60) / bpm.value) - (audioCtx.outputLatency * 1000))
})

}, audioCtx.outputLatency * 1000)
}
go()
console.log(`Latency compensation: ${Math.round(audioCtx.outputLatency * 1000)}ms`)
return () => { stop.current = true }
}
}
6 changes: 3 additions & 3 deletions src/components/subeditors/sequencer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import type { EditorProps } from '../../lib/state'
import { type Signal, useSignal, useSignalEffect, signal } from '@preact/signals'
import { IoPause, IoPlay, IoStop } from 'react-icons/io5'
import { cellsToTune, height, tuneToCells, beats, Cells, yNoteMap, playNote, play, cellsEq } from './sequencer-utils'
import { instruments, type InstrumentType, reverseInstrumentKey } from 'sprig'
import { textToTune, tuneToText } from 'sprig/base'
import { instruments , type InstrumentType, reverseInstrumentKey } from '../../../engine/src/api'
import { textToTune, tuneToText } from '../../../engine/src/base'
import { leftDown, rightDown } from '../../lib/utils/events'
import { useEffect } from 'preact/hooks'
import Button from '../design-system/button'
Expand Down Expand Up @@ -255,4 +255,4 @@ export default function SequencerEditor(props: EditorProps) {
</div>
</div>
)
}
}
20 changes: 10 additions & 10 deletions src/integrations/thumbnail.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { baseEngine, palette } from 'sprig/base'
import { baseEngine, palette } from '../../engine/src/base'
import { RawThumbnail, Thumbnail } from '../lib/thumbnail'
import fs from 'fs'
import path from 'path'
Expand All @@ -21,7 +21,7 @@ const evalGameScript = (script: string) => {
setLegend: (...bitmaps: [string, string][]) => { legend = bitmaps },
setBackground: (bg: string) => { background = bg },
setMap: (string: string) => { map = string },
onInput: () => {},
onInput: () => {},
afterInput: () => {},
playTune: () => {},
setTimeout: () => {},
Expand Down Expand Up @@ -74,8 +74,8 @@ const blitSprite = (data: Uint8Array, width: number, bitmap: number[], tx: numbe

const drawGameImage = (src: string): RawThumbnail => {
const { legend, map, background } = evalGameScript(src)
if (!map) {
throw new Error('No map found')
if (!map) {
throw new Error('No map found')
}

const mapWidth = map.trim().split('\n')[0]!.trim().length
Expand Down Expand Up @@ -105,10 +105,10 @@ const drawGameImage = (src: string): RawThumbnail => {
export const generateImageJson = async (name: string) => {
let gameContentString = loadGameContentFromDisk(name)
let gameImageBase64 = loadImageBase64FromDisk(name)

let thumbnail: Thumbnail
try {
if (gameImageBase64 != null)
if (gameImageBase64 != null)
{
// Try fetching a custom image (PNG only)
thumbnail = {
Expand All @@ -119,10 +119,10 @@ export const generateImageJson = async (name: string) => {
if (gameContentString == null) {
throw new Error('No image found, no game content found - weird')
} else {
// Fetch the script and try to run the game
// Fetch the script and try to run the game
thumbnail = drawGameImage(gameContentString as string)
}
}
}
} catch (error) {
// If everything breaks, use a default image
// console.error(error)
Expand Down Expand Up @@ -152,8 +152,8 @@ function loadImageBase64FromDisk(name: string) {
}
}

function loadGameContentFromDisk(name: string) {
function loadGameContentFromDisk(name: string) {
let gameContentPath = path.resolve(__dirname, `../../games/${name}.js`)
if (!fs.existsSync(gameContentPath)) return null
return fs.readFileSync(gameContentPath).toString()
}
}
8 changes: 4 additions & 4 deletions src/lib/codemirror/widgets.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { EditorView, Decoration } from '@codemirror/view'
import { type EditorState, StateField, type Range } from '@codemirror/state'
import { syntaxTree, foldService } from '@codemirror/language'
import { palette } from 'sprig/base'
import { palette } from '../../../engine/src/base'
import { FromTo, getTag, makeWidget } from './util'
import OpenButton from '../../components/codemirror-widgets/open-button'
import Swatch from '../../components/codemirror-widgets/swatch'
Expand All @@ -14,7 +14,7 @@ const SwatchWidget = makeWidget(Swatch)
function makeValue(state: EditorState) {
const widgets: Range<Decoration>[] = []
const foldRanges: FromTo[] = []

const syntax = syntaxTree(state)
syntax.iterate({
enter(node) {
Expand All @@ -35,7 +35,7 @@ function makeValue(state: EditorState) {
} else if (tag.textFrom !== tag.textTo) {
foldRanges.push({ from: tag.textFrom, to: tag.textTo })
}

break
}
}
Expand All @@ -56,4 +56,4 @@ export default StateField.define({
value.foldRanges.find(range => range.from >= lineStart && range.from <= lineEnd) ?? null
))
]
})
})
10 changes: 5 additions & 5 deletions src/lib/engine/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { playTune } from './tune'
import { normalizeGameError } from './error'
import { bitmaps, NormalizedError } from '../state'
import type { PlayTuneRes } from 'sprig'
import { textToTune } from 'sprig/base'
import { webEngine } from 'sprig/web'
import type { PlayTuneRes } from '../../../engine/src/api'
import { textToTune } from '../../../engine/src/base'
import { webEngine } from '../../../engine/src/web'
import * as Babel from "@babel/standalone"
import TransformDetectInfiniteLoop, { BuildDuplicateFunctionDetector } from '../custom-babel-transforms'
import {logInfo} from "../../components/popups-etc/help";
Expand Down Expand Up @@ -136,11 +136,11 @@ export function runGameHeadless(code: string): void {
setInterval: () => {},
setLegend: (..._bitmaps: [string, string][]) => {
// this is bad; but for some reason i could not do _bitmaps === [undefined]
if(JSON.stringify(_bitmaps) === "[null]") {
if(JSON.stringify(_bitmaps) === "[null]") {
// @ts-ignore
bitmaps.value = [[]];
throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).');
} else
} else
bitmaps.value = _bitmaps
return game.api.setLegend(..._bitmaps)
},
Expand Down
6 changes: 3 additions & 3 deletions src/lib/engine/tune.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { effect } from '@preact/signals'
import { lazy } from '../utils/lazy'
import { muted } from '../state'
import { type PlayTuneRes, type Tune } from 'sprig'
import { playTuneHelper } from 'sprig/web'
import type { PlayTuneRes, Tune } from '../../../engine/src/api'
import { playTuneHelper } from '../../../engine/src/web'

const audioCtx = lazy(() => new AudioContext())
const volGain = lazy(() => {
Expand All @@ -19,4 +19,4 @@ export function playTune(tune: Tune, number = 1): PlayTuneRes {
end() { playingRef.playing = false },
isPlaying() { return playingRef.playing }
}
}
}
Loading

0 comments on commit 1682182

Please sign in to comment.