This commit is contained in:
2023-08-04 20:27:36 -04:00
parent 53ea20cb58
commit bb7bc4f9ea
23 changed files with 541 additions and 1996 deletions

165
src/Lain.js Normal file
View File

@@ -0,0 +1,165 @@
'use strict'
// In the real world, it didnt matter if I was there or not.
// When I realized that, I was no longer afraid of losing my body.
const AsyncFunction = (async () => {}).constructor
function Lain (lib = {}) {
const TYPES = { identifier: 0, number: 1, string: 2, bool: 3, symbol: 4 }
const Context = function (scope, parent) {
this.scope = scope
this.parent = parent
this.get = function (identifier) {
if (identifier in this.scope) {
return this.scope[identifier]
} else if (this.parent !== undefined) {
return this.parent.get(identifier)
}
}
}
const special = {
let: async function (input, context) {
const letContext = new Context({}, context)
for(let x of input[1]) {
letContext.scope[x[0].value] = await interpret(x[1], context)
}
return await interpret(input[2], letContext)
},
def: async function (input, context) {
if (input.length !== 3) { console.warn('Lain', 'Invalid definition.'); return }
const identifier = input[1].host ? input[1].host : input[1].value
if (input[1].host) {
if (!context.scope[identifier]) { context.scope[identifier] = {} }
context.scope[identifier][input[1].value] = await interpret(input[2], context)
return context.scope[identifier][input[1].value]
}
context.scope[identifier] = await interpret(input[2], context)
return context.scope[identifier]
},
defn: async function (input, context) {
const identifier = input[1].value
if (context.scope[identifier]) { console.warn('Lain', `Redefining function: ${identifier}`) }
const fnParams = input[2].type === TYPES.string && input[3] ? input[3] : input[2]
const fnBody = input[2].type === TYPES.string && input[4] ? input[4] : input[3]
context.scope[identifier] = async function () {
const lambdaArguments = arguments
const lambdaScope = fnParams.reduce(function (acc, x, i) {
acc[x.value] = lambdaArguments[i]
return acc
}, {})
return await interpret(fnBody, new Context(lambdaScope, context))
}
},
λ: async function (input, context) {
return async function () {
const lambdaArguments = arguments
const lambdaScope = input[1].reduce(function (acc, x, i) {
acc[x.value] = lambdaArguments[i]
return acc
}, {})
return await interpret(input[2], new Context(lambdaScope, context))
}
},
if: async function (input, context) {
return await interpret(input[1], context) ? await interpret(input[2], context) : input[3] ? interpret(input[3], context) : []
}
}
const interpretList = async function (input, context) {
if (input.length > 0 && input[0].value in special) {
return await special[input[0].value](input, context)
.catch(console.error)
}
const list = []
for (let i = 0; i < input.length; i++) {
if (input[i].type === TYPES.symbol) {
if (input[i].host) {
const host = context.get(input[i].host)
if (host) {
list.push(host[input[i].value])
}
} else {
list.push(obj => obj[input[i].value])
}
} else {
list.push(await interpret(input[i], context))
}
}
if(list[0] instanceof AsyncFunction) {
return await list[0].apply(undefined, list.slice(1))
.catch(console.error)
} else if(list[0] instanceof Function) {
return list[0].apply(undefined, list.slice(1))
} else {
return list
}
}
const interpret = async function (input, context) {
if (!input) { console.warn('Lain', context.scope); return null }
if (context === undefined) {
return await interpret(input, new Context(lib))
} else if (input instanceof Array) {
return await interpretList(input, context)
} else if (input.type === TYPES.identifier) {
return context.get(input.value)
} else if (input.type === TYPES.number || input.type === TYPES.symbol || input.type === TYPES.string || input.type === TYPES.bool) {
return input.value
}
}
const categorize = function (input) {
if (!isNaN(parseFloat(input))) {
return { type: TYPES.number, value: parseFloat(input) }
} else if (input[0] === '"' && input.slice(-1) === '"') {
return { type: TYPES.string, value: input.slice(1, -1) }
} else if (input[0] === ':') {
return { type: TYPES.symbol, value: input.slice(1) }
} else if (input.indexOf(':') > 0) {
return { type: TYPES.symbol, host: input.split(':')[0], value: input.split(':')[1] }
} else if (input === 'true' || input === 'false') {
return { type: TYPES.bool, value: input === 'true' }
} else {
return { type: TYPES.identifier, value: input }
}
}
const parenthesize = function (input, list) {
if (list === undefined) { return parenthesize(input, []) }
const token = input.shift()
if (token === undefined) {
return list.pop()
} else if (token === '(') {
list.push(parenthesize(input, []))
return parenthesize(input, list)
} else if (token === ')') {
return list
} else {
return parenthesize(input, list.concat(categorize(token)))
}
}
const tokenize = function (input) {
const i = input.replace(/^[\s]*;.*\n?/gm, '').split('"')
return i.map(function (x, i) {
return i % 2 === 0 ? x.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ') : x.replace(/ /g, '!ws!')
}).join('"').trim().split(/\s+/).map(function (x) { return x.replace(/!ws!/g, ' ') })
}
this.run = async (input) => {
return await interpret(parenthesize(tokenize(input)))
}
this.runSandbox = async (input, args) => {
let context = new Context(lib)
for(let i = 0; i < args.length; i++) {
context.scope['arg-' + i] = args[i]
}
return await interpret(parenthesize(tokenize(input)), context)
}
}
export default Lain

727
src/Library.js Normal file
View File

@@ -0,0 +1,727 @@
function Library (client) {
// IO
this.open = async (name, scale = 1) => { // Import a graphic and scale canvas to fit.
const img = await resolveImage(name)
const rect = this.rect(0, 0, img.width * scale, img.height * scale)
this.resize(rect.w, rect.h)
await this.import(name, rect)
return rect
}
this.import = async (name, shape, alpha = 1) => { // Imports a graphic file with format.
const img = await resolveImage(name)
client.surface.draw(img, shape, alpha)
return shape || this.rect(0, 0, img.width, img.height)
}
this.export = async (format = 'jpg', quality = 0.9, name = `ronin-${timestamp()}`) => { // Exports a graphic file with format.
const type = `image/${format === 'jpeg' || format === 'jpg' ? 'jpeg' : 'png'}`
console.log('Exporting!')
client.source.write(name, format, client.surface.toDataURL(type, quality), type)
}
function timestamp (d = new Date(), e = new Date(d)) {
return `${arvelie()}-${neralie()}`
}
function arvelie (date = new Date()) {
const start = new Date(date.getFullYear(), 0, 0)
const diff = (date - start) + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000)
const doty = Math.floor(diff / 86400000) - 1
const y = date.getFullYear().toString().substr(2, 2)
const m = doty === 364 || doty === 365 ? '+' : String.fromCharCode(97 + Math.floor(doty / 14)).toUpperCase()
const d = `${(doty === 365 ? 1 : doty === 366 ? 2 : (doty % 14)) + 1}`.padStart(2, '0')
return `${y}${m}${d}`
}
function neralie (d = new Date(), e = new Date(d)) {
const ms = e - d.setHours(0, 0, 0, 0)
return (ms / 8640 / 10000).toFixed(6).substr(2, 6)
}
this.files = () => {
return Object.keys(client.cache.data)
}
// Shapes
this.pos = (x = 0, y = 0) => { // Returns a position shape.
return { x, y }
}
this.line = (ax, ay, bx, by) => { // Returns a line shape.
return { a: this.pos(ax, ay), b: this.pos(bx, by) }
}
this.size = (w, h) => { // Returns a size shape.
return { w, h }
}
this.rect = (x, y, w, h) => { // Returns a rect shape.
return { x, y, w, h, pos: { x, y }, size: { w, h } }
}
this.circle = (cx, cy, r) => { // Returns a circle shape.
return { cx, cy, r }
}
this.ellipse = (cx, cy, rx, ry) => { // Returns a ellipse shape.
return { cx, cy, rx, ry }
}
this.arc = (cx, cy, r, sa, ea) => { // Returns an arc shape.
return { cx, cy, r, sa, ea }
}
this.poly = (...pos) => { // Returns a poly shape.
return pos
}
this.text = (x, y, p, t, a = 'left', f = 'Arial') => { // Returns a text shape.
return { x, y, p, t, a, f }
}
this.svg = (x, y, d) => { // Returns a svg shape.
return { x, y, d }
}
this.color = (r, g, b, a = 1) => { // Returns a color object.
const hex = '#' + ('0' + parseInt(r, 10).toString(16)).slice(-2) + ('0' + parseInt(g, 10).toString(16)).slice(-2) + ('0' + parseInt(b, 10).toString(16)).slice(-2)
const rgba = `rgba(${r},${g},${b},${a})`
return { r, g, b, a, hex, rgba, toString: () => { return rgba }, 0: r, 1: g, 2: b, 3: a, f: [r / 255, g / 255, b / 255, a] }
}
this.hsl = (h, s, l, a = 1) => { // returns a HSL color object
return { h, s, l, a, toString: () => { return `hsla(${h},${s}%,${l}%,${a})` }, 0: h, 1: s, 2: l, 3: a, f: [h / 360, s / 100, l / 100, a] }
}
// Frame
this.resize = (w = client.surface.bounds().w, h = client.surface.bounds().h, fit = true) => { // Resizes the canvas to target w and h, returns the rect.
if (w === this['get-frame']().w && h === this['get-frame']().h) { return }
const rect = { x: 0, y: 0, w, h }
const a = new Image()
const b = new Image()
a.src = client.surface.toDataURL()
client.surface.resizeImage(a, b)
client.surface.resize(rect, fit)
return client.surface.draw(b, rect)
}
this.rescale = (w = 1, h) => { // Rescales the canvas to target ratio of w and h, returns the rect.
const rect = { x: 0, y: 0, w: this['get-frame']().w * w, h: this['get-frame']().h * (h || w) }
const a = new Image()
const b = new Image()
a.src = client.surface.toDataURL()
client.surface.resizeImage(a, b)
client.surface.resize(rect, true)
return client.surface.draw(b, rect)
}
this.crop = (rect = this['get-frame']()) => { // Crop canvas to rect.
return client.surface.crop(rect)
}
this.copy = (rect = this['get-frame']()) => { // Copy a section of the canvas.
return client.surface.copy(rect)
}
this.paste = (copy, rect = this['get-frame']()) => { // Paste a section of the canvas.
return client.surface.paste(copy, rect)
}
this.drag = (rect = this['get-frame'](), line = this.line()) => { // Drag a part of the canvas.
const pos = { x: line.b.x - line.a.x, y: line.b.y - line.a.y }
const crop = client.surface.copy(rect)
client.surface.clear(rect)
this.guide({ a: { x: rect.x, y: rect.y }, b: { x: pos.x + rect.x, y: pos.y + rect.y } })
this.guide(rect)
this.guide(this.offset(rect, { x: pos.x, y: pos.y }))
client.surface.context.drawImage(crop, rect.x, rect.y)
}
this.view = (a, b) => { // View a part of the canvas.
if (!a || !b) { return }
this.guide({ a: { x: a.x, y: a.y }, b: { x: b.x, y: b.y } })
this.guide(a)
this.guide(b)
client.surface.context.drawImage(this.copy(a), b.x, b.y, b.w, b.h)
}
this.pick = (shape = this['get-frame']()) => { // Returns the color of a pixel at pos, or of the average of the pixels in rect.
const rect = shape.w && shape.h ? shape : this.rect(shape.x, shape.y, 1, 1)
const img = client.surface.context.getImageData(rect.x, rect.y, rect.w, rect.h)
const sum = [0, 0, 0]
const count = img.data.length / 4
for (let i = 0, loop = img.data.length; i < loop; i += 4) {
sum[0] += img.data[i]
sum[1] += img.data[i + 1]
sum[2] += img.data[i + 2]
}
return this.color(this.floor(sum[0] / count), this.floor(sum[1] / count), this.floor(sum[2] / count))
}
this.orient = (deg = 0) => { // Orient canvas with angle in degrees.
const copy = this.copy()
const frame = this['get-frame']()
const mode = Math.floor(deg / 90) % 4
const offset = { x: [0, 0, -frame.w, -frame.w], y: [0, -frame.h, -frame.h, 0] }
const rect = { x: 0, y: 0, w: (mode === 1 || mode === 3 ? frame.h : frame.w), h: (mode === 1 || mode === 3 ? frame.w : frame.h) }
client.surface.resize(rect, false)
client.surface.context.save()
client.surface.context.rotate(this.rad(mode * 90))
client.surface.context.translate(offset.x[mode], offset.y[mode])
client.surface.context.drawImage(copy, 0, 0)
client.surface.context.restore()
}
this.mirror = { // Mirror canvas, methods: `x`, `y`.
x: (j = 0) => {
const copy = this.copy()
const frame = this['get-frame']()
client.surface.context.save()
client.surface.context.translate(frame.w, 0)
client.surface.context.scale(-1, 1)
client.surface.context.drawImage(copy, 0, 0)
client.surface.context.restore()
},
y: (j = 0) => {
const copy = this.copy()
const frame = this['get-frame']()
client.surface.context.save()
client.surface.context.translate(0, frame.h)
client.surface.context.scale(1, -1)
client.surface.context.drawImage(copy, 0, 0)
client.surface.context.restore()
}
}
// Transforms
this.transform = { // The transform toolkit, methods `push`, `pop`, `reset`, `move`, `scale`, `rotate`.
push: () => {
client.surface.context.save()
},
pop: () => {
client.surface.context.restore()
},
reset: () => {
client.surface.context.resetTransform()
client.surface.guide.resetTransform()
},
move: (x, y) => {
client.surface.context.translate(x, y)
this.guide(this.line(0, 0, x, y))
client.surface.guide.translate(x, y)
},
scale: (w, h) => {
client.surface.context.scale(w, h === undefined ? w : h)
this.guide(this.rect(0, 0, 50 * w, 50 * h))
client.surface.guide.scale(w, h === undefined ? w : h)
},
rotate: (a) => {
client.surface.context.rotate(a)
this.guide(this.arc(0, 0, 50, 0, a))
client.surface.guide.rotate(a)
}
}
// Actions
this.stroke = (shape, color, thickness = 2) => { // Strokes a shape.
client.surface.stroke(shape, color, thickness)
return shape
}
this.fill = (rect = this['get-frame'](), color) => { // Fills a shape.
client.surface.fill(rect, color)
return rect
}
this.clear = (rect = this['get-frame']()) => { // Clears a rect.
client.surface.clearGuide(rect)
client.surface.clear(rect)
return rect
}
this.gradient = (line, colors = ['white', 'black']) => { // Defines a gradient color.
const gradient = client.surface.context.createLinearGradient(line.a.x, line.a.y, line.b.x, line.b.y)
colors.forEach((color, i) => {
gradient.addColorStop(i * (1 / (colors.length - 1)), color)
})
return gradient
}
this.guide = (shape, color) => { // Draws a shape on the guide layer.
client.surface.drawGuide(shape, color)
return shape
}
// Pixels
this.pixels = (fn, q = 1, rect = this['get-frame']()) => {
if (!fn) { console.warn('Unknown function'); return rect }
const img = client.surface.context.getImageData(rect.x, rect.y, rect.w, rect.h)
for (let i = 0, loop = img.data.length; i < loop; i += 4) {
const pixel = [img.data[i], img.data[i + 1], img.data[i + 2], img.data[i + 3]]
const processed = fn(pixel, q)
img.data[i] = this.clamp(parseInt(processed[0]), 0, 255)
img.data[i + 1] = this.clamp(parseInt(processed[1]), 0, 255)
img.data[i + 2] = this.clamp(parseInt(processed[2]), 0, 255)
img.data[i + 3] = this.clamp(parseInt(processed[3]), 0, 255)
}
client.surface.context.putImageData(img, rect.x, rect.y)
return rect
}
this.saturation = (pixel, q) => { // Change the saturation of pixels.
const color = this.lum(pixel)
return [(color * (1 - q)) + (pixel[0] * q), (color * (1 - q)) + (pixel[1] * q), (color * (1 - q)) + (pixel[2] * q), pixel[3]]
}
this.contrast = (pixel, q) => { // Change the contrast of pixels.
const intercept = 128 * (1 - q)
return [pixel[0] * q + intercept, pixel[1] * q + intercept, pixel[2] * q + intercept, pixel[3]]
}
this.brightness = (pixel, q) => { // Change the brightness of pixels.
const range = 255 - -q
return [((pixel[0] / 255) * range), ((pixel[1] / 255) * range), ((pixel[2] / 255) * range), pixel[3]]
}
this.additive = (pixel, q) => { // Condense the data of pixels.
return [pixel[0] + q, pixel[1] + q, pixel[2] + q, pixel[3]]
}
this.multiply = (pixel, q) => { // Change the color balance of pixels.
return [pixel[0] * q[0], pixel[1] * q[1], pixel[2] * q[2], pixel[3]]
}
this.normalize = (pixel, q) => { // Normalize the color of pixels with another color.
const averaged = [128 - q.r + pixel[0], 128 - q.g + pixel[1], 128 - q.b + pixel[2], pixel[3]]
const offset = this.lum(pixel) - this.lum(averaged)
return this.additive(averaged, offset)
}
// Color
this.lum = (color) => { // Return the luminance of a color.
return 0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2]
}
// Strings
this.concat = (...items) => { // Concat multiple strings.
return items.reduce((acc, item) => { return `${acc}${item}` }, '')
}
this.split = (string, char) => { // Split string at character.
return string.split(char)
}
// Math
this.add = this['+'] = (...args) => { // Adds values.
return args.reduce((sum, val) => sum + val)
}
this.sub = this['-'] = (...args) => { // Subtracts values.
return args.reduce((sum, val) => sum - val)
}
this.mul = this['*'] = (...args) => { // Multiplies values.
return args.reduce((sum, val) => sum * val)
}
this.div = this['/'] = (...args) => { // Divides values.
return args.reduce((sum, val) => sum / val)
}
this.mod = this['%'] = (a, b) => { // Returns the modulo of a and b.
return a % b
}
this.rad = (degrees) => { // Convert radians to degrees.
return degrees * (Math.PI / 180)
}
this.deg = (radians) => { // Convert degrees to radians.
return radians * (180 / Math.PI)
}
this.clamp = (val, min, max) => { // Clamps a value between min and max.
return this.min(max, this.max(min, val))
}
this.step = (val, step) => {
return this.round(val / step) * step
}
this.min = Math.min // Returns lowest value.
this.max = Math.max // Returns highest value.
this.ceil = Math.ceil // Rounds up to the nearest integer.
this.floor = Math.floor // Rounds down to the nearest integer.
this.round = Math.round // Rounds to the nearest integer
this.sin = Math.sin
this.cos = Math.cos
this.log = Math.log
this.pow = Math.pow
this.sqrt = Math.sqrt // Calculate the square root.
this.sq = (a) => { // Calculate the square.
return a * a
}
this.PI = Math.PI
this.TWO_PI = Math.PI * 2
this.random = (...args) => {
if (args.length >= 2) {
// (random start end)
return args[0] + Math.random() * (args[1] - args[0])
} else if (args.length === 1) {
// (random max)
return Math.random() * args[0]
}
return Math.random()
}
// Binary
this.logand = (a, b) => {
return a & b
}
this.logior = (a, b) => {
return a | b
}
this.logxor = (a, b) => {
return a ^ b
}
this.lognot = (a) => {
return ~ a
}
this.ash = (a, b) => {
return a << b
}
// Logic
this.gt = (a, b) => { // Returns true if a is greater than b, else false.
return a > b
}
this.lt = (a, b) => { // Returns true if a is less than b, else false.
return a < b
}
this.eq = (a, b) => { // Returns true if a is equal to b, else false.
return a === b
}
this.and = (...args) => { // Returns true if all conditions are true.
for (let i = 0; i < args.length; i++) {
if (!args[i]) {
return args[i]
}
}
return args[args.length - 1]
}
this.or = (a, b, ...rest) => { // Returns true if at least one condition is true.
const args = [a, b].concat(rest)
for (let i = 0; i < args.length; i++) {
if (args[i]) {
return args[i]
}
}
return args[args.length - 1]
}
this.not = (a) => { //Negation. Returns true if a is false. Returns false if a is true.
return !a
}
this.while = (fn, action) => { //While loop. Execute action for as long as fn is true.
while (fn()) {
action()
}
}
// Arrays
this.apply = (fn, argslist) => {
let result = fn(...argslist);
return result;
}
this.each = (arr, fn) => { // Run a function for each element in a list.
for (let i = 0; i < arr.length; i++) {
const arg = arr[i]
fn(arg, i)
}
}
this.eachof = (arr, fn) => {
for(let elem of arr){
fn(elem);
}
}
this.map = (arr, fn) => { // Returns a new list with fn applied to each value.
return arr.map(fn);
}
this.filter = (arr, fn) => { // Returns a new list, without values evaluated to false by fn.
return arr.filter(fn);
}
this.reduce = (arr, fn, acc) => {
const length = arr.length
let result = acc === undefined ? arr[0] : acc
for (let i = acc === undefined ? 1 : 0; i < length; i++) {
result = fn(result, arr[i], i, arr)
}
return result
}
this.len = (item) => { // Returns the length of a list.
return item.length
}
this.list = (...items) => { // Returns a new array with the items
return items
}
this.cons = (arr, ...items) => { // Returns a new array with the items appended to arr.
return arr.concat(items)
}
this.push = (arr, ...items) => { // Appends the items into the existing list.
for (let i = 0; i < items.length; i++) {
arr.push(items[i])
}
return arr
}
this.pop = (arr) => { // Pop the last item from the list and return the item.
return arr.pop();
}
this.first = (arr) => { // Returns the first item of a list.
return arr[0]
}
this.last = (arr) => { // Returns the last
return arr[arr.length - 1]
}
this.rest = ([_, ...arr]) => { // Returns all arguments except the first
return arr
}
this.range = (start, end, step = 1) => { //Returns a list of numbers counting from start to end. Step defaults to 1.
const arr = []
if (step > 0) {
for (let i = start; i <= end; i += step) {
arr.push(i)
}
} else {
for (let i = start; i >= end; i += step) {
arr.push(i)
}
}
return arr
}
// Objects
this.get = (item, key) => { // Gets an object's parameter with name.
return item && (key !== null && key !== undefined) ? item[key] : null
}
this.set = (item, ...args) => { // Sets an object's parameter with name as value.
for (let i = 0; i < args.length; i += 2) {
const key = args[i]
const val = args[i + 1]
item[key] = val
}
return item
}
this.of = (h, ...keys) => { // Gets object parameters with names.
return keys.reduce((acc, key) => {
return acc[key]
}, h)
}
this.object = (...entries) => { // Creates an object with provided entries.
const result = {}
for (let i = 0; i < entries.length; i += 2) {
result[entries[i]] = entries[i + 1]
}
return result
}
this.keys = (item) => { // Returns a list of the object's keys
return Object.keys(item)
}
this.values = (item) => { // Returns a list of the object's values
return Object.values(item)
}
this.entries = (item) => { // Returns a list of the object's properties, each in array of [key, value]
return Object.entries(item);
}
// Convolve
this.convolve = (kernel, rect = this['get-frame']()) => {
const sigma = kernel.flat().reduce((a, x) => (a + x))
const kw = kernel[0].length; const kh = kernel.length
const img = client.surface.context.getImageData(rect.x, rect.y, rect.w, rect.h)
const out = new Uint8ClampedArray(rect.w * 4 * rect.h)
for (let i = 0, outer = img.data.length; i < outer; i++) { // bytes
const ix = Math.floor(i / 4) % rect.w; const iy = Math.floor((i / 4) / rect.w)
let acc = 0.0
for (let k = 0, inner = kw * kh; k < inner; k++) { // kernel
const kx = (k % kw); const ky = (Math.floor(k / kw))
const x = Math.ceil(ix + kx - kw / 2); const y = Math.ceil(iy + ky - kh / 2)
if (x < 0 || x >= rect.w || y < 0 || y >= rect.h) continue // edge case
acc += img.data[x * 4 + y * rect.w * 4 + i % 4] * kernel[kx][ky] / sigma
}
out[i] = acc
if (i % 4 === 3) out[i] = 255
}
img.data.set(out, 0)
client.surface.context.putImageData(img, rect.x, rect.y)
return rect
}
this.blur = () => { // Returns the blur kernel.
return [[1, 2, 1],
[2, 4, 2],
[1, 2, 2]]
}
this.sharpen = () => { // Returns the sharpen kernel.
return [[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]]
}
this.edge = () => { // Returns the edge kernel.
return [[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]]
}
// Points
this.offset = (a, b) => { // Offsets pos a with pos b, returns a.
a.x += b.x
a.y += b.y
return a
}
this.distance = (a, b) => { // Get distance between positions.
return Math.sqrt(((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)))
}
// Utilities
this.print = (value) => {
client.source.write('ronin-print', 'txt', value, 'text/plain')
return value
}
this.echo = (...args) => { // Print arguments to interface.
client.log(args)
return args
}
this.debug = (...args) => { // Print arguments to console.
console.log(...args)
return args
}
this.time = (rate = 1) => { // Returns timestamp in milliseconds.
return (Date.now() * rate)
}
this.js = () => { // Javascript interop.
return window
}
// Returns a new function that
// Useful when executing JS functions that need a strict `this` context.
//
// An example:
// `(get (get (js) "navigator") "requestMIDIAccess")` in Ronin
// should be equivalent to `window.navigator.requestMIDIAccess` in JS.
// Executing such retrieved JS method will crash though - as the method
// needs an internal `this` context - in exemplary case, window.navigator.
//
this['js-bind'] = (fn, thisArg, ...args) => {
return fn.bind(thisArg, ...args)
}
this.on = (event, f) => { // Triggers on event.
client.bind(event, f)
}
this.test = (name, a, b) => { //nit test. Checks if a is equal to b, logs results to console.
if (`${a}` !== `${b}`) {
console.warn('failed ' + name, a, b)
} else {
console.log('passed ' + name, a)
}
return a === b
}
this.benchmark = (fn) => { // Logs time taken to execute a function.
const start = Date.now()
const result = fn()
console.log(`time taken: ${Date.now() - start}ms`)
return result
}
// Accessors
this['get-theme'] = () => { // Get theme values.
return client.theme.active
}
this['get-frame'] = () => { // Get frame shape.
return client.surface.getFrame()
}
// Extras
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
this['blend-mode'] = (operation = 'source-over') => {
client.surface.context.globalCompositeOperation = operation
}
async function resolveImage(name) {
const img = new Image()
img.src = await client.cache.resolve(name)
return img
}
}
export default Library

296
src/Surface.js Normal file
View File

@@ -0,0 +1,296 @@
function Surface (client) {
this.createCanvas = null
this.start = function () {
this.maximize()
}
this.onResize = function () {
if (client.commander._input.value === '') {
this.maximize()
}
const f = this.getFrame()
client.log(`resize ${f.w}x${f.h}`)
}
// Shape
this.stroke = (shape, color = client.resolveMissingColor('f_high'), width = 2, context = this.context) => {
context.beginPath()
this.trace(shape, context)
context.lineWidth = width
context.strokeStyle = color.rgba ? color.rgba : color
if (isText(shape)) {
context.textAlign = shape.a
context.font = `${shape.p}px ${shape.f}`
context.strokeText(`${shape.t}`, shape.x, shape.y)
} else if (isSvg(shape)) {
context.lineWidth = width
context.save()
context.translate(shape.x, shape.y)
context.stroke(new Path2D(shape.d))
context.restore()
} else {
context.stroke()
}
context.closePath()
}
// Fill
this.fill = (shape, color = client.resolveMissingColor('b_high'), context = this.context) => {
context.beginPath()
context.fillStyle = typeof color === 'object' && color.rgba ? color.rgba : color
this.trace(shape, context)
if (isText(shape)) {
context.textAlign = shape.a
context.font = `${shape.p}px ${shape.f}`
context.fillText(`${shape.t}`, shape.x, shape.y)
} else if (isSvg(shape)) {
context.save()
context.translate(shape.x, shape.y)
context.fill(new Path2D(shape.d))
context.restore()
} else {
context.fill()
}
context.closePath()
}
// Clear
this.clear = function (rect = this.getFrame(), context = this.context) {
context.clearRect(rect.x, rect.y, rect.w, rect.h)
}
this.clearGuide = function (rect = this.getFrame(), context = this.guide) {
context.clearRect(rect.x, rect.y, rect.w, rect.h)
}
// Tracers
this.trace = function (shape, context) {
if (isRect(shape)) {
this.traceRect(shape, context)
} else if (isPos(shape)) {
this.tracePos(shape, context)
}
if (isLine(shape)) {
this.traceLine(shape, context)
} else if (isPoly(shape)) {
this.tracePoly(shape, context)
}
if (isArc(shape)) {
this.traceArc(shape, context)
} else if (isCircle(shape)) {
this.traceCircle(shape, context)
} else if (isEllipse(shape)) {
this.traceEllipse(shape, context)
} else if (isText(shape)) {
this.traceText(shape, context)
} else if (isSvg(shape)) {
this.traceSVG(shape, context)
}
}
this.traceRect = function (rect, context) {
context.moveTo(rect.x, rect.y)
context.lineTo(rect.x + rect.w, rect.y)
context.lineTo(rect.x + rect.w, rect.y + rect.h)
context.lineTo(rect.x, rect.y + rect.h)
context.lineTo(rect.x, rect.y)
}
this.traceLine = function (line, context) {
context.moveTo(line.a.x, line.a.y)
context.lineTo(line.b.x, line.b.y)
}
this.tracePoly = function (poly, context) {
const positions = Object.values(poly)
const origin = positions.shift()
context.moveTo(origin.x, origin.y)
for (const pos of positions) {
context.lineTo(pos.x, pos.y)
}
}
this.tracePos = function (pos, context, radius = 7.5) {
context.lineCap = 'round'
context.moveTo(pos.x - radius, pos.y)
context.lineTo(pos.x + radius, pos.y)
context.moveTo(pos.x, pos.y - radius)
context.lineTo(pos.x, pos.y + radius)
}
this.traceCircle = function (circle, context) {
context.arc(circle.cx, circle.cy, circle.r, 0, 2 * Math.PI)
}
this.traceArc = function (arc, context) {
context.arc(arc.cx, arc.cy, arc.r, arc.sa, arc.ea)
}
this.traceEllipse = function (ellipse, context) {
context.ellipse(ellipse.cx, ellipse.cy, ellipse.rx, ellipse.ry, 0, 2 * Math.PI, false)
}
this.traceText = function (text, context) {
}
this.traceSVG = function (text, context) {
}
// IO
this.draw = function (img, shape = this.getFrame(), alpha = 1) {
this.context.globalAlpha = alpha
if (isLine(shape)) {
this.context.drawImage(img, shape.a.x, shape.a.y, shape.b.x - shape.a.x, shape.b.y - shape.a.y)
} else if (isRect(shape)) {
const fit = fitRect({ w: img.width, h: img.height }, { w: shape.w, h: shape.h })
this.context.drawImage(img, shape.x, shape.y, fit.w, fit.h)
} else if (isCircle(shape)) {
const side = Math.sqrt(Math.pow(shape.r, 2) / 2)
const rect = { x: shape.cx - (side), y: shape.cy - (side), w: side * 2, h: side * 2 }
const fit = fitRect({ w: img.width, h: img.height }, { w: rect.w, h: rect.h })
this.context.drawImage(img, rect.x, rect.y, fit.w, fit.h)
} else {
this.context.drawImage(img, shape.x, shape.y, img.width, img.height)
}
this.context.globalAlpha = 1
}
this.crop = function (rect) {
if (!isRect(rect)) { return }
client.log(`Crop ${rect.w}x${rect.h} from ${rect.x}x${rect.y}`)
const crop = this.copy(rect)
this.resize(rect, true)
this.context.drawImage(crop, 0, 0)
}
this.drawGuide = function (shape, color = 'white', context = this.guide) {
if (!shape) { return }
this.stroke(shape.rect || shape, 'black', 4, context)
if (shape.pos) { this.stroke(shape.pos, 'black', 4, context) }
if (shape.line) { this.stroke(shape.line, 'black', 4, context) }
if (shape.circle) {
this.stroke(shape.circle, 'black', 4, context)
}
this.stroke(shape.rect || shape, color, 1.5, context)
if (shape.pos) { this.stroke(shape.pos, color, 1.5, context) }
if (shape.line) { this.stroke(shape.line, color, 1.5, context) }
if (shape.circle) {
this.stroke(shape.circle, color, 1.5, context)
}
}
this.resize = (size, fit = false) => {
const frame = this.getFrame()
if (frame.w === size.w && frame.h === size.h) { return }
console.log('Surface', `Resize: ${size.w}x${size.h}`)
this._canvas.width = size.w
this._canvas.height = size.h
}
this.copy = function (rect) {
const newCanvas = this.createCanvas()
newCanvas.width = rect.w
newCanvas.height = rect.h
newCanvas.getContext('2d').drawImage(this._canvas, rect.x, rect.y, rect.w, rect.h, 0, 0, rect.w, rect.h)
return newCanvas
}
this.paste = function (copy, rect) {
return this.context.drawImage(copy, rect.x, rect.y, rect.w, rect.h)
}
this.resizeImage = function (src, dst, type = 'image/png', quality = 1.0) {
return new Promise(resolve => {
const tmp = new Image()
let canvas
let context
let cW = src.naturalWidth
let cH = src.naturalHeight
tmp.src = src.src
tmp.onload = () => {
canvas = this.createCanvas()
cW /= 2
cH /= 2
if (cW < src.width) {
cW = src.width
}
if (cH < src.height) {
cH = src.height
}
canvas.width = cW
canvas.height = cH
context = canvas.getContext('2d', { colorspace: "srgb" })
context.drawImage(tmp, 0, 0, cW, cH)
dst.src = canvas.toDataURL(type, quality)
if (cW <= src.width || cH <= src.height) { return resolve() }
tmp.src = dst.src
return resolve()
}
})
}
this.maximize = () => {
this.resize(this.bounds())
}
this.bounds = () => {
return { x: 0, y: 0, w: ((window.innerWidth - 60) * this.ratio), h: ((window.innerHeight - 60) * this.ratio) }
}
this.getFrame = () => {
return { x: 0, y: 0, w: this._canvas.width, h: this._canvas.height, c: this._canvas.width / 2, m: this._canvas.height / 2 }
}
this.toggleGuides = function () {
if(this._guide) {
this._guide.className = this._guide.className === 'hidden' ? '' : 'hidden'
}
}
function isRect (shape) {
return shape && !isNaN(shape.x) && !isNaN(shape.y) && !isNaN(shape.w) && !isNaN(shape.h)
}
function isCircle (shape) {
return shape && !isNaN(shape.cx) && !isNaN(shape.cy) && !isNaN(shape.r)
}
function isArc (shape) {
return shape && !isNaN(shape.cx) && !isNaN(shape.cy) && !isNaN(shape.r) && !isNaN(shape.sa) && !isNaN(shape.ea)
}
function isEllipse (shape) {
return shape && !isNaN(shape.cx) && !isNaN(shape.cy) && !isNaN(shape.rx) && !isNaN(shape.ry)
}
function isPos (shape) {
return shape && !isNaN(shape.x) && !isNaN(shape.y)
}
function isSvg (shape) {
return shape && shape.d
}
function isText (shape) {
return shape && !isNaN(shape.x) && !isNaN(shape.y) && shape.p && shape.t && shape.f && shape.a
}
function isLine (shape) {
return shape && shape.a && shape.b && !isNaN(shape.a.x) && !isNaN(shape.a.y) && !isNaN(shape.b.x) && !isNaN(shape.b.y)
}
function isPoly (shape) {
return shape && shape[0] && shape[1] && !isNaN(shape[0].x) && !isNaN(shape[0].y) && !isNaN(shape[1].x) && !isNaN(shape[1].y)
}
function fitRect (image, container) {
image.ratio = image.w / image.h
container.ratio = container.w / container.h
return {
w: image.ratio < container.ratio ? container.h * image.ratio : container.w,
h: image.ratio > container.ratio ? container.w / image.ratio : container.h
}
}
}
export default Surface

119
src/browser/Acels.js Normal file
View File

@@ -0,0 +1,119 @@
function Acels (client) {
this.el = document.createElement('ul')
this.el.id = 'acels'
this.order = []
this.all = {}
this.pipe = null
this.install = (host = document.body) => {
window.addEventListener('keydown', this.onKeyDown, false)
window.addEventListener('keyup', this.onKeyUp, false)
host.appendChild(this.el)
}
this.start = () => {
const cats = this.sort()
for (const cat of this.order) {
const main = document.createElement('li')
const head = document.createElement('a')
head.innerText = cat
const subs = document.createElement('ul')
for (const item of cats[cat]) {
const option = document.createElement('li')
option.onclick = item.downfn
option.innerHTML = item.accelerator ? `${item.name} <i>${item.accelerator.replace('CmdOrCtrl+', '^')}</i>` : `${item.name}`
subs.appendChild(option)
}
main.appendChild(head)
main.appendChild(subs)
this.el.appendChild(main)
}
}
this.set = (cat, name, accelerator, downfn, upfn) => {
if (this.all[accelerator]) { console.warn('Acels', `Trying to overwrite ${this.all[accelerator].name}, with ${name}.`) }
if (this.order.indexOf(cat) < 0) { this.order.push(cat) }
this.all[accelerator] = { cat, name, downfn, upfn, accelerator }
}
this.get = (accelerator) => {
return this.all[accelerator]
}
this.sort = () => {
const h = {}
for (const item of Object.values(this.all)) {
if (!h[item.cat]) { h[item.cat] = [] }
h[item.cat].push(item)
}
return h
}
this.convert = (event) => {
const accelerator = event.key === ' ' ? 'Space' : capitalize(event.key.replace('Arrow', ''))
if ((event.ctrlKey || event.metaKey) && event.shiftKey) {
return `CmdOrCtrl+Shift+${accelerator}`
}
if (event.shiftKey && event.key.toUpperCase() !== event.key) {
return `Shift+${accelerator}`
}
if (event.altKey && event.key.length !== 1) {
return `Alt+${accelerator}`
}
if (event.ctrlKey || event.metaKey) {
return `CmdOrCtrl+${accelerator}`
}
return accelerator
}
this.route = (obj) => {
this.pipe = obj
}
this.onKeyDown = (e) => {
const target = this.get(this.convert(e))
if (!target || !target.downfn) { return this.pipe ? this.pipe.onKeyDown(e) : null }
target.downfn()
e.preventDefault()
}
this.onKeyUp = (e) => {
const target = this.get(this.convert(e))
if (!target || !target.upfn) { return this.pipe ? this.pipe.onKeyUp(e) : null }
target.upfn()
e.preventDefault()
}
this.toMarkdown = () => {
const cats = this.sort()
let text = ''
for (const cat in cats) {
text += `\n### ${cat}\n\n`
for (const item of cats[cat]) {
text += item.accelerator ? `- \`${item.accelerator}\`: ${item.name}\n` : ''
}
}
return text.trim()
}
this.toString = () => {
const cats = this.sort()
let text = ''
for (const cat of this.order) {
for (const item of cats[cat]) {
text += item.accelerator ? `${cat.padEnd(8, ' ')} ${item.name.padEnd(16, ' ')} ${item.accelerator.replace('CmdOrCtrl+', '^')}\n` : ''
}
}
return text.trim()
}
this.toggle = () => {
this.el.className = this.el.className === 'hidden' ? '' : 'hidden'
}
function capitalize (s) { return s.substr(0, 1).toUpperCase() + s.substr(1) }
}
export default Acels

242
src/browser/Client.js Normal file
View File

@@ -0,0 +1,242 @@
import Acels from "./Acels.js"
import Theme from "./Theme.js"
import Source from "./Source.js"
import Commander from "./Commander.js"
import DisplaySurface from "./DisplaySurface.js"
import Library from "../Library.js"
import Lain from "../Lain.js"
function Client () {
this.el = document.createElement('div')
this.el.id = 'ronin'
this.acels = new Acels(this)
this.theme = new Theme(this)
this.source = new Source(this)
this.commander = new Commander(this)
this.surface = new DisplaySurface(this)
this.library = new Library(this)
this.lain = new Lain(this.library)
this.bindings = {}
this.install = function (host = document.body) {
this._wrapper = document.createElement('div')
this._wrapper.id = 'wrapper'
this.commander.install(this._wrapper)
this.surface.install(this._wrapper)
this.el.appendChild(this._wrapper)
host.appendChild(this.el)
this.theme.install(host)
this.acels.install(host)
window.addEventListener('dragover', this.onDrag)
window.addEventListener('drop', this.onDrop)
this.acels.set('∷', 'Toggle Menubar', 'Tab', () => { this.acels.toggle() })
this.acels.set('∷', 'Open Theme', 'CmdOrCtrl+Shift+O', () => { this.theme.open() })
this.acels.set('∷', 'Reset Theme', 'CmdOrCtrl+Backspace', () => { this.theme.reset() })
this.acels.set('File', 'New', 'CmdOrCtrl+N', () => { this.source.new(); this.surface.clear(); this.commander.clear() })
this.acels.set('File', 'Save', 'CmdOrCtrl+S', () => { this.source.write('ronin', 'lisp', this.commander._input.value, 'text/plain') })
this.acels.set('File', 'Export Image', 'CmdOrCtrl+E', () => { this.source.write('ronin', 'png', this.surface.el.toDataURL('image/png', 1.0), 'image/png') })
this.acels.set('File', 'Open', 'CmdOrCtrl+U', () => { this.source.open('lisp', this.whenOpen) })
this.acels.set('View', 'Toggle Guides', 'CmdOrCtrl+H', () => { this.surface.toggleGuides() })
this.acels.set('View', 'Toggle Commander', 'CmdOrCtrl+K', () => { this.commander.toggle() })
this.acels.set('View', 'Expand Commander', 'CmdOrCtrl+Shift+K', () => { this.commander.toggle(true) })
this.acels.set('Project', 'Eval', 'CmdOrCtrl+Enter', () => { this.commander.eval() })
this.acels.set('Project', 'Eval Selection', 'Alt+Enter', () => { this.commander.evalSelection() })
this.acels.set('Project', 'Re-Indent', 'CmdOrCtrl+Shift+I', () => { this.commander.lint() })
this.acels.set('Project', 'Clean', 'Escape', () => { this.commander.cleanup() })
this.acels.set('Project', 'Start Function', '`', () => {
this.commander.inject('()')
this.commander._input.selectionEnd = this.commander._input.selectionStart - 1
})
this.acels.route(this)
}
this.start = function () {
console.log('Ronin', 'Starting..')
console.info(`${this.acels}`)
this.theme.start()
this.acels.start()
this.source.start()
this.commander.start()
this.surface.start()
this.loop()
}
this.whenOpen = (file, res) => {
console.log(file, res)
this.commander.load(res)
this.commander.show()
}
this.loop = () => {
if (this.bindings.animate && typeof this.bindings.animate === 'function') {
this.bindings.animate()
}
requestAnimationFrame(() => this.loop())
}
this.log = (...msg) => {
this.commander.setStatus(msg.reduce((acc, val) => {
return acc + JSON.stringify(val).replace(/"/g, '').trim() + ' '
}, ''))
}
this.bind = (event, fn) => {
this.bindings[event] = fn
}
// Cursor
this.mouseOrigin = null
this.onMouseDown = (e, id = 'mouse-down') => {
const pos = { x: e.offsetX * this.surface.ratio, y: e.offsetY * this.surface.ratio }
this.mouseOrigin = pos
const shape = this.mouseShape(pos, id)
if (this.bindings[id]) {
this.bindings[id](shape)
}
this.commander.capture()
this.surface.clearGuide()
this.surface.drawGuide(shape)
}
this.onKeyPress = (e, id = 'key-press') => {
if (this.bindings[id]) {
this.bindings[id](e)
}
}
this.onKeyDown = (e, id = 'key-down') => {
if (this.bindings[id]) {
this.bindings[id](e)
}
}
this.onKeyUp = (e, id = 'key-up') => {
if (this.bindings[id]) {
this.bindings[id](e)
}
}
this.onMouseMove = (e, id = 'mouse-move') => {
const pos = { x: e.offsetX * this.surface.ratio, y: e.offsetY * this.surface.ratio }
const shape = this.mouseShape(pos, id)
if (this.bindings[id]) {
this.bindings[id](shape)
}
if (this.mouseOrigin) {
this.commander.commit(shape, false, e.which !== 1)
this.surface.clearGuide()
this.surface.drawGuide(shape)
}
}
this.onMouseUp = (e, id = 'mouse-up') => {
const pos = { x: e.offsetX * this.surface.ratio, y: e.offsetY * this.surface.ratio }
const shape = this.mouseShape(pos, id)
if (this.bindings[id]) {
this.bindings[id](shape)
}
if (this.mouseOrigin) {
this.commander.commit(shape, true, e.which !== 1)
}
this.mouseOrigin = null
this.surface.clearGuide()
}
this.onMouseOver = (e) => {
this.mouseOrigin = null
}
this.onMouseOut = (e) => {
this.mouseOrigin = null
}
this.parseFile = (file) => {
if (file.name.indexOf('.lisp') > -1) {
this.source.read(file, this.whenOpen)
this.log('Loaded ' + file.name)
} else if (file.type.substr(0, 5) === 'image') {
const img = new Image()
img.onload = () => {
this.cache.set(file.name, img)
this.commander.injectPath(file.name)
this.log('Loaded ' + file.name)
}
img.src = URL.createObjectURL(file)
} else {
console.warn('Unknown format', file)
}
}
this.onDrag = (e) => {
e.stopPropagation()
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
}
this.onDrop = (e) => {
e.preventDefault()
e.stopPropagation()
for (const file of e.dataTransfer.files) {
this.parseFile(file)
}
}
this.cache = {
data: {},
set: (key, content) => {
this.log((this.cache.data[key] ? 'Updated ' : 'Stored ') + key)
this.cache.data[key] = content
},
get: (key) => {
return this.cache.data[key]
}
}
this.mouseShape = (position, type) => {
if (!this.mouseOrigin) { return }
const x = position.x
const y = position.y
const xy = x + ' ' + y
const pos = { x, y }
const line = {
a: { x: this.mouseOrigin.x, y: this.mouseOrigin.y },
b: { x: pos.x, y: pos.y }
}
const size = { w: line.a.x ? pos.x - line.a.x : 0, h: line.a.y ? pos.y - line.a.y : 0 }
const rect = {
x: line.a.x,
y: line.a.y,
w: size.w,
h: size.h
}
const wh = rect.w + ' ' + rect.h
const d = Math.sqrt(((line.a.x - line.b.x) * (line.a.x - line.b.x)) + ((line.a.y - line.b.y) * (line.a.y - line.b.y))).toFixed(2)
const r = d
const a = Math.atan2(pos.y - line.a.y, pos.x - line.a.x).toFixed(2)
const circle = {
cx: line.a.x,
cy: line.a.y,
r: d
}
const arc = {
cx: line.a.x,
cy: line.a.y,
r: d,
sa: 0,
ea: a
}
return { x, y, xy, wh, d, r, a, line, rect, pos, size, circle, arc, type, 'is-down': type !== 'mouse-up' ? true : null }
}
}
export default Client

327
src/browser/Commander.js Normal file
View File

@@ -0,0 +1,327 @@
'use strict'
function Commander (client) {
this.el = document.createElement('div')
this.el.id = 'commander'
this._input = document.createElement('textarea')
this._status = document.createElement('div'); this._status.id = 'status'
this._log = document.createElement('div'); this._log.id = 'log'
this._docs = document.createElement('div'); this._docs.id = 'help'
this._eval = document.createElement('a'); this._eval.id = 'eval'
this.isVisible = true
this.install = function (host) {
this.el.appendChild(this._input)
this._status.appendChild(this._log)
this._status.appendChild(this._docs)
this._status.appendChild(this._eval)
this.el.appendChild(this._status)
host.appendChild(this.el)
this._eval.setAttribute('title', 'Eval(c-R)')
this._input.setAttribute('autocomplete', 'off')
this._input.setAttribute('autocorrect', 'off')
this._input.setAttribute('autocapitalize', 'off')
this._input.setAttribute('spellcheck', 'false')
this._input.addEventListener('input', this.onInput)
this._input.addEventListener('click', this.onClick)
this._eval.addEventListener('click', () => { this.eval() })
// this._input.onkeydown = (e) => {
// const cursorIndex = this._input.selectionStart
// switch(e.code) {
// case 'Tab':
// e.preventDefault()
// for(let i = cursorIndex - 1; i > 0; i--) {
// let char = this._input.value[i]
// if(char !== ' ') {
// if(this._input.value[i] == '\n') {
// this.inject(' ')
// return
// }
// // else {
// // let start = this._input.value.indexOf(')', cursorIndex)
// // if(start !== -1) {
// // this._input.selectionStart = start
// // }
// // }
// break
// }
// }
// let jumpTo = this._input.value.indexOf(/[^\w]/g, cursorIndex + 1)
// if(jumpTo !== -1) {
// console.log(jumpTo)
// this._input.selectionStart = jumpTo
// }
// // if('\n(;)'.includes(this._input.value[cursorIndex])) {
// // this._input.selectionStart = cursorIndex + 1
// // return
// // }
// break
// case 'Backspace':
// // If the cursor is in the middle of a "()" expand the cursor to delete both
// if(cursorIndex == this._input.selectionEnd &&
// this._input.value[cursorIndex -1] == '(' &&
// this._input.value[cursorIndex] == ')') {
// this._input.selectionStart--
// this._input.selectionEnd++
// }
// }
// }
client.surface.maximize()
}
this.start = function () {
this.show()
this._input.value = this.splash
setTimeout(() => { this.eval() }, 1000)
this.setStatus('Ready.')
}
this.eval = (txt = this._input.value) => {
if (this._input.value.indexOf('$') > -1) { txt = this.clean(txt) }
client.bindings = {}
client.lain.run(`(${txt})`)
this.feedback()
}
this.evalSelection = () => {
const value = this._input.value.substr(this._input.selectionStart, this._input.selectionEnd)
client.lain.run(`(${value})`)
this.feedback()
}
this.load = function (txt) {
this._input.value = txt
this.eval(txt)
}
this.clear = function () {
this.load('')
}
this.cleanup = function () {
this._input.value = this.clean(this._input.value)
this.lint()
this.eval()
}
this.update = function () {
}
this.onInput = () => {
this.setStatus()
}
this.onClick = () => {
this.setStatus()
}
this.clean = function (input) {
const keywords = ['$pos+', '$pos', '$rect', '$line', '$x', '$y', '$xy']
for (const word of keywords) {
input = input.replace(word, '').trim()
}
return input
}
this.setStatus = function (msg) {
// Logs
if (msg && msg !== this._log.textContent) {
this._log.textContent = `${msg}`
}
this._docs.textContent = this.getDocs()
}
// Injection
this.cache = this._input.value
this.capture = function () {
if (this._input.value.indexOf('$') < 0) { return }
this.cache = this._input.value
}
this.inject = function (injection, at = this._input.selectionStart) {
this._input.value = this._input.value.substring(0, this._input.selectionStart) + injection + this._input.value.substring(this._input.selectionEnd)
this._input.selectionEnd = at + injection.length
}
this.injectPath = function (path) {
if (this._input.value.indexOf('$') < 0) { return }
this._input.value = this._input.value.replace('$path', `"${path}"`)
}
// Helpers
this.commit = function (shape, end = false, run = false) {
if (this.cache.indexOf('$') < 0) { return }
const segs = this.cache.split('$')
const words = segs[1].split(' ')
const word = words[0].split(/[^A-Za-z]/)[0]
const append = words[0].indexOf('+') > -1
if (word === 'drag') {
this.cache = this.cache.replace('$drag', '(drag $rect $line)')
} else if (word === 'view') {
this.cache = this.cache.replace('$view', '(view $rect $rect)')
} else if (word === 'poly') {
this.cache = this.cache.replace('$poly', '(poly $pos+)')
} else if (word === 'move') {
this.cache = this.cache.replace('$move', '(transform:move $wh)')
} else if (word === 'rotate') {
this.cache = this.cache.replace('$rotate', '(transform:rotate $a)')
}
if (shape[word]) {
if (append) {
this._input.value = this.cache.replace('$' + word + '+', this.template(shape[word], word) + ' $' + word + '+')
} else {
this._input.value = this.cache.replace('$' + word, this.template(shape[word], word))
}
}
if (end === true) {
this.cache = this._input.value
}
if (run === true) {
this.eval()
}
}
this.template = function (shape, word) {
if (word === 'rect') { return `(rect ${shape.x} ${shape.y} ${shape.w} ${shape.h})` }
if (word === 'pos') { return `(pos ${shape.x} ${shape.y})` }
if (word === 'line') { return `(line ${shape.a.x} ${shape.a.y} ${shape.b.x} ${shape.b.y})` }
if (word === 'circle') { return `(circle ${shape.cx} ${shape.cy} ${shape.r})` }
if (word === 'arc') { return `(arc ${shape.cx} ${shape.cy} ${shape.r} ${shape.sa} ${shape.ea})` }
if (word === 'x' || word === 'y' || word === 'xy' || word === 'wh' || word === 'a' || word === 'r') { return `${shape}` }
return ''
}
// Display
this.show = (expand = false) => {
if (this.isVisible === true && expand !== true) { return }
client.el.className = expand ? 'expand' : ''
this.isVisible = true
this._input.focus()
}
this.hide = () => {
if (this.isVisible !== true) { return }
client.el.className = 'hidden'
this.isVisible = false
this._input.blur()
}
this.toggle = (expand = false) => {
if (this.isVisible !== true) {
this.show(expand)
} else {
this.hide()
}
}
this.length = function () {
return this._input.value.split('\n').length
}
this.feedback = function () {
this._eval.className = 'active'
setTimeout(() => { this._eval.className = '' }, 150)
}
// Docs
this.getCurrentWord = () => {
const pos = this._input.value.substr(0, this._input.selectionStart).lastIndexOf('(')
return this._input.value.substr(pos).split(' ')[0].replace(/\(/g, '').replace(/\)/g, '').trim()
}
this.getCurrentFunction = () => {
const word = this.getCurrentWord()
let mostSimilar = ''
if (client.library[word]) { return word }
for (const id of Object.keys(client.library)) {
if (id.substr(0, word.length) === word) {
mostSimilar = id
}
}
return mostSimilar
}
this.getDocs = (id) => {
const name = this.getCurrentFunction()
const fn = client.library[name]
if (!fn) { return }
const fnString = fn.toString()
if (fnString.indexOf(') => {') < 0) { return }
const fnParams = fnString.split(') => {')[0].substr(1).split(',').reduce((acc, item) => { return `${acc}${item.indexOf('=') > -1 ? '~' + item.split('=')[0].trim() : item} ` }, '').trim()
return `(${(name + ' ' + fnParams).trim()})`
}
this.lint = function () {
const value = this._input.value
if (value.split('(').length !== value.split(')').length) {
return client.log('Uneven number of parens.')
}
this._input.value = lintLISP(value)
}
// Splash
this.splash = `; Ronin v2.50
(def logo-path "M60,60 L195,60 A45,45 0 0,1 240,105 A45,45 0 0,1 195,150 L60,150 M195,150 A45,45 0 0,1 240,195 L240,240 ")
(clear)
(resize 600 600)
(stroke
(svg 140 140 logo-path) "black" 7)`
}
function lintLISP (str) {
// cleanup
let val = str.replace(/\n/g, '').replace(/ \)/g, ')').replace(/ +(?= )/g, '').replace(/\( \(/g, '((').replace(/\) \)/g, '))').trim()
// begin
let depth = 0
for (let i = 0; i < val.length; i++) {
const c = val.charAt(i)
depth += c === '(' ? 1 : c === ')' ? -1 : 0
// Pad comments
if (c === ';') {
const indent = '\n' + (' '.repeat(depth))
val = [val.slice(0, i), `${indent}`, val.slice(i)].join('')
i += indent.length
}
// Don't pad when closing on next char
if (c === '(' && val.charAt(i + 1) !== ')') {
const indent = '\n' + (' '.repeat(depth - 1))
val = [val.slice(0, i), `${indent}`, val.slice(i)].join('')
i += indent.length
}
// Add linebreak after paren at depth 0
if (c === ')' && depth === 0) {
val = [val.slice(0, i), ')\n', val.slice(i + 1)].join('')
}
}
// Space out comments
val = val.split('\n').map((line) => { return line.substr(0, 2) === '; ' ? `\n${line}\n` : line }).join('\n')
return val.trim()
}
export default Commander

54
src/browser/DisplaySurface.js Executable file
View File

@@ -0,0 +1,54 @@
import Surface from "../Surface.js"
import { classExtends } from "../util.js"
const DisplaySurface = function(client) {
classExtends(this, Surface, client)
this._canvas = document.createElement('canvas')
this._canvas.id = 'surface'
this._guide = document.createElement('canvas')
this._guide.id = 'guide'
this._guide.setAttribute('tabindex', '1') // focus is necessary to capture keyboard events
this.ratio = window.devicePixelRatio
this.context = this._canvas.getContext('2d')
this.guide = this._guide.getContext('2d')
this.createCanvas = () =>
document.createElement('canvas')
this.install = function (host) {
host.appendChild(this._canvas)
host.appendChild(this._guide)
window.addEventListener('resize', (e) => { this.onResize() }, false)
this._guide.addEventListener('mousedown', client.onMouseDown, false)
this._guide.addEventListener('mousemove', client.onMouseMove, false)
this._guide.addEventListener('mouseup', client.onMouseUp, false)
this._guide.addEventListener('mouseover', client.onMouseOver, false)
this._guide.addEventListener('mouseout', client.onMouseOut, false)
this._guide.addEventListener('keydown', client.onKeyDown, false)
this._guide.addEventListener('keyup', client.onKeyUp, false)
this._guide.addEventListener('keypress', client.onKeyPress, false)
}
// Clone the method
const genericResize = this.resize.bind(this)
this.resize = (size, fit) => {
genericResize(size, fit)
this._guide.width = size.w
this._guide.height = size.h
this._canvas.style.width = (size.w / this.ratio) + 'px'
this._canvas.style.height = (size.h / this.ratio) + 'px'
this._guide.style.width = (size.w / this.ratio) + 'px'
this._guide.style.height = (size.h / this.ratio) + 'px'
}
this.toggleGuides = function () {
this._guide.className = this._guide.className === 'hidden' ? '' : 'hidden'
}
this.toDataURL = () => {
return this._canvas.toDataURL()
}
}
export default DisplaySurface

99
src/browser/Source.js Normal file
View File

@@ -0,0 +1,99 @@
function Source (client) {
this.cache = {}
this.install = () => {
}
this.start = () => {
this.new()
}
this.new = () => {
console.log('Source', 'New file..')
this.cache = {}
}
this.open = (ext, callback, store = false) => {
console.log('Source', 'Open file..')
const input = document.createElement('input')
input.type = 'file'
input.onchange = (e) => {
const file = e.target.files[0]
if (file.name.indexOf('.' + ext) < 0) { console.warn('Source', `Skipped ${file.name}`); return }
this.read(file, callback, store)
}
input.click()
}
this.load = (ext, callback) => {
console.log('Source', 'Load files..')
const input = document.createElement('input')
input.type = 'file'
input.setAttribute('multiple', 'multiple')
input.onchange = (e) => {
for (const file of e.target.files) {
if (file.name.indexOf('.' + ext) < 0) { console.warn('Source', `Skipped ${file.name}`); continue }
this.read(file, this.store)
}
}
input.click()
}
this.store = (file, content) => {
console.info('Source', 'Stored ' + file.name)
this.cache[file.name] = content
}
this.save = (name, content, type = 'text/plain', callback) => {
this.saveAs(name, content, type, callback)
}
this.saveAs = (name, ext, content, type = 'text/plain', callback) => {
console.log('Source', 'Save new file..')
this.write(name, ext, content, type, callback)
}
// I/O
this.read = (file, callback, store = false) => {
const reader = new FileReader()
reader.onload = (event) => {
const res = event.target.result
if (callback) { callback(file, res) }
if (store) { this.store(file, res) }
}
reader.readAsText(file, 'UTF-8')
}
this.write = (name, ext, content, type, settings = 'charset=utf-8') => {
const link = document.createElement('a')
link.setAttribute('download', `${name}-${timestamp()}.${ext}`)
if (type === 'image/png' || type === 'image/jpeg') {
link.setAttribute('href', content)
} else {
link.setAttribute('href', 'data:' + type + ';' + settings + ',' + encodeURIComponent(content))
}
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
}
function timestamp (d = new Date(), e = new Date(d)) {
return `${arvelie()}-${neralie()}`
}
function arvelie (date = new Date()) {
const start = new Date(date.getFullYear(), 0, 0)
const diff = (date - start) + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000)
const doty = Math.floor(diff / 86400000) - 1
const y = date.getFullYear().toString().substr(2, 2)
const m = doty === 364 || doty === 365 ? '+' : String.fromCharCode(97 + Math.floor(doty / 14)).toUpperCase()
const d = `${(doty === 365 ? 1 : doty === 366 ? 2 : (doty % 14)) + 1}`.padStart(2, '0')
return `${y}${m}${d}`
}
function neralie (d = new Date(), e = new Date(d)) {
const ms = e - d.setHours(0, 0, 0, 0)
return (ms / 8640 / 10000).toFixed(6).substr(2, 6)
}
}
export default Source

172
src/browser/Theme.js Normal file
View File

@@ -0,0 +1,172 @@
'use strict'
/* global localStorage */
/* global FileReader */
/* global DOMParser */
function Theme (client) {
this.el = document.createElement('style')
this.el.type = 'text/css'
this.active = {}
this.default = {
background: '#eeeeee',
f_high: '#0a0a0a',
f_med: '#4a4a4a',
f_low: '#6a6a6a',
f_inv: '#111111',
b_high: '#a1a1a1',
b_med: '#c1c1c1',
b_low: '#ffffff',
b_inv: '#ffb545'
}
// Callbacks
this.onLoad = () => {}
this.install = (host = document.body) => {
window.addEventListener('dragover', this.drag)
window.addEventListener('drop', this.drop)
host.appendChild(this.el)
}
this.start = () => {
console.log('Theme', 'Starting..')
if (isJson(localStorage.theme)) {
const storage = JSON.parse(localStorage.theme)
if (isValid(storage)) {
console.log('Theme', 'Loading theme in localStorage..')
this.load(storage)
return
}
}
this.load(this.default)
}
this.open = () => {
console.log('Theme', 'Open theme..')
const input = document.createElement('input')
input.type = 'file'
input.onchange = (e) => {
this.read(e.target.files[0], this.load)
}
input.click()
}
this.load = (data) => {
const theme = this.parse(data)
if (!isValid(theme)) { console.warn('Theme', 'Invalid format'); return }
console.log('Theme', 'Loaded theme!')
this.el.innerHTML = `:root {
--background: ${theme.background};
--f_high: ${theme.f_high};
--f_med: ${theme.f_med};
--f_low: ${theme.f_low};
--f_inv: ${theme.f_inv};
--b_high: ${theme.b_high};
--b_med: ${theme.b_med};
--b_low: ${theme.b_low};
--b_inv: ${theme.b_inv};
}`
localStorage.setItem('theme', JSON.stringify(theme))
this.active = theme
if (this.onLoad) {
this.onLoad(data)
}
}
this.reset = () => {
this.load(this.default)
}
this.set = (key, val) => {
if (!val) { return }
const hex = (`${val}`.substr(0, 1) !== '#' ? '#' : '') + `${val}`
if (!isColor(hex)) { console.warn('Theme', `${hex} is not a valid color.`); return }
this.active[key] = hex
}
this.get = (key) => {
return this.active[key]
}
this.parse = (any) => {
if (isValid(any)) { return any }
if (isJson(any)) { return JSON.parse(any) }
if (isHtml(any)) { return extract(any) }
}
// Drag
this.drag = (e) => {
e.stopPropagation()
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
}
this.drop = (e) => {
e.preventDefault()
const file = e.dataTransfer.files[0]
if (file.name.indexOf('.svg') > -1) {
this.read(file, this.load)
}
e.stopPropagation()
}
this.read = (file, callback) => {
const reader = new FileReader()
reader.onload = (event) => {
callback(event.target.result)
}
reader.readAsText(file, 'UTF-8')
}
// Helpers
function extract (xml) {
const svg = new DOMParser().parseFromString(xml, 'text/xml')
try {
return {
background: svg.getElementById('background').getAttribute('fill'),
f_high: svg.getElementById('f_high').getAttribute('fill'),
f_med: svg.getElementById('f_med').getAttribute('fill'),
f_low: svg.getElementById('f_low').getAttribute('fill'),
f_inv: svg.getElementById('f_inv').getAttribute('fill'),
b_high: svg.getElementById('b_high').getAttribute('fill'),
b_med: svg.getElementById('b_med').getAttribute('fill'),
b_low: svg.getElementById('b_low').getAttribute('fill'),
b_inv: svg.getElementById('b_inv').getAttribute('fill')
}
} catch (err) {
console.warn('Theme', 'Incomplete SVG Theme', err)
}
}
function isValid (json) {
if (!json) { return false }
if (!json.background || !isColor(json.background)) { return false }
if (!json.f_high || !isColor(json.f_high)) { return false }
if (!json.f_med || !isColor(json.f_med)) { return false }
if (!json.f_low || !isColor(json.f_low)) { return false }
if (!json.f_inv || !isColor(json.f_inv)) { return false }
if (!json.b_high || !isColor(json.b_high)) { return false }
if (!json.b_med || !isColor(json.b_med)) { return false }
if (!json.b_low || !isColor(json.b_low)) { return false }
if (!json.b_inv || !isColor(json.b_inv)) { return false }
return true
}
function isColor (hex) {
return /^#([0-9A-F]{3}){1,2}$/i.test(hex)
}
function isJson (text) {
try { JSON.parse(text); return true } catch (error) { return false }
}
function isHtml (text) {
try { new DOMParser().parseFromString(text, 'text/xml'); return true } catch (error) { return false }
}
}
export default Theme

76
src/browser/index.html Normal file
View File

@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ronin</title>
<style>
* { margin:0;padding:0;border:0;outline:0;text-decoration:none;font-weight:inherit;font-style:inherit;color:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;list-style:none;border-collapse:collapse;border-spacing:0; -webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;}
body { margin:0px; padding:0px; overflow:hidden; font-family: monospace; background:000; -webkit-app-region: drag; -webkit-user-select: none; font-size:12px; transition: background 500ms}
*:focus { outline: none; }
#ronin { height: calc(100vh - 60px); width:calc(100vw - 60px); -webkit-app-region: drag; padding: 30px;overflow: hidden; }
#ronin #wrapper { overflow: hidden; position: relative; }
#ronin #wrapper #commander { z-index: 9000;position: relative;width: calc(50vw - 30px);height: calc(100vh - 60px);-webkit-app-region: no-drag;padding-right: 30px;transition: margin-left 250ms;}
#ronin #wrapper #commander textarea { background: none; width: 100%; height: calc(100vh - 105px); resize: none; font-size: 12px;line-height: 15px; padding-right: 15px}
#ronin #wrapper #commander #status { position: absolute; bottom: 0px; line-height: 15px; height: 30px; overflow: hidden; width: calc(100% - 75px); padding-left:45px;}
#ronin #wrapper #commander #status #eval { display: block; width: 26px; height: 26px; position: absolute; top: 0px; border-radius: 15px; left:0px; cursor: pointer; border:2px solid #fff; transition: background-color 250ms, border-color 250ms}
#ronin #wrapper #commander #status #eval:hover { background: none }
#ronin.expand #wrapper #commander { width:100%; }
#ronin #surface, #ronin #guide { position: absolute; top:0px; -webkit-user-select: none;-webkit-app-region: no-drag; background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'><circle cx='10' cy='10' r='1' fill='%23555'></circle></svg>"); background-size: 10px 10px; background-position: -4px -4px; width:100%; height:100%; transition: left 250ms, opacity 250ms; opacity: 1; }
#ronin.hidden #wrapper #commander { margin-left:-40vw; }
#ronin.hidden #surface, #ronin.hidden #guide { left:0; }
#ronin #guide.hidden { opacity: 0 }
#ronin.hidden #wrapper #commander { margin-left:-50vw; }
#ronin #surface,#ronin #guide { left:50vw; }
#ronin #guide { background:none; }
#ronin #surface { border-radius: 2px }
#acels { position: fixed;width: 30px;background: red;top: 0;left: 0; width: 100vw; color:black; background:white; font-size:11px; line-height: 20px; transition: margin-top 0.25s; z-index: 9999; padding-left: 25px; }
#acels.hidden { margin-top:-20px; }
#acels.hidden > li > ul > li { display: none }
#acels > li { float: left; position: relative; cursor: pointer; padding:0px 5px; display: inline-block; }
#acels > li:hover { background: black; color:white; }
#acels > li > ul { display: none; position: absolute; background:white; position: absolute; top:20px; left:0px; color:black; width: 200px}
#acels > li:hover > ul { display: block; }
#acels > li > ul > li { padding: 0px 10px; display: block }
#acels > li > ul > li:hover { background: #ccc; }
#acels > li > ul > li > i { display: inline-block; float: right; color: #aaa; }
body { background:var(--background); }
#ronin #wrapper { background: var(--background); }
#ronin #wrapper #commander { background:var(--background); }
#ronin #wrapper #commander textarea { color:var(--f_high); }
#ronin #wrapper #commander #status { color:var(--f_med); }
#ronin #wrapper #commander #status #source { color:var(--f_low); }
#ronin #wrapper #commander #status #eval { background-color: var(--b_inv); border-color: var(--b_inv) }
#ronin #wrapper #commander #status #eval.active { background:var(--f_high); border-color:var(--f_high); transition: none }
::selection { background-color:var(--b_inv); color:var(--f_inv); text-decoration:none }
@media (min-width: 720px) {
#ronin #wrapper #commander { width:350px; }
#ronin.hidden #wrapper #commander { margin-left:-380px; }
#ronin #surface,#ronin #guide { left:380px; }
}
</style>
</head>
<body>
<script type="module">
import Client from './Client.js'
const client = new Client()
client.install(document.body)
window.addEventListener('load', () => {
client.start()
})
window.client = client
</script>
</body>
</html>

16
src/browser/index.js Normal file
View File

@@ -0,0 +1,16 @@
import Path from 'path'
import FS from 'fs/promises'
import http from 'http'
const root = Path.join(__dirname, '../')
function respond(request, response) {
if(request.url == '/') {
}
}
const server = http.createServer()
server.on('request', respond)
server.listen(8080)

94
src/cli/Client.js Executable file
View File

@@ -0,0 +1,94 @@
import Lain from "../Lain.js";
import Library from "../Library.js";
import NodeSurface from "./NodeSurface.js";
import Source from "./Source.js";
import Path from 'path'
import FS from 'fs/promises'
import { Image, Path2D } from "@napi-rs/canvas";
// Polyfill
global.Image = Image
global.Path2D = Path2D
function Client(directory) {
this.workingDirectory = directory
this.surface = new NodeSurface(this)
this.library = new Library(this)
this.lain = new Lain(this.library)
this.source = new Source(this)
this.run = (args, program) => {
if(program.indexOf('$') > -1) {
program = this.replaceConstants(program, args)
}
this.surface.clear()
return this.lain.run('(' + program + ')')
}
this.bind = () => {
// Perhaps binding in the cli could work by piping in
// CSV. Events could be recorded in the web client and saved
// to the format
}
this.log = (...msg) => {
console.log('Evaluation:', ...msg)
}
this.cache = {
data: {},
set: (key, content) => {
this.log((this.cache.data[key] ? 'Updated ' : 'Stored ') + key)
this.cache.data[key] = content
},
get: (key) => {
return this.cache.data[key]
},
// Async
load: (pathResolvable) => {
let key = resolvePath(pathResolvable)
return openImage(key)
},
// Async
resolve: (pathResolvable) => {
let key = resolvePath(pathResolvable),
out = this.cache.get(key)
if(out) {
return Promise.resolve(out)
} else {
return openImage(key)
}
}
}
const replaceConstants = (txt, args) => {
return txt.replaceAll(/\$(\d+)/g, (match, num) => {
return JSON.stringify(args[parseInt(num)])
})
}
const resolvePath = pathResolvable => {
return Path.isAbsolute(pathResolvable) ? Path.normalize(pathResolvable) : Path.join(this.workingDirectory, pathResolvable)
}
const openImage = async (key) => {
let buf = await FS.readFile(key)
.catch(err => {
console.error('Source', `Could not load image at path "${key}"`, err)
process.exit()
})
let img = new Image()
img.src = buf
this.cache.set(key, buf)
return buf
}
}
export default Client

44
src/cli/NodeSurface.js Executable file
View File

@@ -0,0 +1,44 @@
import { createCanvas } from "@napi-rs/canvas"
import Surface from "../Surface.js"
import { classExtends } from "../util.js"
function noop () {}
function NodeSurface (client) {
classExtends(this, Surface, client)
// TODO: Find proper default canvas size
this._canvas = createCanvas(500, 500)
this._canvas.id = 'surface'
this.context = this._canvas.getContext('2d')
this.createCanvas = () =>
createCanvas()
this.install = noop
this.clearGuide = noop
// this.toStream = (type, quality) => {
// switch(type) {
// case 'image/png':
// return this._canvas.toBuffer(type)
// case 'image/jpg':
// case 'image/jpeg':
// return this._canvas.createJPEGStream()
// case 'image/pdf':
// return this._canvas.createPDFStream()
// default:
// throw new Error(`Cannot handle filetype with extension "${ext}"`)
// }
// }
this.toDataURL = (type = 'image/png') => {
return this._canvas.toBuffer(type)
}
}
export default NodeSurface

15
src/cli/Source.js Executable file
View File

@@ -0,0 +1,15 @@
import FS from 'fs'
import Path from 'path'
function Source (client) {
// Needed by Library
this.write = (name, ext, content, type, settings = 'charset=utf-8') => {
let path = Path.extname(name) == '' ? `${name}.${ext}` : name
path = Path.isAbsolute(`${name}.${ext}`) ? path : Path.join(client.workingDirectory, path)
return FS.writeFileSync(path, content)
}
}
export default Source

13
src/cli/index.js Executable file
View File

@@ -0,0 +1,13 @@
import Path from 'path'
import FS from 'fs'
import Client from './Client.js'
let target = process.argv[2],
client = new Client(process.cwd())
if(!Path.isAbsolute(target) )
target = Path.join(client.workingDirectory, target)
let program = FS.readFileSync(target, 'utf8')
client.run(process.argv.slice(3), program)

9
src/index.js Normal file
View File

@@ -0,0 +1,9 @@
import Path from 'path'
let target = process.argv[2]
if(target == undefined || target == 'edit') {
import('./browser/index.js')
} else {
import('./cli/index.js')
}

17
src/util.js Executable file
View File

@@ -0,0 +1,17 @@
function classExtends (context, parentConstructor, ...superArgs) {
let parent = parentConstructor.call(context, ...superArgs)
for(let key in parent) {
let value = parent[key]
if(typeof value == 'function') {
context[key] = value.bind(context)
} else {
context[key] = value
}
}
}
export {
classExtends
}