file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
rollup.config.js
JavaScript
import json from '@rollup/plugin-json'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import nodeResolve from 'rollup-plugin-node-resolve'; import serve from 'rollup-plugin-serve'; import { terser } from 'rollup-plugin-terser'; import typescript from 'rollup-plugin-typescript2'; const dev = process.env.ROLLUP_WATCH; const serveopts = { contentBase: ['./dist'], host: '0.0.0.0', port: 5000, allowCrossOrigin: true, headers: { 'Access-Control-Allow-Origin': '*', }, }; const plugins = [ nodeResolve({ browser: true, // This instructs the plugin to use // the "browser" property in package.json }), commonjs(), typescript({ sourceMap: false }), json(), babel({ exclude: 'node_modules/**', }), dev && serve(serveopts), !dev && terser(), ]; export default [ { input: 'src/grid-view.ts', output: { dir: 'dist', format: 'es', sourcemap: true, }, plugins: [...plugins], }, ];
zsarnett/Custom-Grid-View
109
Custom Drag and Drop Grid for Home Assistant
TypeScript
zsarnett
Zack Barett
src/functions.ts
TypeScript
/* eslint-disable @typescript-eslint/ban-ts-ignore */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { LovelaceConfig } from 'custom-card-helpers/dist/types'; export const replaceView = (config: LovelaceConfig, viewIndex: number, viewConfig: any): LovelaceConfig => ({ ...config, views: config.views.map((origView, index) => (index === viewIndex ? viewConfig : origView)), }); /* eslint-disable @typescript-eslint/explicit-function-return-type */ export const afterNextRender = (cb: () => void): void => { requestAnimationFrame(() => setTimeout(cb, 0)); }; export const nextRender = () => { return new Promise(resolve => { afterNextRender(resolve); }); };
zsarnett/Custom-Grid-View
109
Custom Drag and Drop Grid for Home Assistant
TypeScript
zsarnett
Zack Barett
src/grid-view.ts
TypeScript
/* eslint-disable @typescript-eslint/ban-ts-ignore */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { mdiPlus, mdiResizeBottomRight } from '@mdi/js'; import { computeCardSize, computeRTL, fireEvent, HomeAssistant, LovelaceCard, LovelaceViewConfig, } from 'custom-card-helpers'; import { css, CSSResult, customElement, html, internalProperty, LitElement, property, PropertyValues, TemplateResult, } from 'lit-element'; import 'lit-grid-layout'; import { classMap } from 'lit-html/directives/class-map'; import { v4 as uuidv4 } from 'uuid'; import { nextRender, replaceView } from './functions'; import './hui-grid-card-options'; import { HuiGridCardOptions } from './hui-grid-card-options'; const mediaQueryColumns = [2, 6, 9, 12]; interface LovelaceGridCard extends LovelaceCard, HuiGridCardOptions { key: string; grid?: { key: string; width: number; height: number; posX: number; posY: number; }; } const RESIZE_HANDLE = document.createElement('div') as HTMLElement; RESIZE_HANDLE.style.cssText = 'width: 100%; height: 100%; cursor: se-resize; fill: var(--primary-text-color)'; RESIZE_HANDLE.innerHTML = ` <svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" > <g><path d=${mdiResizeBottomRight}></path></g> </svg> `; @customElement('grid-dnd') export class GridView extends LitElement { @property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public lovelace?: any; @property({ type: Number }) public index?: number; @property({ attribute: false }) public cards: Array<LovelaceGridCard> = []; @property({ attribute: false }) public badges: any[] = []; @internalProperty() private _columns?: number; @internalProperty() private _layout?: Array<{ width: number; height: number; posX: number; posY: number; key: string; }>; @internalProperty() public _cards: { [key: string]: LovelaceCard | any; } = {}; private _config?: LovelaceViewConfig; private _layoutEdit?: Array<{ width: number; height: number; posX: number; posY: number; key: string; }>; private _createColumnsIteration = 0; private _mqls?: MediaQueryList[]; public constructor() { super(); this.addEventListener('iron-resize', (ev: Event) => ev.stopPropagation()); } public setConfig(config: LovelaceViewConfig): void { this._config = config; } protected render(): TemplateResult { return html` ${this.lovelace.editMode ? html` <div class="toolbar"> <mwc-button @click=${this._saveView} raised>Save Layout</mwc-button> </div> ` : ''} <div id="badges" style=${this.badges.length > 0 ? 'display: block' : 'display: none'}> ${this.badges.map( badge => html` ${badge} `, )} </div> <lit-grid-layout rowHeight="40" .containerPadding=${[8, 8]} .margin=${[8, 8]} .resizeHandle=${RESIZE_HANDLE} .itemRenderer=${this._itemRenderer} .layout=${this._layout} .columns=${this._columns} .dragHandle=${'.overlay'} .dragDisabled=${!this.lovelace?.editMode} .resizeDisabled=${!this.lovelace?.editMode} @item-changed=${this._saveLayout} ></lit-grid-layout> ${this.lovelace?.editMode ? html` <mwc-fab class=${classMap({ rtl: computeRTL(this.hass!), })} .title=${this.hass!.localize('ui.panel.lovelace.editor.edit_card.add')} @click=${this._addCard} > <ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon> </mwc-fab> ` : ''} `; } protected firstUpdated(): void { this._updateColumns = this._updateColumns.bind(this); this._mqls = [300, 600, 900, 1200].map(width => { const mql = matchMedia(`(min-width: ${width}px)`); mql.addEventListener('change', this._updateColumns); return mql; }); this._updateCardsWithID(); this._updateColumns(); } protected updated(changedProperties: PropertyValues): void { super.updated(changedProperties); if (changedProperties.has('hass')) { const oldHass = changedProperties.get('hass') as HomeAssistant; if ((oldHass && this.hass!.dockedSidebar !== oldHass.dockedSidebar) || (!oldHass && this.hass)) { this._updateColumns(); } if (changedProperties.size === 1) { return; } } const oldLovelace = changedProperties.get('lovelace') as any | undefined; if ( (changedProperties.has('lovelace') && (oldLovelace?.config !== this.lovelace?.config || oldLovelace?.editMode !== this.lovelace?.editMode)) || changedProperties.has('_columns') ) { if (!this._layout?.length) { this._createLayout(); return; } this._createCards(); } if (changedProperties.has('lovelace') && this.lovelace.editMode && !oldLovelace.editMode) { this._layoutEdit = this._layout; } if (changedProperties.has('lovelace') && !this.lovelace.editMode && oldLovelace.editMode) { this._layout = (this._config as any).layout; } } private _updateCardsWithID(): void { if (!this._config) { return; } if (this._config.cards!.filter(card => !card.layout?.key).length === 0) { return; } const cards = this._config.cards!.map(card => { if (card.layout?.key) { return card; } card = { ...card, layout: { key: card.layout?.key || uuidv4() } }; return card; }); const newConfig = { ...this._config, cards }; this.lovelace.saveConfig(replaceView(this.lovelace!.config, this.index!, newConfig)); } private async _createLayout(): Promise<void> { this._createColumnsIteration++; const iteration = this._createColumnsIteration; if (this._layout?.length) { return; } const newLayout: Array<{ width: number; height: number; posX: number; posY: number; key: string; minHeight: number; }> = []; let tillNextRender: Promise<unknown> | undefined; let start: Date | undefined; // Calculate the size of every card and determine in what column it should go for (const [index, card] of this.cards.entries()) { const cardConfig = this._config!.cards![index]; const currentLayout = (this._config as any).layout?.find(item => item.key === cardConfig.layout?.key); if (currentLayout) { newLayout.push(currentLayout); continue; } console.log('not in current layout: ', cardConfig); if (tillNextRender === undefined) { // eslint-disable-next-line no-loop-func tillNextRender = nextRender().then(() => { tillNextRender = undefined; start = undefined; }); } let waitProm: Promise<unknown> | undefined; // We should work for max 16ms (60fps) before allowing a frame to render if (start === undefined) { // Save the time we start for this frame, no need to wait yet start = new Date(); } else if (new Date().getTime() - start.getTime() > 16) { // We are working too long, we will prevent a render, wait to allow for a render waitProm = tillNextRender; } const cardSizeProm = computeCardSize(card); // @ts-ignore // eslint-disable-next-line no-await-in-loop const [cardSize] = await Promise.all([cardSizeProm, waitProm]); if (iteration !== this._createColumnsIteration) { // An other create columns is started, abort this one return; } const computedLayout = { width: 3, height: cardSize, key: cardConfig.layout?.key, }; newLayout.push({ ...computedLayout, ...currentLayout, }); } this._layout = newLayout; this._createCards(); } private _createCards(): void { const elements = {}; this.cards.forEach((card: LovelaceGridCard, index) => { const cardLayout = this._layout![index]; if (!cardLayout) { return; } card.editMode = this.lovelace?.editMode; let element = card; if (this.lovelace?.editMode) { const wrapper = document.createElement('hui-grid-card-options') as LovelaceGridCard; wrapper.hass = this.hass; wrapper.lovelace = this.lovelace; wrapper.path = [this.index!, index]; wrapper.appendChild(card); element = wrapper; } elements[cardLayout.key] = element; }); this._cards = elements; } private _saveLayout(ev: CustomEvent): void { this._layoutEdit = ev.detail.layout; } private async _saveView(): Promise<void> { const viewConf: any = { ...this._config, layout: this._layoutEdit, }; await this.lovelace?.saveConfig(replaceView(this.lovelace!.config, this.index!, viewConf)); } private _itemRenderer = (key: string): TemplateResult => { if (!this._cards) { return html``; } return html` ${this._cards[key]} `; }; private _addCard(): void { fireEvent(this, 'll-create-card' as any); } private _updateColumns(): void { if (!this._mqls) { return; } const matchColumns = this._mqls!.reduce((cols, mql) => cols + Number(mql.matches), 0); // Do -1 column if the menu is docked and open this._columns = Math.max(1, mediaQueryColumns[matchColumns - 1]); } static get styles(): CSSResult { return css` :host { display: block; box-sizing: border-box; padding: 4px 4px env(safe-area-inset-bottom); transform: translateZ(0); position: relative; color: var(--primary-text-color); background: var(--lovelace-background, var(--primary-background-color)); } lit-grid-layout { --placeholder-background-color: var(--accent-color); --resize-handle-size: 32px; } #badges { margin: 8px 16px; font-size: 85%; text-align: center; } mwc-fab { position: sticky; float: right; right: calc(16px + env(safe-area-inset-right)); bottom: calc(16px + env(safe-area-inset-bottom)); z-index: 5; } mwc-fab.rtl { float: left; right: auto; left: calc(16px + env(safe-area-inset-left)); } .toolbar { background-color: var(--divider-color); border-bottom-left-radius: var(--ha-card-border-radius, 4px); border-bottom-right-radius: var(--ha-card-border-radius, 4px); padding: 8px; } `; } } declare global { interface HTMLElementTagNameMap { 'grid-dnd': GridView; } }
zsarnett/Custom-Grid-View
109
Custom Drag and Drop Grid for Home Assistant
TypeScript
zsarnett
Zack Barett
src/hui-grid-card-options.ts
TypeScript
/* eslint-disable @typescript-eslint/no-non-null-assertion */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { mdiDelete, mdiPencil } from '@mdi/js'; import { computeCardSize, fireEvent, HomeAssistant, LovelaceCard } from 'custom-card-helpers'; import { css, CSSResult, customElement, LitElement, property, queryAssignedNodes } from 'lit-element'; import { html, TemplateResult } from 'lit-html'; @customElement('hui-grid-card-options') export class HuiGridCardOptions extends LitElement { @property({ attribute: false }) public hass?: HomeAssistant; @property({ attribute: false }) public lovelace?; @property({ type: Array }) public path?: [number, number]; @queryAssignedNodes() private _assignedNodes?: NodeListOf<LovelaceCard>; public getCardSize(): number | Promise<number> { return this._assignedNodes ? computeCardSize(this._assignedNodes[0]) : 1; } protected render(): TemplateResult { return html` <slot></slot> <div class="parent-card-actions"> <div class="overlay"></div> <div class="card-actions"> <mwc-icon-button .title=${this.hass!.localize('ui.panel.lovelace.editor.edit_card.edit')} @click=${this._editCard} > <ha-svg-icon .path=${mdiPencil}></ha-svg-icon> </mwc-icon-button> <mwc-icon-button .title=${this.hass!.localize('ui.panel.lovelace.editor.edit_card.delete')} @click=${this._deleteCard} > <ha-svg-icon .path=${mdiDelete}></ha-svg-icon> </mwc-icon-button> </div> </div> `; } private _editCard(): void { fireEvent(this, 'll-edit-card' as any, { path: this.path }); } private _deleteCard(): void { fireEvent(this, 'll-delete-card' as any, { path: this.path }); } static get styles(): CSSResult { return css` slot { pointer-events: none; z-index: 0; } .overlay { transition: all 0.25s; position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 1; opacity: 0; cursor: move; } .parent-card-actions:hover .overlay { outline: 2px solid var(--primary-color); background: rgba(0, 0, 0, 0.3); /* background-color: grey; */ opacity: 1; } .parent-card-actions { transition: all 0.25s; position: absolute; top: 0; left: 0; right: 0; bottom: 0; opacity: 0; } .parent-card-actions:hover { opacity: 1; } .card-actions { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; z-index: 2; position: absolute; left: 0; right: 0; bottom: 24px; color: white; } .card-actions > * { margin: 0 4px; border-radius: 24px; background: rgba(0, 0, 0, 0.7); } mwc-list-item { cursor: pointer; white-space: nowrap; } mwc-list-item.delete-item { color: var(--error-color); } .drag-handle { cursor: move; } `; } } declare global { interface HTMLElementTagNameMap { 'hui-grid-card-options': HuiGridCardOptions; } }
zsarnett/Custom-Grid-View
109
Custom Drag and Drop Grid for Home Assistant
TypeScript
zsarnett
Zack Barett
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Lit Grid Layout</title> <!-- <script src="https://unpkg.com/lit-grid-layout@1.1.10/dist/lit-grid-layout.js?module" crossorigin="anonymous" type="module" ></script> --> </head> <body style="margin: 0;"> <my-app></my-app> <script type="module"> import './dist/lit-grid-layout.js'; // import {html, LitElement} from 'https://cdn.skypack.dev/pin/lit-element@v2.4.0-1XOpe9DTEoAR5DmPqDi1/lit-element.js' import { html } from 'lit-html/lit-html.js'; import { LitElement } from 'lit-element/lit-element.js'; class MyItem extends LitElement { static get properties () { return { activated: { type: Boolean }, title: { type: String } }; } constructor () { super(); this.activated = false; if (!this.title) this.title = ''; } onClick () { this.activated = !this.activated; } render () { const itemBackgroundColor = this.activated ? 'lightgreen' : '#ccc'; const itemStyle = `background-color: ${itemBackgroundColor};`; return html` <style> .lit-grid-item { background-color: #ccc; border: 1px solid black; height: 100%; width: 100%; font-size: 24px; display: flex; position: relative; justify-content: center; align-items: center; } .drag-handle { position: absolute; top: 0; left: 0; cursor: move; line-height: 0; } </style> <div class="lit-grid-item" style="${itemStyle}"> <span style="cursor: pointer;" @click="${this.onClick}">${this.title}</span> <div class="drag-handle"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-grid-dots" width="24" height="24" viewBox="0 0 24 24" stroke-width="1.5" stroke="#607D8B" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z"/> <circle cx="5" cy="5" r="1" /> <circle cx="12" cy="5" r="1" /> <circle cx="19" cy="5" r="1" /> <circle cx="5" cy="12" r="1" /> <circle cx="12" cy="12" r="1" /> <circle cx="19" cy="12" r="1" /> <circle cx="5" cy="19" r="1" /> <circle cx="12" cy="19" r="1" /> <circle cx="19" cy="19" r="1" /> </svg> </div> </div>`; } } customElements.define('my-item', MyItem); function generateRandomLayout (n) { if (n < 0) throw new Error('Number of layout items must be positive'); const layout = []; for (let i = 0; i < n; i++) { var y = Math.ceil(Math.random() * 4) + 1; var x = Math.floor(Math.random() * 3) + 1; layout.push({ posX: 3 * (i % 4), posY: Math.floor(i / 6) * y, width: 3, height: y + 1, key: i.toString(), }); } return layout; } const mediaQueryColumns = [12,9,6,2, 6, 9, 12]; class MyApp extends LitElement { static get properties () { return { isSunnyMode: { type: Boolean }, index: { type: Number } }; } constructor () { super(); this.isSunnyMode = false; this.index = 0; console.log("generate"); this.layout = generateRandomLayout(50); } onSunnyButtonClick () { this.isSunnyMode = !this.isSunnyMode; } onNewLayoutClick () { this.layout = generateRandomLayout(50); } onColummnClick() { this.index +=1; } itemRenderer (itemKey) { return html` <my-item .title=${itemKey}> </my-item> `; } onLayoutChanged (event) { console.log(event); // this.layout = event.detail.layout; } updated(props) { console.log("props"); console.log(props); console.log(this.layout); } render () { console.log("render", [...this.layout]); const buttonText = this.isSunnyMode ? 'Switch to regular mode' : 'Switch to sunny mode'; const layoutBackgroundColor = this.isSunnyMode ? '#ffe493' : '#eee'; const sortStyle = 'masonry'; const dragHandle = '.drag-handle'; return html` <style> .container { margin: 5em auto auto auto; max-width: 1000px; } .highlighted-green { background-color: lightgreen; } .buttons-row { display: flex; flex-direction: row; justify-content: center; margin-top: 2.5em; } .layout-button { border: solid darkgrey; color: black; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; background-color: white; margin-left: 1em; margin-right: 1em; } </style> <div class="container"> <div> <p> Click on the item number to activate or deactivate that item, it will turn <span class="highlighted-green">green</span> when activated. </p> <p> You can press "Switch to sunny mode" to change then app state and force trigger a re-render. Notice that the internal state of items is preserved. </p> <p> Also, the layout of the parent is reactive. Click "New layout" to change genereate a new layout. Notice again that active items remain active. </p> </div> <div class="buttons-row"> <button class="layout-button" @click=${this.onSunnyButtonClick}> ${buttonText} </button> <button class="layout-button" @click=${this.onNewLayoutClick}> New layout </button> <button class="layout-button" @click=${this.onColummnClick}> + Columns </button> </div> </div> <div class="layout" style=" background-color: ${layoutBackgroundColor}; box-sizing: border-box; position: relative; "> <lit-grid-layout .layout=${this.layout} .dragHandle=${dragHandle} .sortStyle=${sortStyle} .itemRenderer=${this.itemRenderer} .columns=${mediaQueryColumns[this.index]} @layout-changed=${this.onLayoutChanged} @item-changed=${this.onLayoutChanged}> </lit-grid-layout> </div>`; } } customElements.define('my-app', MyApp); </script> </body> </html>
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-draggable-wrapper.ts
TypeScript
import { css, CSSResult, customElement, html, LitElement, property, TemplateResult, } from "lit-element"; import "./lit-draggable"; import type { DraggingEvent, LGLDomEvent } from "./types"; import { fireEvent } from "./util/fire-event"; @customElement("lit-draggable-wrapper") export class LitDraggableWrapper extends LitElement { @property({ type: Array }) public grid?: [number, number]; @property() public handle?: string; private _startTop?: number; private _startLeft?: number; protected render(): TemplateResult { return html` <div class="draggable-wrapper"> <lit-draggable .handle=${this.handle} @dragging=${this._drag} @dragStart=${this._dragStart} @dragEnd=${this._dragEnd} > <slot></slot> </lit-draggable> </div> `; } private _dragStart(): void { const rect = this.getBoundingClientRect(); const parentRect = this.offsetParent!.getBoundingClientRect(); this._startLeft = rect.left - parentRect.left; this._startTop = rect.top - parentRect.top; fireEvent(this, "dragStart"); } private _drag(ev: LGLDomEvent<DraggingEvent>): void { ev.stopPropagation(); if (this._startLeft === undefined || this._startTop === undefined) { return; } const { deltaX, deltaY } = ev.detail; this.style.setProperty( "--drag-x", `${Math.round(this._startLeft! + deltaX)}px` ); this.style.setProperty( "--drag-y", `${Math.round(this._startTop! + deltaY)}px` ); fireEvent(this, "dragging", { deltaX, deltaY }); } private _dragEnd(): void { this._startLeft = undefined; this._startTop = undefined; fireEvent(this, "dragStart"); } static get styles(): CSSResult { return css` .draggable-wrapper { position: absolute; transform: translate(var(--drag-x), var(--drag-y)); touch-action: none; user-select: none; } `; } } declare global { interface HTMLElementTagNameMap { "lit-draggable-wrapper": LitDraggableWrapper; } }
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-draggable.ts
TypeScript
import { customElement, html, LitElement, property, TemplateResult, } from "lit-element"; import { fireEvent } from "./util/fire-event"; import { getMouseTouchLocation } from "./util/get-mouse-touch-location"; import { getTouchIdentifier } from "./util/get-touch-identifier"; import { matchesSelectorAndParentsTo } from "./util/match-selector"; @customElement("lit-draggable") export class LitDraggable extends LitElement { @property({ type: Array }) public grid?: [number, number]; @property({ type: Boolean, reflect: true }) public disabled = false; @property() public handle?: string; private startX?: number; private startY?: number; private _dragging = false; private _touchIdentifier?: number; protected firstUpdated(): void { this.addEventListener("mousedown", this._dragStart.bind(this), { capture: true, passive: false, }); this.addEventListener("touchstart", this._dragStart.bind(this), { capture: true, passive: false, }); document.addEventListener("mousemove", this._drag.bind(this), { capture: true, passive: false, }); document.addEventListener("touchmove", this._drag.bind(this), { capture: true, passive: false, }); document.addEventListener("mouseup", this._dragEnd.bind(this), { capture: true, passive: false, }); document.addEventListener("touchcancel", this._dragEnd.bind(this), { capture: true, passive: false, }); document.addEventListener("touchend", this._dragEnd.bind(this), { capture: true, passive: false, }); } protected render(): TemplateResult { return html`<slot></slot>`; } private _dragStart(ev: MouseEvent | TouchEvent): void { if ( (ev.type.startsWith("mouse") && (ev as MouseEvent).button !== 0) || this.disabled ) { return; } if ( this.handle && !matchesSelectorAndParentsTo(ev, this.handle, this.offsetParent as Node) ) { return; } ev.preventDefault(); ev.stopPropagation(); if (ev.type === "touchstart") { this._touchIdentifier = getTouchIdentifier(ev as TouchEvent); } const pos = getMouseTouchLocation(ev, this._touchIdentifier); if (!pos) { return; } this.startX = pos.x; this.startY = pos.y; this._dragging = true; fireEvent(this, "dragStart", { startX: this.startX, startY: this.startY, }); } private _drag(ev: MouseEvent | TouchEvent): void { if (!this._dragging || this.disabled) { return; } ev.preventDefault(); ev.stopPropagation(); const pos = getMouseTouchLocation(ev, this._touchIdentifier); if (!pos) { return; } let deltaX = pos.x - this.startX!; let deltaY = pos.y - this.startY!; if (this.grid) { deltaX = Math.round(deltaX / this.grid[0]) * this.grid[0]; deltaY = Math.round(deltaY / this.grid[1]) * this.grid[1]; } if (!deltaX && !deltaY) { return; } fireEvent(this, "dragging", { deltaX, deltaY, }); } private _dragEnd(ev: MouseEvent | TouchEvent): void { if (!this._dragging || this.disabled) { return; } ev.preventDefault(); ev.stopPropagation(); this._touchIdentifier = undefined; this._dragging = false; fireEvent(this, "dragEnd"); } } declare global { interface HTMLElementTagNameMap { "lit-draggable": LitDraggable; } }
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-grid-item.ts
TypeScript
import { css, CSSResult, customElement, html, internalProperty, LitElement, property, PropertyValues, query, TemplateResult, } from "lit-element"; import { classMap } from "lit-html/directives/class-map"; import "./lit-draggable"; import "./lit-resizable"; import type { DraggingEvent, LGLDomEvent, ResizingEvent } from "./types"; import { fireEvent } from "./util/fire-event"; @customElement("lit-grid-item") export class LitGridItem extends LitElement { @property({ type: Number }) public width!: number; @property({ type: Number }) public height!: number; @property({ type: Number }) public posX!: number; @property({ type: Number }) public posY!: number; @property({ type: Number }) public rowHeight!: number; @property({ type: Number }) public columns!: number; @property({ type: Number }) public parentWidth!: number; @property({ type: Array }) public margin!: [number, number]; @property({ type: Array }) public containerPadding!: [number, number]; @property({ type: Number }) public minWidth = 1; @property({ type: Number }) public minHeight = 1; @property({ type: Number }) public maxWidth?: number; @property({ type: Number }) public maxHeight?: number; @property({ type: Boolean }) public isDraggable = true; @property({ type: Boolean }) public isResizable = true; @property({ type: Boolean }) private _isDragging = false; @property({ type: Boolean }) private _isResizing = false; @property({ type: Boolean }) private _firstLayoutFinished = false; @property({ attribute: false }) public resizeHandle?: HTMLElement; @property({ attribute: false }) public dragHandle?: string; @property() public key!: string; @query(".grid-item-wrapper") private gridItem!: HTMLElement; @internalProperty() private _itemTopPX?: number; @internalProperty() private _itemLeftPX?: number; @internalProperty() private _itemWidthPX?: number; @internalProperty() private _itemHeightPX?: number; private _startTop?: number; private _startLeft?: number; private _startPosX?: number; private _startPosY?: number; private _minWidthPX?: number; private _maxWidthPX?: number; private _minHeightPX?: number; private _maxHeightPX?: number; private _fullColumnWidth?: number; private _fullRowHeight?: number; private _columnWidth?: number; protected updated(changedProps: PropertyValues): void { // Set up all the calculations that are needed in the drag/resize events // No need to calculate them all the time unless they change if ( changedProps.has("parentWidth") || changedProps.has("margin") || changedProps.has("columns") || changedProps.has("containerPadding") || changedProps.has("minHeight") || changedProps.has("minWidth") || changedProps.has("maxWidth") || changedProps.has("maxHeight") || changedProps.has("rowHeight") || changedProps.has("posX") || (changedProps.has("_isDragging") && !this._isDragging) ) { this._columnWidth = (this.parentWidth - this.margin[0] * (this.columns - 1) - this.containerPadding[0] * 2) / this.columns; this._fullColumnWidth = this._columnWidth + this.margin[0]; this._fullRowHeight = this.rowHeight + this.margin[1]; this._minWidthPX = this._fullColumnWidth! * this.minWidth - this.margin[0]; const maxWidthUnits = this.maxWidth !== undefined ? Math.min(this.maxWidth, this.columns - this.posX) : this.columns - this.posX; this._maxWidthPX = this._fullColumnWidth! * maxWidthUnits - this.margin[0]; this._minHeightPX = this._fullRowHeight! * this.minHeight - this.margin[1]; this._maxHeightPX = this._fullRowHeight! * (this.maxHeight || Infinity) - this.margin[1]; } if (this._isDragging) { return; } this._itemLeftPX = Math.round( this.posX * this._fullColumnWidth! + this.containerPadding[0] ); this._itemTopPX = !this.parentWidth ? 0 : Math.round(this.posY * this._fullRowHeight! + this.containerPadding[1]); if (this._isResizing) { return; } this._itemWidthPX = this.width * this._columnWidth! + Math.max(0, this.width - 1) * this.margin[0]; this._itemHeightPX = this.height * this.rowHeight + Math.max(0, this.height - 1) * this.margin[1]; if (!this._firstLayoutFinished && this.parentWidth > 0) { setTimeout(() => (this._firstLayoutFinished = true), 200); } } protected render(): TemplateResult { let gridItemHTML = html`<slot></slot>`; if (this.isDraggable) { gridItemHTML = html` <lit-draggable .handle=${this.dragHandle} @dragStart=${this._dragStart} @dragging=${this._drag} @dragEnd=${this._dragEnd} > ${gridItemHTML} </lit-draggable> `; } if (this.isResizable) { const resizeHandle = this.resizeHandle?.cloneNode(true) as HTMLElement; gridItemHTML = html` <lit-resizable .handle=${resizeHandle} @resizeStart=${this._resizeStart} @resize=${this._resize} @resizeEnd=${this._resizeEnd} > ${gridItemHTML} </lit-resizable> `; } return html` <div class="grid-item-wrapper ${classMap({ dragging: this._isDragging, resizing: this._isResizing, finished: this._firstLayoutFinished, })}" style="transform: translate(${this._itemLeftPX}px, ${this ._itemTopPX}px); width: ${this._itemWidthPX}px; height: ${this ._itemHeightPX}px" > ${gridItemHTML} </div> `; } private _resizeStart(): void { this.isDraggable = false; this._isResizing = true; this._isDragging = false; fireEvent(this, "resizeStart"); } private _resize(ev: LGLDomEvent<ResizingEvent>): void { if (!this._isResizing) { return; } let { width, height } = ev.detail; // update width and height to be within contraints width = Math.max(this._minWidthPX!, width); width = Math.min(this._maxWidthPX!, width); height = Math.max(this._minHeightPX!, height); height = Math.min(this._maxHeightPX!, height); // Go ahead an update the width and height of the element (this won't affect the layout) this._itemWidthPX = width; this._itemHeightPX = height; // Calculate the new width and height in grid units const newWidth = Math.round( (width + this.margin[0]) / this._fullColumnWidth! ); const newHeight = Math.round( (height + this.margin[1]) / this._fullRowHeight! ); // if the grid units don't change, don't send the update to the layout if (newWidth === this.width && newHeight === this.height) { return; } fireEvent(this, "resize", { newWidth, newHeight }); } private _resizeEnd(): void { this.isDraggable = true; this._isResizing = false; fireEvent(this, "resizeEnd"); } private _dragStart(): void { if (!this.isDraggable) { return; } const rect = this.gridItem.getBoundingClientRect(); const parentRect = this.offsetParent!.getBoundingClientRect(); this._startLeft = rect.left - parentRect.left; this._startTop = rect.top - parentRect.top; this._startPosX = this.posX; this._startPosY = this.posY; this._isDragging = true; fireEvent(this, "dragStart"); } private _drag(ev: LGLDomEvent<DraggingEvent>): void { if ( this._startPosX === undefined || this._startPosY === undefined || this._startLeft === undefined || this._startTop === undefined || !this.isDraggable ) { return; } const { deltaX, deltaY } = ev.detail; // Go ahead an update the position of the item, this won't affect the layout this._itemLeftPX = this._startLeft + deltaX; this._itemTopPX = this._startTop + deltaY; // Get the change in grid units from the change in pixels const deltaCols = Math.round(deltaX / this._fullColumnWidth!); const deltaRows = Math.round(deltaY / this._fullRowHeight!); // If change in grid units from both axis are 0, no need to go forward if (!deltaRows && !deltaCols) { return; } // Add the delta to the orginal, to get the new position let newPosX = this._startPosX + deltaCols; let newPosY = this._startPosY + deltaRows; // Positions have to stay within bounds newPosX = Math.max(0, newPosX); newPosY = Math.max(0, newPosY); newPosX = Math.min(this.columns - this.width, newPosX); fireEvent(this, "dragging", { newPosX, newPosY }); } private _dragEnd(): void { this._isDragging = false; this._startLeft = undefined; this._startTop = undefined; this._startPosX = undefined; this._startPosY = undefined; fireEvent(this, "dragEnd"); } static get styles(): CSSResult { return css` .grid-item-wrapper { position: absolute; transition: var(--grid-item-transition, all 200ms); z-index: 2; opacity: 0; } .grid-item-wrapper.dragging { transition: none; z-index: 3; opacity: var(--grid-item-dragging-opacity, 0.8) !important; } .grid-item-wrapper.resizing { transition-property: transform; z-index: 3; opacity: var(--grid-item-resizing-opacity, 0.8) !important; } .grid-item-wrapper.finished { opacity: 1; } :host([placeholder]) .grid-item-wrapper { background-color: var(--placeholder-background-color, red); opacity: var(--placeholder-background-opacity, 0.2); z-index: 1; } lit-resizable { width: 100%; height: 100%; } `; } } declare global { interface HTMLElementTagNameMap { "lit-grid-item": LitGridItem; } }
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-grid-layout.ts
TypeScript
import deepClone from "deep-clone-simple"; import { css, CSSResult, customElement, html, internalProperty, LitElement, property, PropertyValues, TemplateResult, } from "lit-element"; import { nothing } from "lit-html"; import { repeat } from "lit-html/directives/repeat"; import "./lit-grid-item"; import type { ItemDraggedEvent, ItemRenderer, ItemResizedEvent, Layout, LayoutItem, LGLItemDomEvent, } from "./types"; import { areLayoutsDifferent } from "./util/are-layouts-different"; import { condenseLayout } from "./util/condense-layout"; import { debounce } from "./util/debounce"; import { findLayoutBottom } from "./util/find-layout-bottom"; import { fireEvent } from "./util/fire-event"; import { fixLayoutBounds } from "./util/fix-layout-bounds"; import { getMasonryLayout } from "./util/get-masonry-layout"; import { installResizeObserver } from "./util/install-resize-observer"; import { moveItem } from "./util/move-item"; // TODO: Instead of resize handle being a different draggable element. Why not just add a second handle like the Drag and use that @customElement("lit-grid-layout") export class LitGridLayout extends LitElement { @property({ type: Array }) public layout?: Layout; @property() public sortStyle: "default" | "masonry" = "masonry"; @property({ type: Array }) public margin: [number, number] = [10, 10]; @property({ type: Array }) public containerPadding: [number, number] = [ 20, 20, ]; @property({ type: Number }) public rowHeight = 30; @property({ type: Number }) public columns = 12; @property({ type: Boolean }) public dragDisabled = false; @property({ type: Boolean }) public resizeDisabled = false; @property({ attribute: false }) public resizeHandle?: HTMLElement; @property({ attribute: false }) public dragHandle?: string; @property({ type: Boolean, attribute: true, reflect: true }) public resizing?: boolean = false; @property({ type: Boolean, attribute: true, reflect: true }) public dragging?: boolean = false; @property() public itemRenderer?: ItemRenderer; @internalProperty() private _width = 0; @internalProperty() private _layout: Layout = []; @internalProperty() private _placeholder?: LayoutItem; private _oldItemLayout?: LayoutItem; private _oldItemIndex?: number; private _resizeObserver?: ResizeObserver; private _prevPosX?: number; private _prevPosY?: number; get _layoutHeight(): number { const btm = findLayoutBottom(this._layout); return ( btm * this.rowHeight + (btm - 1) * this.margin[1] + this.containerPadding[1] * 2 ); } public disconnectedCallback(): void { if (this._resizeObserver) { this._resizeObserver.disconnect(); } } public connectedCallback(): void { super.connectedCallback(); this.updateComplete.then(() => this._attachObserver()); } protected updated(changedProps: PropertyValues): void { super.updated(changedProps); if (changedProps.has("layout")) { this._setupLayout(); } else if (changedProps.has("columns")) { this._updateLayout(deepClone(this.layout)); } this.style.height = `${this._layoutHeight}px`; } protected render(): TemplateResult { if (!this._layout?.length || !this.itemRenderer) { return html``; } return html` ${repeat( this._layout, (item: LayoutItem) => item.key, (item) => { if ( !item || !this._layout.some((layoutItem) => layoutItem.key === item.key) ) { return nothing; } return html` <lit-grid-item .width=${item.width} .height=${item.height} .posY=${item.posY} .posX=${item.posX} .minWidth=${item.minWidth || 1} .minHeight=${item.minHeight || 1} .maxWidth=${item.maxHeight} .maxHeight=${item.maxHeight} .key=${item.key} .parentWidth=${this._width!} .columns=${this.columns} .rowHeight=${this.rowHeight} .margin=${this.margin} .containerPadding=${this.containerPadding} .isDraggable=${!this.dragDisabled} .isResizable=${!this.resizeDisabled} .resizeHandle=${this.resizeHandle} .dragHandle=${this.dragHandle} @resizeStart=${this._itemResizeStart} @resize=${this._itemResize} @resizeEnd=${this._itemResizeEnd} @dragStart=${this._itemDragStart} @dragging=${this._itemDrag} @dragEnd=${this._itemDragEnd} > ${this.itemRenderer!(item.key)} </lit-grid-item> `; } )} ${this._renderPlaceHolder()} `; } private _setupLayout(): void { if (!this.layout) { throw new Error("Missing layout"); } // Dirty check to avoid endless cycles if (areLayoutsDifferent(this.layout, this._layout)) { this._updateLayout(this.layout, true); fireEvent(this, "layout-changed", { layout: this._layout }); } } private _updateLayout( layout: Layout, fix = false, style = this.sortStyle ): void { if (style === "masonry") { this._layout = getMasonryLayout(layout, this.columns); } else { const newLayout = fix ? fixLayoutBounds(layout, this.columns) : layout; this._layout = condenseLayout(newLayout); } } private _itemResizeStart(ev: LGLItemDomEvent<Event>): void { this._oldItemIndex = this._layout.findIndex( (item) => item.key === ev.currentTarget.key ); this._placeholder = this._layout[this._oldItemIndex]; this._oldItemLayout = this._layout[this._oldItemIndex]; } private _itemResize(ev: LGLItemDomEvent<ItemResizedEvent>): void { if (!this._oldItemLayout || this._oldItemIndex === undefined) { return; } const { newWidth, newHeight } = ev.detail; const newItemLayout = { ...this._oldItemLayout, width: newWidth, height: newHeight, }; this._layout[this._oldItemIndex] = newItemLayout; this._placeholder = newItemLayout; this._updateLayout(this._layout, false, "default"); } private _itemResizeEnd(): void { const newItemLayout = this._layout.find( (item) => item.key === this._oldItemLayout?.key ); if (!this.layout || this._oldItemLayout === newItemLayout) { return; } fireEvent(this, "item-changed", { item: this._placeholder, layout: this._layout, }); this._placeholder = undefined; this._oldItemLayout = undefined; this._oldItemIndex = undefined; } private _itemDragStart(ev: LGLItemDomEvent<Event>): void { const itemIndex = this._layout.findIndex( (item) => item.key === ev.currentTarget.key ); this._placeholder = this._layout[itemIndex]; this._oldItemLayout = this._layout.find( (item) => item.key === ev.currentTarget.key ); } private _itemDrag(ev: LGLItemDomEvent<ItemDraggedEvent>): void { if (!this._oldItemLayout) { return; } ev.stopPropagation(); ev.preventDefault(); const { newPosX, newPosY } = ev.detail; if (this._prevPosX === newPosX && this._prevPosY === newPosY) { return; } this._prevPosX = newPosX; this._prevPosY = newPosY; const newLayout = moveItem( [...this._layout], { ...this._oldItemLayout }, newPosX, newPosY, this.columns, true ); this._updateLayout(newLayout, false, "default"); this._placeholder = this._layout.find( (item) => item.key === this._oldItemLayout!.key ); } private _itemDragEnd(): void { const newItemLayout = this._layout.find( (item) => item.key === this._oldItemLayout!.key ); if (!this.layout || this._oldItemLayout === newItemLayout) { return; } fireEvent(this, "item-changed", { item: this._placeholder, layout: this._layout, }); this._placeholder = undefined; this._oldItemLayout = undefined; this._oldItemIndex = undefined; } private _renderPlaceHolder(): TemplateResult { if (!this._placeholder) { return html``; } return html` <lit-grid-item .width=${this._placeholder.width} .height=${this._placeholder.height} .posY=${this._placeholder.posY} .posX=${this._placeholder.posX} .key=${this._placeholder.key} .parentWidth=${this.clientWidth} .columns=${this.columns} .rowHeight=${this.rowHeight} .margin=${this.margin} .containerPadding=${this.containerPadding} .isDraggable=${false} .isResizable=${false} placeholder > </lit-grid-item> `; } private async _attachObserver(): Promise<void> { if (!this._resizeObserver) { await installResizeObserver(); this._resizeObserver = new ResizeObserver( debounce(() => this._measureLayoutWidth(), 250, false) ); } this._resizeObserver.observe(this); } private _measureLayoutWidth(): void { if (this.offsetParent) { this._width = this.offsetParent.clientWidth; } } static get styles(): CSSResult { return css` :host { display: block; position: relative; } :host([dragging]), :host([resizing]), :host([dragging]) lit-grid-item, :host([resizing]) lit-grid-item { user-select: none; touch-action: none; } `; } } declare global { interface HTMLElementTagNameMap { "lit-grid-layout": LitGridLayout; } }
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-resizable-wrapper.ts
TypeScript
import { customElement, html, LitElement, TemplateResult, CSSResult, css, } from "lit-element"; import type { LGLDomEvent, ResizingEvent } from "./types"; import { fireEvent } from "./util/fire-event"; import "./lit-resizable"; @customElement("lit-resizable-wrapper") export class LitResizableWrapper extends LitElement { protected render(): TemplateResult { return html` <lit-resizable @resize=${this._resize} @resizeStart=${this._resizeStart} @resizeEnd=${this._resizeEnd} > <slot></slot> </lit-resizable> `; } private _resizeStart(ev: Event): void { ev.stopPropagation(); ev.preventDefault(); fireEvent(this, "resizeStart"); } private _resize(ev: LGLDomEvent<ResizingEvent>): void { ev.stopPropagation(); ev.preventDefault(); const { width, height } = ev.detail; this.style.setProperty("--item-width", `${width}px`); this.style.setProperty("--item-height", `${height}px`); fireEvent(this, "resize", { width, height }); } private _resizeEnd(ev: Event): void { ev.stopPropagation(); ev.preventDefault(); fireEvent(this, "resizeStart"); } static get styles(): CSSResult { return css` :host { position: absolute; width: var(--item-width); height: var(--item-height); } lit-resizable { width: 100%; height: 100%; } `; } } declare global { interface HTMLElementTagNameMap { "lit-resizable-wrapper": LitResizableWrapper; } }
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-resizable.ts
TypeScript
import { css, CSSResult, customElement, html, LitElement, property, svg, TemplateResult, } from "lit-element"; import "./lit-draggable"; import type { DraggingEvent, LGLDomEvent } from "./types"; import { fireEvent } from "./util/fire-event"; @customElement("lit-resizable") export class LitResizable extends LitElement { @property({ attribute: false }) public handle?: HTMLElement; @property({ type: Boolean }) public disabled = false; private startWidth?: number; private startHeight?: number; protected render(): TemplateResult { return html` <slot></slot> ${this.disabled ? "" : html` <lit-draggable @dragging=${this._resize} @dragStart=${this._resizeStart} @dragEnd=${this._resizeEnd} > ${!this.handle ? svg` <svg xmlns="http://www.w3.org/2000/svg" class="icon-tabler-arrows-diagonal-2" viewBox="0 0 24 24" > <path stroke="none" d="M0 0h24v24H0z" /> <polyline points="16 20 20 20 20 16" /> <line x1="14" y1="14" x2="20" y2="20" /> <polyline points="8 4 4 4 4 8" /> <line x1="4" y1="4" x2="10" y2="10" /> </svg> ` : html`${this.handle}`} </lit-draggable> `} `; } private _resizeStart(ev: Event): void { ev.preventDefault(); ev.stopPropagation(); this.startWidth = this.clientWidth; this.startHeight = this.clientHeight; fireEvent(this, "resizeStart"); } private _resize(ev: LGLDomEvent<DraggingEvent>): void { ev.preventDefault(); ev.stopPropagation(); if (this.startWidth === undefined || this.startHeight === undefined) { return; } const { deltaX, deltaY } = ev.detail; if (deltaY === 0 && deltaX === 0) { return; } const width = this.startWidth + deltaX; const height = this.startHeight + deltaY; fireEvent(this, "resize", { width, height, deltaX, deltaY, }); } private _resizeEnd(ev: Event): void { ev.preventDefault(); ev.stopPropagation(); this.startWidth = undefined; this.startHeight = undefined; fireEvent(this, "resizeEnd"); } static get styles(): CSSResult { return css` :host { position: relative; display: block; } lit-draggable { position: absolute; left: var(--resize-handle-position-left, unset); top: var(--resize-handle-postion-top, unset); bottom: var(--resize-handle-position-bottom, 0); right: var(--resize-handle-postion-right, 0); width: var(--resize-handle-size, 18px); height: var(--resize-handle-size, 18px); z-index: var(--resize-handle-z-index, 5); opacity: var(--resize-handle-opacity, 1); user-select: none; } .icon-tabler-arrows-diagonal-2 { width: 100%; height: 100%; stroke-width: 1.5; stroke: #607d8b; fill: none; stroke-linecap: round; stroke-linejoin: round; cursor: se-resize; } `; } } declare global { interface HTMLElementTagNameMap { "lit-resizable": LitResizable; } }
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/types.ts
TypeScript
import type { TemplateResult } from "lit-html"; export interface LayoutItem { width: number; height: number; posX: number; posY: number; key: string; hasMoved?: boolean; minWidth?: number; maxWidth?: number; minHeight?: number; maxHeight?: number; } export type Layout = Array<LayoutItem>; export interface LayoutObject { [key: string]: LayoutItem; } export interface LayoutItemElement extends HTMLElement { key: string; grid: { width: number; height: number; posX: number; posY: number; }; } export interface LGLDomEvent<T> extends Event { detail: T; } export interface LGLItemDomEvent<T> extends Event { detail: T; currentTarget: LayoutItemElement; } export interface DraggingEvent { deltaX: number; deltaY: number; } export interface ResizingEvent { width: number; height: number; } export interface ItemDraggedEvent { newPosX: number; newPosY: number; } export interface ItemResizedEvent { newWidth: number; newHeight: number; } export interface MouseLocation { x: number; y: number; } export interface MouseTouchLocation { x: number; y: number; } export type EventHandler<T> = (e: T) => void | false; export type ItemRenderer = (itemKey: string) => TemplateResult;
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/are-layouts-different.ts
TypeScript
import type { Layout } from "../types"; export const areLayoutsDifferent = (a: Layout, b: Layout): boolean => { if (a === b) { return false; } return ( a.length !== b.length || a.some((aItem, itemIndex) => { const bItem = b[itemIndex]; const aItemKeys = Object.keys(aItem); return ( aItemKeys.length !== Object.keys(bItem).length || aItemKeys.some((key) => aItem[key] !== bItem[key]) ); }) ); };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/condense-layout.ts
TypeScript
// Fill in any gaps in the LayoutItem array import type { Layout, LayoutItem } from "../types"; import { getItemItersect } from "./get-item-intersect"; import { resolveIntersection } from "./resolve-intersection"; import { sortLayout } from "./sort-layout"; // Return LayoutItem Array export const condenseLayout = (layout: Layout): Layout => { const condensedLayout: Layout = []; const returnLayout: Layout = []; const sortedLayout: Layout = sortLayout(layout); for (const item of sortedLayout) { // Move up while no intersecting another element while (item.posY > 0 && !getItemItersect(condensedLayout, item)) { item.posY--; } // Move down Item down, if it intersects with another item, move it down as well let intersectItem: LayoutItem | undefined; while ((intersectItem = getItemItersect(condensedLayout, item))) { resolveIntersection( sortedLayout, item, intersectItem.posY + intersectItem.height ); } delete item.hasMoved; condensedLayout.push(item); returnLayout[layout.indexOf(item)] = item; } return returnLayout; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/debounce.ts
TypeScript
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/ban-ts-comment */ // From: https://davidwalsh.name/javascript-debounce-function // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. // eslint-disable-next-line @typescript-eslint/ban-types export const debounce = <T extends Function>( func: T, wait, immediate = false ): T => { let timeout; // @ts-ignore return function (...args) { // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-this-alias const context = this; const later = () => { timeout = null; if (!immediate) { func.apply(context, args); } }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/find-layout-bottom.ts
TypeScript
import type { LayoutItem } from "../types"; // Return the bottom y value export const findLayoutBottom = (layout: LayoutItem[]): number => { let layoutYMax = 0; for (const item of layout) { const itemBottom = item.posY + item.height; layoutYMax = itemBottom > layoutYMax ? itemBottom : layoutYMax; } return layoutYMax; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/fire-event.ts
TypeScript
export const fireEvent = ( target: EventTarget, event: string, detail: Record<string, any> = {} ): void => { target.dispatchEvent(new CustomEvent(event, { detail })); };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/fix-layout-bounds.ts
TypeScript
import type { LayoutItem } from "../types"; // Make sure all layout items are within the bounds of the cols provided export const fixLayoutBounds = ( layout: LayoutItem[], cols: number ): LayoutItem[] => { for (const item of layout) { // Width is greater than amount of columns // set the width to be number of columns if (item.width > cols) { item.width = cols; } // Out of bounds right // set the x to be against the right side if (item.posX + item.width > cols) { item.posX = cols - item.width; } // Out of bounds left // set x to be against the left side if (item.posX < 0) { item.posX = 0; } } return layout; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/get-all-intersects.ts
TypeScript
import type { Layout, LayoutItem } from "../types"; import { intersects } from "./intersects"; export const getAllIntersects = ( layout: Layout, layoutItem: LayoutItem ): Array<LayoutItem> => { return layout.filter((l) => intersects(l, layoutItem)); };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/get-item-intersect.ts
TypeScript
import type { LayoutItem } from "../types"; import { intersects } from "./intersects"; export const getItemItersect = ( layout: LayoutItem[], layoutItem: LayoutItem ): LayoutItem | undefined => { for (const item of layout) { if (intersects(item, layoutItem)) { return item; } } return undefined; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/get-masonry-layout.ts
TypeScript
import type { Layout, LayoutItem } from "../types"; import { sortLayout } from "./sort-layout"; export const getMasonryLayout = (layout: Layout, columns: number): Layout => { const masonryLayout: Layout = []; const sortedLayout: Layout = sortLayout(layout); const columnHeights: number[] = new Array(columns).fill(0); for (const item of sortedLayout) { if (item.width > columns) { item.width = columns; } const itemPostion = getMinItemColumn(item, columnHeights, columns); const newItem = { ...item, ...itemPostion }; masonryLayout.push(newItem); // Update Columns Heights from new item position for (let i = itemPostion.posX; i < itemPostion.posX + item.width; i++) { columnHeights[i] += item.height; } } return masonryLayout; }; // Finds the shortest column the item can fit into const getMinItemColumn = ( item: LayoutItem, columnHeights: number[], columns: number ): { posX: number; posY: number } => { // If the item is just 1 column, just find the shortest column and put it there if (item.width === 1) { const minPosY = Math.min(...columnHeights); return { posX: columnHeights.indexOf(minPosY), posY: minPosY }; } const columnHeightGroup: number[] = []; // How many spans of columns can the item go const columnSpans = columns + 1 - item.width; // For each of the spans, find the max Y for (let i = 0; i < columnSpans; i++) { const groupColumnHeights = columnHeights.slice(i, i + item.width); columnHeightGroup[i] = Math.max(...groupColumnHeights); } // Find the shortest of the spans const minPosY = Math.min(...columnHeightGroup); return { posX: columnHeightGroup.indexOf(minPosY), posY: minPosY }; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/get-mouse-touch-location.ts
TypeScript
import type { MouseTouchLocation } from "../types"; export const getMouseTouchLocation = ( ev: MouseEvent | TouchEvent, touchIdentifier: number | undefined ): MouseTouchLocation | undefined => { if (ev.type.startsWith("touch")) { if (touchIdentifier === undefined) { return; } const touchEvent = ev as TouchEvent; const touchObj = getTouch(touchEvent, touchIdentifier); return { x: touchObj.x, y: touchObj.y, }; } return { x: (ev as MouseEvent).clientX, y: (ev as MouseEvent).clientY, }; }; const getTouch = (e: TouchEvent, identifier: number): MouseTouchLocation => { const touchObj = (e.targetTouches && Array.prototype.find.call( e.targetTouches, (t) => identifier === t.identifier )) || (e.changedTouches && Array.prototype.find.call( e.changedTouches, (t) => identifier === t.identifier )); return { x: touchObj.clientX, y: touchObj.clientY, }; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/get-touch-identifier.ts
TypeScript
export const getTouchIdentifier = (e: TouchEvent): number => { if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier; if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier; return 0; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/install-resize-observer.ts
TypeScript
export const installResizeObserver = async (): Promise<void> => { if (typeof ResizeObserver !== "function") { window.ResizeObserver = (await import("resize-observer-polyfill")).default; } };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/intersects.ts
TypeScript
import type { LayoutItem } from "../types"; export const intersects = (item1: LayoutItem, item2: LayoutItem): boolean => { // same element if (item1.key === item2.key) { return false; } // item1 is left of item2 if (item1.posX + item1.width <= item2.posX) { return false; } // item1 is right of item2 if (item1.posX >= item2.posX + item2.width) { return false; } // item1 is above item2 if (item1.posY + item1.height <= item2.posY) { return false; } // item1 is below item2 if (item1.posY >= item2.posY + item2.height) { return false; } return true; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/match-selector.ts
TypeScript
// Credit to react-draggable [https://github.com/STRML/react-draggable] let matchesSelectorFunc: string | undefined = ""; const matchesSelector = (el: Node, selector: string): boolean => { if (!matchesSelectorFunc) { matchesSelectorFunc = [ "matches", "webkitMatchesSelector", "mozMatchesSelector", "msMatchesSelector", "oMatchesSelector", ].find((method) => isFunction(el[method])); } if (!matchesSelectorFunc || !isFunction(el[matchesSelectorFunc])) { return false; } return el[matchesSelectorFunc](selector); }; export const matchesSelectorAndParentsTo = ( ev: MouseEvent | TouchEvent, selector: string, baseNode: Node ): boolean => { const path = ev.composedPath().reverse(); while (path.length) { const node: Node | null = path.pop() as Node; if (matchesSelector(node, selector)) { return true; } if (node === baseNode) { return false; } } return false; }; const isFunction = (func: any): boolean => { return ( typeof func === "function" || Object.prototype.toString.call(func) === "[object Function]" ); };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/move-item-away-from-intersect.ts
TypeScript
import type { Layout, LayoutItem } from "../types"; import { moveItem } from "./move-item"; import { getItemItersect } from "./get-item-intersect"; export const moveItemAwayFromIntersect = ( layout: Layout, intersectItem: LayoutItem, itemToMove: LayoutItem, cols: number, isUserMove: boolean ): Layout => { if (isUserMove) { isUserMove = false; const tempItem: LayoutItem = { posX: itemToMove.posX, posY: Math.max(itemToMove.height - intersectItem.posY, 0), width: itemToMove.width, height: itemToMove.height, key: "-1", }; if (!getItemItersect(layout, tempItem)) { return moveItem( layout, itemToMove, undefined, tempItem.posY, cols, isUserMove ); } } return moveItem( layout, itemToMove, undefined, itemToMove.posY + 1, cols, isUserMove ); };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/move-item.ts
TypeScript
import type { Layout, LayoutItem } from "../types"; import { sortLayout } from "./sort-layout"; import { getAllIntersects } from "./get-all-intersects"; import { moveItemAwayFromIntersect } from "./move-item-away-from-intersect"; export const moveItem = ( layout: Layout, item: LayoutItem, newPosX: number | undefined, newPosY: number | undefined, columns: number, isUserMove: boolean ): Layout => { if (item.posY === newPosY && item.posX === newPosX) { return layout; } const oldPosY = item.posY; if (newPosX !== undefined) { item.posX = newPosX; } if (newPosY !== undefined) { item.posY = newPosY; } item.hasMoved = true; let sorted = sortLayout(layout); const movingUp = newPosY !== undefined && oldPosY >= newPosY; if (movingUp) { sorted = sorted.reverse(); } const allIntersects = getAllIntersects(sorted, item); const itemIndex = layout.findIndex((i) => i.key === item.key); layout[itemIndex] = item; // Move each item that intersects away from this element. for (let i = 0, len = allIntersects.length; i < len; i++) { const intersectItem = allIntersects[i]; if (intersectItem.hasMoved) { continue; } layout = moveItemAwayFromIntersect( [...layout], item, intersectItem, columns, isUserMove ); } return layout; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/resolve-intersection.ts
TypeScript
import type { LayoutItem } from "../types"; import { intersects } from "./intersects"; export const resolveIntersection = ( layout: LayoutItem[], item: LayoutItem, newYPos: number ): void => { item.posY += 1; const itemIndex = layout .map((layoutItem: LayoutItem) => { return layoutItem.key; }) .indexOf(item.key); for (let i = itemIndex + 1; i < layout.length; i++) { const otherItem = layout[i]; if (otherItem.posY > item.posY + item.height) { break; } if (intersects(item, otherItem)) { resolveIntersection(layout, otherItem, newYPos + item.height); } } item.posY = newYPos; };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
src/util/sort-layout.ts
TypeScript
import type { Layout } from "../types"; export const sortLayout = (layout: Layout): Layout => { return layout.slice(0).sort(function (a, b) { if (a.posY > b.posY || (a.posY === b.posY && a.posX > b.posX)) { return 1; } else if (a.posY === b.posY && a.posX === b.posX) { return 0; } return -1; }); };
zsarnett/Lit-Grid-Layout
31
Grid Layout using Lit Element
TypeScript
zsarnett
Zack Barett
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="dist/lit-resizable-wrapper.js" type="module"></script> <title>Lit Resizable</title> </head> <body> <div style=" width: 100%; height: 100vh; background-color: #eee; position: relative; " > <lit-resizable-wrapper style="--item-width: 150px; --item-height: 100px;"> <div style=" width: 100%; height: 100%; background-color: #ccc; border: 1px solid black; text-align: center; font-size: 22px; line-height: var(--item-height); margin: auto; " > Resize Me! </div> </lit-resizable-wrapper> </div> </body> </html>
zsarnett/Lit-Resizable
0
Resizable Lit Element
TypeScript
zsarnett
Zack Barett
rollup.config.js
JavaScript
import { nodeResolve } from "@rollup/plugin-node-resolve"; import typescript from "@rollup/plugin-typescript"; import { terser } from "rollup-plugin-terser"; import filesize from "rollup-plugin-filesize"; export default [ { input: "src/lit-resizable.ts", output: { file: "dist/lit-resizable.js", format: "esm", sourcemap: "inline", }, plugins: [ nodeResolve({ extensions: [".js", ".ts"], }), typescript(), terser({ warnings: true, ecma: 2017, compress: { unsafe: true, }, output: { comments: false, }, }), filesize({ showBrotliSize: true, }), ], }, { input: "src/lit-resizable-wrapper.ts", output: { file: "dist/lit-resizable-wrapper.js", format: "esm", }, plugins: [ nodeResolve({ extensions: [".js", ".ts"], }), typescript(), terser({ warnings: true, ecma: 2017, compress: { unsafe: true, }, output: { comments: false, }, }), filesize({ showBrotliSize: true, }), ], }, ];
zsarnett/Lit-Resizable
0
Resizable Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-resizable-wrapper.ts
TypeScript
import { customElement, html, LitElement, TemplateResult, CSSResult, css, } from "lit-element"; import type { LGLDomEvent, ResizingEvent } from "./types"; import { fireEvent } from "./util/fire-event"; import "./lit-resizable"; @customElement("lit-resizable-wrapper") export class LitResizableWrapper extends LitElement { protected render(): TemplateResult { return html` <lit-resizable @resize=${this._resize} @resizeStart=${this._resizeStart} @resizeEnd=${this._resizeEnd} > <slot></slot> </lit-resizable> `; } private _resizeStart(ev: Event): void { ev.stopPropagation(); ev.preventDefault(); fireEvent(this, "resizeStart"); } private _resize(ev: LGLDomEvent<ResizingEvent>): void { ev.stopPropagation(); ev.preventDefault(); const { width, height } = ev.detail; this.style.setProperty("--item-width", `${width}px`); this.style.setProperty("--item-height", `${height}px`); fireEvent(this, "resize", { width, height }); } private _resizeEnd(ev: Event): void { ev.stopPropagation(); ev.preventDefault(); fireEvent(this, "resizeStart"); } static get styles(): CSSResult { return css` :host { position: absolute; width: var(--item-width); height: var(--item-height); } lit-resizable { width: 100%; height: 100%; } `; } } declare global { interface HTMLElementTagNameMap { "lit-resizable-wrapper": LitResizableWrapper; } }
zsarnett/Lit-Resizable
0
Resizable Lit Element
TypeScript
zsarnett
Zack Barett
src/lit-resizable.ts
TypeScript
import { customElement, html, LitElement, TemplateResult, CSSResult, css, property, svg, } from "lit-element"; import "lit-draggable"; import type { LGLDomEvent, DraggingEvent } from "./types"; import { fireEvent } from "./util/fire-event"; @customElement("lit-resizable") export class LitResizable extends LitElement { @property({ attribute: false }) public handle?: HTMLElement; @property({ type: Boolean }) public disabled = false; private startWidth?: number; private startHeight?: number; protected render(): TemplateResult { return html` <slot></slot> ${this.disabled ? "" : html` <lit-draggable @dragging=${this._resize} @dragStart=${this._resizeStart} @dragEnd=${this._resizeEnd} > ${!this.handle ? svg` <svg xmlns="http://www.w3.org/2000/svg" class="icon-tabler-arrows-diagonal-2" viewBox="0 0 24 24" > <path stroke="none" d="M0 0h24v24H0z" /> <polyline points="16 20 20 20 20 16" /> <line x1="14" y1="14" x2="20" y2="20" /> <polyline points="8 4 4 4 4 8" /> <line x1="4" y1="4" x2="10" y2="10" /> </svg> ` : html`${this.handle}`} </lit-draggable> `} `; } private _resizeStart(ev: Event): void { ev.preventDefault(); ev.stopPropagation(); this.startWidth = this.clientWidth; this.startHeight = this.clientHeight; fireEvent(this, "resizeStart"); } private _resize(ev: LGLDomEvent<DraggingEvent>): void { ev.preventDefault(); ev.stopPropagation(); if (this.startWidth === undefined || this.startHeight === undefined) { return; } const { deltaX, deltaY } = ev.detail; if (deltaY === 0 && deltaX === 0) { return; } const width = this.startWidth + deltaX; const height = this.startHeight + deltaY; fireEvent(this, "resize", { width, height, deltaX, deltaY, }); } private _resizeEnd(ev: Event): void { ev.preventDefault(); ev.stopPropagation(); this.startWidth = undefined; this.startHeight = undefined; fireEvent(this, "resizeEnd"); } static get styles(): CSSResult { return css` :host { position: relative; display: block; } lit-draggable { position: absolute; left: var(--resize-handle-position-left, unset); top: var(--resize-handle-postion-top, unset); bottom: var(--resize-handle-position-bottom, 0); right: var(--resize-handle-postion-right, 0); width: var(--resize-handle-width, 18px); height: var(--resize-handle-height, 18px); user-select: none; } .icon-tabler-arrows-diagonal-2 { width: 100%; height: 100%; stroke-width: 1.5; stroke: #607d8b; fill: none; stroke-linecap: round; stroke-linejoin: round; cursor: se-resize; } `; } } declare global { interface HTMLElementTagNameMap { "lit-resizable": LitResizable; } }
zsarnett/Lit-Resizable
0
Resizable Lit Element
TypeScript
zsarnett
Zack Barett
src/types.ts
TypeScript
export interface LGLDomEvent<T> extends Event { detail: T; } export interface DraggingEvent { deltaX: number; deltaY: number; } export interface ResizingEvent { width: number; height: number; }
zsarnett/Lit-Resizable
0
Resizable Lit Element
TypeScript
zsarnett
Zack Barett
src/util/fire-event.ts
TypeScript
export const fireEvent = ( target: EventTarget, event: string, detail: Record<string, any> = {} ): void => { target.dispatchEvent(new CustomEvent(event, { detail })); };
zsarnett/Lit-Resizable
0
Resizable Lit Element
TypeScript
zsarnett
Zack Barett
README.sh
Shell
#!/bin/sh cat << EOF # Awfice - the world smallest office suite Awfice is a collection of tiny office suite apps: * a word processor, a spreadsheet, a drawing app and a presentation maker * each less than 1KB of plain JavaScript * each is literally just one line of code * packaged as data URLs, so you can use them right away, without downloading or installing * you can also use them offline * but they can't store their state, so whatever you type there would be lost on page refresh * which can be also sold as a "good for your privacy" feature * this project is only a half-joke, I actually use a few Awfice apps as quick scratchpads. * the only way to save your job is to save a HTML or send it to the printer/print to PDF. ## Text editor - $(wc -c < edit.html | tr -d ' ') bytes! A simple rich text editor. Type whatever you want, it won't be saved anywhere, but it might be convenient for quick throwaway notes. You should be able to use Ctrl+B and Ctrl+I to mark text selection as bold or italic. Undo/redo should work as well. You can also copy/paste text and images from other sources. Copy and add to bookmarks or open in the URL bar: \`\`\`html data:text/html,$(cat edit.html) \`\`\` [Try it!](https://htmlpreview.github.io/?https://github.com/zserge/awfice/blob/main/edit.html) ## Spreadsheet - $(wc -c < calc.html | tr -d ' ') bytes! A very basic spreadsheet with math formulas. It has 100 rows and 26 columns (A..Z). If the value in the cell starts with an "=" = it is evaluated as a formula. You may refer to other cell values, i.e. "=(A10+A11)/A12". Under the hood it uses eval(), so be careful. Copy and add to bookmarks or open in the URL bar: \`\`\`html data:text/html,$(cat calc.html) \`\`\` [Try it!](https://htmlpreview.github.io/?https://github.com/zserge/awfice/blob/main/calc.html) ## Drawing app - $(wc -c < draw.html | tr -d ' ') bytes! Nothing simpler than drawing on a blank canvas with mouse. Works with touch screens as well. To save your results... well, do a screenshot maybe... Copy and add to bookmarks or open in the URL bar: \`\`\`html data:text/html,$(cat draw.html) \`\`\` [Try it!](https://htmlpreview.github.io/?https://github.com/zserge/awfice/blob/main/draw.html) ## Presentation maker - $(wc -c < beam.html | tr -d ' ') bytes! Just a variant of a rich text editor with some hotkeys. There are 50 blank slides for you (I hope you don't need to bore your audience with more slides). Each slide is a rich text editor, but there are some hotkeys to make styling better: * Ctrl+Alt+1: Header * Ctrl+Alt+2: Normal style * Ctrl+Alt+3: Align left * Ctrl+Alt+4: Align center * Ctrl+Alt+5: Align right * Ctrl+Alt+6: Outdent * Ctrl+Alt+7: Indent * Ctrl+Alt+8: Make a list Copy and add to bookmarks or open in the URL bar: \`\`\`html data:text/html,$(cat beam.html) \`\`\` [Try it!](https://htmlpreview.github.io/?https://github.com/zserge/awfice/blob/main/beam.html) ## Code editor - $(wc -c < code.html) bytes! A simple code editor. You can type in HTML, CSS & Javascript. Copy and add to bookmarks or open in the URL bar: \`\`\`html data:text/html,$(cat code.html) \`\`\` [Try it!](https://htmlpreview.github.io/?https://github.com/zserge/awfice/blob/main/code.html) ## Calculator - $(wc -c < calculator.html) bytes! A simple calculator which supports the basic operational symbol to calculate. Copy and add to bookmarks or open in the URL bar: \`\`\`html data:text/html,$(cat calculator.html) \`\`\` [Try it!](https://htmlpreview.github.io/?https://github.com/zserge/awfice/blob/main/calculator.html) ## Contributions The code is distributed under MIT license. PRs are always welcome, especially if they fix something or make the code smaller, or add features that are valuable, but do not require a lot of code. To modify something - edit HTML files directly. There is README.sh script that re-generates the README and embeds apps code into it. EOF
zserge/awfice
3,645
The world smallest office suite
HTML
zserge
Serge Zaitsev
beam.html
HTML
<body><script>d=document;for(i=0;i<50;i++)d.body.innerHTML+='<div style="position:relative;width:90%;padding-top:60%;margin:5%;border:1px solid silver;page-break-after:always"><div contenteditable style=outline:none;position:absolute;right:10%;bottom:10%;left:10%;top:10%;font-size:5vmin>';d.querySelectorAll("div>div").forEach(e=>e.onkeydown=e=>{n=e.ctrlKey&&e.altKey&&e.keyCode-49,f="formatBlock",j="justify",x=[f,f,j+"Left",j+"Center",j+"Right","outdent","indent","insertUnorderedList"][n],y=["<h1>","<div>"][n],x&&d.execCommand(x,!1,y)})</script><style>@page{size:6in 8in landscape}@media print{*{border:0 !important}}
zserge/awfice
3,645
The world smallest office suite
HTML
zserge
Serge Zaitsev
calc.html
HTML
<table id=t><script>z=Object.defineProperty,p=parseFloat;for(I=[],D={},C={},q=_=>I.forEach(e=>{try{e.value=D[e.id]}catch(e){}}),i=0;i<101;i++)for(r=t.insertRow(-1),j=0;j<27;j++)c=String.fromCharCode(65+j-1),d=r.insertCell(-1),d.innerHTML=i?j?"":i:c,i*j&&I.push(d.appendChild((f=>(f.id=c+i,f.onfocus=e=>f.value=C[f.id]||"",f.onblur=e=>{C[f.id]=f.value,q()},get=_=>{v=C[f.id]||"";if("="!=v.charAt(0))return isNaN(p(v))?v:p(v);with(D)return eval(v.slice(1))},a={get},z(D,f.id,a),z(D,f.id.toLowerCase(),a),f))(document.createElement`input`)))</script><style>#t{border-collapse:collapse}td{border:1px solid gray;text-align:right}input{border:none;width:4rem;text-align:center}</style>
zserge/awfice
3,645
The world smallest office suite
HTML
zserge
Serge Zaitsev
calculator.html
HTML
<table style="text-align: center;width:80vw;margin: 0 auto;"><tbody><tr><td colspan="4"><textarea></textarea></td></tr></tbody><script>let d=document;let tbl=d.querySelector('tbody');let z=d.querySelector('textarea');let oc=(x)=>z.value+=x;let cl=()=>z.value='';let re=()=>{try{z.value=eval(z.value);}catch(error){cl();}};[[1,2,3,'+'],[4,5,6,'-'],[7,8,9,'*'],['C',0,'=','/']].forEach((a)=>{let r=d.createElement('tr');r.style.lineHeight='64px';tbl.appendChild(r);a.forEach((b)=>{let tb=d.createElement('tb');tb.innerText=b;tb.style.padding='16px';tb.style.border='1px solid';r.appendChild(tb);tb.onclick=b==='='?re:b==='C'?cl:()=>oc(b);})})</script></table>
zserge/awfice
3,645
The world smallest office suite
HTML
zserge
Serge Zaitsev
code.html
HTML
<body oninput="i.srcdoc=h.value+'<style>'+c.value+'</style><script>'+j.value+'</script>'"><style>textarea,iframe{width:100%;height:50%;}body{margin:0;}textarea{width: 33.33%;font-size:18px;padding:0.5em}</style><textarea placeholder="HTML" id="h"></textarea><textarea placeholder="CSS" id="c"></textarea><textarea placeholder="JS" id="j"></textarea><iframe id="i"></iframe><script>document.querySelectorAll("textarea").forEach((t)=>t.addEventListener("keydown",function(t){var e,s;"Tab"==t.key&&(t.preventDefault(),e=this.selectionStart,s=this.selectionEnd,this.value=this.value.substring(0,e)+"  "+this.value.substring(s),this.selectionStart=this.selectionEnd=e+1)}))</script></body>
zserge/awfice
3,645
The world smallest office suite
HTML
zserge
Serge Zaitsev
draw.html
HTML
<canvas id=v><script>d=document,d.body.style.margin=0,P="onpointer",c=v.getContext`2d`,v.width=innerWidth,v.height=innerHeight,c.lineWidth=2,f=0,d[P+"down"]=e=>{f=e.pointerId+1;e.preventDefault();c.beginPath();c.moveTo(e.x,e.y)};d[P+"move"]=e=>{f==e.pointerId+1&&c.lineTo(e.x,e.y);c.stroke()},d[P+"up"]=_=>f=0</script></canvas>
zserge/awfice
3,645
The world smallest office suite
HTML
zserge
Serge Zaitsev
edit.html
HTML
<body contenteditable style=line-height:1.5;font-size:20px onload=document.body.focus()>
zserge/awfice
3,645
The world smallest office suite
HTML
zserge
Serge Zaitsev
examples/nanomagick/frontalface.h
C/C++ Header
#ifndef FRONTALFACE_H #define FRONTALFACE_H /* LBP Cascade for grayskull * Window: 24x24 * Features: 136 * Stages: 20 * Auto-generated from OpenCV XML */ #include <stdint.h> #define FRONTALFACE_NFEATURES 136 #define FRONTALFACE_NWEAKS 139 #define FRONTALFACE_NSTAGES 20 static const int8_t frontalface_features[] = { 0, 0, 3, 5, /* 0 */ 0, 0, 4, 2, /* 1 */ 0, 0, 6, 3, /* 2 */ 0, 1, 2, 3, /* 3 */ 0, 1, 3, 3, /* 4 */ 0, 1, 3, 7, /* 5 */ 0, 4, 3, 3, /* 6 */ 0, 11, 3, 4, /* 7 */ 0, 12, 8, 4, /* 8 */ 0, 14, 4, 3, /* 9 */ 1, 0, 5, 3, /* 10 */ 1, 1, 2, 2, /* 11 */ 1, 3, 3, 1, /* 12 */ 1, 7, 4, 4, /* 13 */ 1, 12, 2, 2, /* 14 */ 1, 13, 4, 1, /* 15 */ 1, 14, 4, 3, /* 16 */ 1, 17, 3, 2, /* 17 */ 2, 0, 2, 3, /* 18 */ 2, 1, 2, 2, /* 19 */ 2, 2, 4, 6, /* 20 */ 2, 3, 4, 4, /* 21 */ 2, 7, 2, 1, /* 22 */ 2, 11, 2, 3, /* 23 */ 2, 17, 3, 2, /* 24 */ 3, 0, 2, 2, /* 25 */ 3, 1, 7, 3, /* 26 */ 3, 7, 2, 1, /* 27 */ 3, 7, 2, 4, /* 28 */ 3, 18, 2, 2, /* 29 */ 4, 0, 2, 3, /* 30 */ 4, 3, 2, 1, /* 31 */ 4, 6, 2, 1, /* 32 */ 4, 6, 2, 5, /* 33 */ 4, 7, 5, 2, /* 34 */ 4, 8, 4, 3, /* 35 */ 4, 18, 2, 2, /* 36 */ 5, 0, 2, 2, /* 37 */ 5, 3, 4, 4, /* 38 */ 5, 6, 2, 5, /* 39 */ 5, 9, 2, 2, /* 40 */ 5, 10, 2, 2, /* 41 */ 6, 3, 4, 4, /* 42 */ 6, 4, 4, 3, /* 43 */ 6, 5, 2, 3, /* 44 */ 6, 5, 2, 5, /* 45 */ 6, 5, 4, 3, /* 46 */ 6, 6, 4, 2, /* 47 */ 6, 6, 4, 4, /* 48 */ 6, 18, 1, 2, /* 49 */ 6, 21, 2, 1, /* 50 */ 7, 0, 3, 7, /* 51 */ 7, 4, 2, 3, /* 52 */ 7, 9, 5, 1, /* 53 */ 7, 21, 2, 1, /* 54 */ 8, 0, 1, 4, /* 55 */ 8, 5, 2, 2, /* 56 */ 8, 5, 3, 2, /* 57 */ 8, 17, 3, 1, /* 58 */ 8, 18, 1, 2, /* 59 */ 9, 0, 5, 3, /* 60 */ 9, 2, 2, 6, /* 61 */ 9, 5, 1, 1, /* 62 */ 9, 11, 1, 1, /* 63 */ 9, 16, 1, 1, /* 64 */ 9, 16, 2, 1, /* 65 */ 9, 17, 1, 1, /* 66 */ 9, 18, 1, 1, /* 67 */ 10, 5, 1, 2, /* 68 */ 10, 5, 3, 3, /* 69 */ 10, 7, 1, 5, /* 70 */ 10, 8, 1, 1, /* 71 */ 10, 9, 1, 1, /* 72 */ 10, 10, 1, 1, /* 73 */ 10, 10, 1, 2, /* 74 */ 10, 14, 3, 3, /* 75 */ 10, 15, 1, 1, /* 76 */ 10, 15, 2, 1, /* 77 */ 10, 16, 1, 1, /* 78 */ 10, 16, 2, 1, /* 79 */ 10, 17, 1, 1, /* 80 */ 10, 21, 1, 1, /* 81 */ 11, 3, 2, 2, /* 82 */ 11, 5, 1, 2, /* 83 */ 11, 5, 3, 3, /* 84 */ 11, 5, 4, 6, /* 85 */ 11, 6, 1, 1, /* 86 */ 11, 7, 2, 2, /* 87 */ 11, 8, 1, 2, /* 88 */ 11, 10, 1, 1, /* 89 */ 11, 10, 1, 2, /* 90 */ 11, 15, 1, 1, /* 91 */ 11, 17, 1, 1, /* 92 */ 11, 18, 1, 1, /* 93 */ 12, 0, 2, 2, /* 94 */ 12, 1, 2, 5, /* 95 */ 12, 2, 4, 1, /* 96 */ 12, 3, 1, 3, /* 97 */ 12, 7, 3, 4, /* 98 */ 12, 10, 3, 2, /* 99 */ 12, 11, 1, 1, /* 100 */ 12, 12, 3, 2, /* 101 */ 12, 14, 4, 3, /* 102 */ 12, 17, 1, 1, /* 103 */ 12, 21, 2, 1, /* 104 */ 13, 6, 2, 5, /* 105 */ 13, 7, 3, 5, /* 106 */ 13, 11, 3, 2, /* 107 */ 13, 17, 2, 2, /* 108 */ 13, 17, 3, 2, /* 109 */ 13, 18, 1, 2, /* 110 */ 13, 18, 2, 2, /* 111 */ 14, 0, 2, 2, /* 112 */ 14, 1, 1, 3, /* 113 */ 14, 2, 3, 2, /* 114 */ 14, 7, 2, 1, /* 115 */ 14, 13, 2, 1, /* 116 */ 14, 13, 3, 3, /* 117 */ 14, 17, 2, 2, /* 118 */ 15, 0, 2, 2, /* 119 */ 15, 0, 2, 3, /* 120 */ 15, 4, 3, 2, /* 121 */ 15, 4, 3, 6, /* 122 */ 15, 6, 3, 2, /* 123 */ 15, 11, 3, 4, /* 124 */ 15, 13, 3, 2, /* 125 */ 15, 17, 2, 2, /* 126 */ 15, 17, 3, 2, /* 127 */ 16, 1, 2, 3, /* 128 */ 16, 3, 2, 4, /* 129 */ 16, 6, 1, 1, /* 130 */ 16, 16, 2, 2, /* 131 */ 17, 1, 2, 2, /* 132 */ 17, 1, 2, 5, /* 133 */ 17, 12, 2, 2, /* 134 */ 18, 0, 2, 2, /* 135 */ }; static const uint16_t frontalface_weak_feature_idx[] = { 46, 13, 2, 84, 21, 106, 48, 47, 12, 26, 8, 96, 33, 57, 125, 53, 60, 7, 98, 44, 24, 42, 6, 61, 123, 9, 105, 30, 35, 119, 82, 52, 99, 18, 111, 92, 51, 28, 112, 69, 19, 73, 126, 45, 114, 97, 25, 34, 134, 16, 74, 113, 110, 37, 41, 117, 65, 56, 20, 15, 129, 102, 88, 59, 27, 29, 128, 70, 4, 76, 124, 54, 95, 39, 120, 89, 14, 67, 86, 80, 75, 55, 71, 31, 40, 109, 130, 66, 49, 133, 0, 103, 43, 90, 104, 85, 24, 78, 5, 11, 32, 122, 68, 58, 94, 87, 127, 3, 79, 116, 132, 62, 23, 77, 22, 72, 50, 108, 92, 81, 1, 121, 38, 17, 100, 63, 101, 118, 92, 10, 131, 83, 135, 115, 64, 36, 93, 91, 107, }; static const float frontalface_weak_left_val[] = { -0.654321014881134f, -0.773921608924866f, -0.706856310367584f, -0.808373570442200f, -0.769841015338898f, -0.750655889511108f, -0.777599036693573f, -0.560188293457031f, -0.612452626228333f, -0.611449658870697f, -0.685407757759094f, -0.405109494924545f, -0.738816261291504f, -0.658294379711151f, -0.598132371902466f, -0.649878799915314f, -0.527819573879242f, -0.520650506019592f, -0.751606106758118f, -0.763931393623352f, -0.512376904487610f, -0.376317411661148f, -0.535276591777802f, -0.567837417125702f, -0.570626258850098f, -0.534460186958313f, -0.770034849643707f, -0.504366874694824f, -0.680804073810577f, -0.492759138345718f, -0.644510746002197f, -0.530755698680878f, -0.522763431072235f, -0.498357266187668f, -0.499086052179337f, -0.569500923156738f, -0.659040510654449f, -0.497277677059174f, -0.438315898180008f, -0.638610541820526f, -0.551279425621033f, -0.641875505447388f, -0.484190136194229f, -0.585573434829712f, -0.251847654581070f, -0.430343240499497f, -0.425955355167389f, -0.560558915138245f, -0.519265651702881f, -0.501307725906372f, -0.463141411542893f, -0.394971609115601f, -0.485588550567627f, -0.462028533220291f, -0.642064332962036f, -0.482011288404465f, -0.446555256843567f, -0.519058644771576f, -0.432380944490433f, -0.458873271942139f, -0.521855354309082f, -0.492000073194504f, -0.449456810951233f, -0.518082678318024f, -0.608124077320099f, -0.179019391536713f, -0.368102461099625f, -0.321723252534866f, -0.437328457832336f, -0.440483689308167f, -0.429415225982666f, -0.397305250167847f, -0.705468356609344f, -0.590594768524170f, -0.444920480251312f, -0.469381868839264f, -0.360035121440888f, -0.445989191532135f, -0.446606904268265f, -0.339495629072189f, -0.534651219844818f, -0.437933564186096f, -0.267098635435104f, -0.414984434843063f, -0.498589158058167f, -0.456872999668121f, -0.477083683013916f, -0.487771511077881f, -0.372165471315384f, -0.393419504165649f, -0.432330071926117f, -0.499327868223190f, -0.331022530794144f, -0.526656091213226f, -0.417188882827759f, -0.455670535564423f, -0.418252974748612f, -0.362536966800690f, -0.474292516708374f, -0.366627156734467f, -0.456763744354248f, -0.405511796474457f, -0.378789722919464f, -0.425832897424698f, -0.456102311611175f, -0.431467264890671f, -0.417454332113266f, -0.432136476039886f, -0.501838624477386f, -0.503750562667847f, -0.244819641113281f, -0.463328391313553f, -0.373109906911850f, -0.365890949964523f, -0.521438419818878f, -0.428903698921204f, -0.462154239416122f, -0.371154844760895f, -0.518065214157104f, -0.259259253740311f, -0.380119591951370f, -0.350911706686020f, -0.406875729560852f, -0.455714106559753f, -0.411780327558518f, -0.400839775800705f, -0.569418966770172f, -0.319534122943878f, -0.336533904075623f, -0.420454531908035f, -0.376255393028259f, -0.425349742174149f, -0.360199809074402f, -0.403429388999939f, -0.362089961767197f, -0.390381664037705f, -0.359144538640976f, -0.429767042398453f, -0.572700679302216f, }; static const float frontalface_weak_right_val[] = { 0.888888895511627f, 0.727863371372223f, 0.676153421401978f, 0.768569648265839f, 0.659291565418243f, 0.544460594654083f, 0.546546161174774f, 0.774311304092407f, 0.697812795639038f, 0.653762817382812f, 0.540323913097382f, 0.758403360843658f, 0.534084320068359f, 0.533949673175812f, 0.532350480556488f, 0.491335064172745f, 0.694637238979340f, 0.632992029190063f, 0.423202425241470f, 0.412356883287430f, 0.579183459281921f, 0.729823350906372f, 0.565948009490967f, 0.496147990226746f, 0.457228839397430f, 0.467205405235291f, 0.594394087791443f, 0.615127444267273f, 0.466732591390610f, 0.540188550949097f, 0.422782212495804f, 0.625817954540253f, 0.504974603652954f, 0.510644137859344f, 0.506050705909729f, 0.446046739816666f, 0.361642450094223f, 0.602707445621490f, 0.596623718738556f, 0.397799998521805f, 0.428207963705063f, 0.354986608028412f, 0.466801941394806f, 0.387913584709167f, 0.708865404129028f, 0.528328835964203f, 0.544080913066864f, 0.422073334455490f, 0.439985543489456f, 0.457025468349457f, 0.479024618864060f, 0.608203232288361f, 0.478536993265152f, 0.498966902494430f, 0.362435191869736f, 0.463214069604874f, 0.506178855895996f, 0.444148033857346f, 0.566376805305481f, 0.454703301191330f, 0.411109238862991f, 0.432672530412674f, 0.444851070642471f, 0.388897269964218f, 0.333322227001190f, 0.660597205162048f, 0.513974964618683f, 0.617155313491821f, 0.435818523168564f, 0.460122019052505f, 0.445216178894043f, 0.485452681779862f, 0.269799739122391f, 0.510193288326263f, 0.449070930480957f, 0.406109482049942f, 0.505632698535919f, 0.413241565227508f, 0.413506776094437f, 0.565864503383636f, 0.358447939157486f, 0.412364512681961f, 0.601414322853088f, 0.467088818550110f, 0.371958494186401f, 0.396581202745438f, 0.386260151863098f, 0.377898633480072f, 0.499440014362335f, 0.476964145898819f, 0.434216409921646f, 0.366537809371948f, 0.562462627887726f, 0.370440304279327f, 0.454043567180633f, 0.370426207780838f, 0.426723122596741f, 0.468465626239777f, 0.368950724601746f, 0.458012729883194f, 0.389470815658569f, 0.548794507980347f, 0.453200340270996f, 0.420279175043106f, 0.400274783372879f, 0.408634662628174f, 0.424986898899078f, 0.409083873033524f, 0.370253384113312f, 0.356498122215271f, 0.568970918655396f, 0.358792960643768f, 0.429045557975769f, 0.455647319555283f, 0.322103738784790f, 0.400495618581772f, 0.383274853229523f, 0.461270153522492f, 0.320587038993836f, 0.587301611900330f, 0.471882730722427f, 0.509480714797974f, 0.413013637065888f, 0.353979200124741f, 0.411859244108200f, 0.403475701808929f, 0.296476274728775f, 0.529401898384094f, 0.506745874881744f, 0.516574561595917f, 0.407530277967453f, 0.372805535793304f, 0.456325620412826f, 0.416081696748734f, 0.459414273500443f, 0.438145935535431f, 0.462407886981964f, 0.402329355478287f, 0.299593478441238f, }; static const uint16_t frontalface_weak_subset_offset[] = { 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, 144, 152, 160, 168, 176, 184, 192, 200, 208, 216, 224, 232, 240, 248, 256, 264, 272, 280, 288, 296, 304, 312, 320, 328, 336, 344, 352, 360, 368, 376, 384, 392, 400, 408, 416, 424, 432, 440, 448, 456, 464, 472, 480, 488, 496, 504, 512, 520, 528, 536, 544, 552, 560, 568, 576, 584, 592, 600, 608, 616, 624, 632, 640, 648, 656, 664, 672, 680, 688, 696, 704, 712, 720, 728, 736, 744, 752, 760, 768, 776, 784, 792, 800, 808, 816, 824, 832, 840, 848, 856, 864, 872, 880, 888, 896, 904, 912, 920, 928, 936, 944, 952, 960, 968, 976, 984, 992, 1000, 1008, 1016, 1024, 1032, 1040, 1048, 1056, 1064, 1072, 1080, 1088, 1096, 1104, }; static const uint16_t frontalface_weak_num_subsets[] = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, }; static const int32_t frontalface_subsets[] = { -67130709, -21569, -1426120013, -1275125205, -21585, -16385, 587145899, -24005, -163512766, -769593758, -10027009, -262145, -514457854, -193593353, -524289, -1, -363936790, -893203669, -1337948010, -136907894, 1088782736, -134217726, -741544961, -1590337, 2147483647, 1946124287, -536870913, 2147450879, 738132490, 1061101567, 243204619, 2147446655, 2147483647, 263176079, 1879048191, 254749487, 1879048191, -134252545, -268435457, 801111999, -98110272, 1610939566, -285484400, -850010381, -189334372, -1671954433, -571026695, -262145, -798690576, -131075, 1095771153, -237144073, -65569, -1, -216727745, -69206049, -21585, -20549, -100818262, -738254174, -20561, -36865, -151016790, -134238549, -286003217, 183435247, -268994614, -421330945, -402686081, 1090387966, -286785545, -402653185, -50347012, 970882927, -50463492, -1253377, -134218251, -50364513, -33619992, -172490753, -273, -135266321, 1877977738, -2088243418, -134217987, 2146926575, -18910642, 1095231247, -1273, 1870659519, -20971602, -67633153, -134250731, 2004875127, -250, -150995969, -868162224, -76810262, -4262145, -257, 1465211989, -268959873, -2656269, -524289, -12817, -49, -541103378, -152950, -38993, -20481, -1153876, -72478976, -269484161, -452984961, -319816180, -1594032130, -2111, -990117891, -488975296, -520947741, 557787431, 670265215, -1342193665, -1075892225, 1998528318, 1056964607, -33570977, -1, -536873708, 880195381, -16842788, -20971521, -176687276, -168427659, -16777260, -33554626, -1, -62981529, -1090591130, 805330978, -8388827, -41945787, -39577, -531118985, -725287348, 1347747543, -852489, -16809993, 1489881036, -167903241, -1, -1, -32777, 1006582562, -65, 935312171, -8388609, -1078198273, -1, 733886267, -85474705, 2138828511, -1036436754, 817625855, 1123369029, -58796809, -1013468481, -194513409, -17409, -20481, -268457797, -134239493, -17473, -1, -21829, -21846, -805310737, -2098262358, -269504725, 682502698, 2147483519, 1740574719, -1090519233, -268472385, -67109678, -6145, -8, -87884584, -20481, -1073762305, -50856216, -16849696, -138428633, 1002418167, -1359008245, -1908670465, -1346685918, 910098423, -1359010520, -1346371657, -89138513, -4196353, 1256531674, -1330665426, 1216308261, -36190633, 33498198, -151796633, 1073769576, 206601725, -34013449, -33554433, -789514004, -101384321, -690225153, -264193, -1432340997, -823623681, -49153, -34291724, -269484035, -1342767105, -1078198273, -1277955, -1067385040, -195758209, -436748425, -134217731, -50855988, -129, -1, -1, 832534325, -34111555, -26050561, -423659521, -268468364, 2105014143, -2114244, -17367185, -1089439888, -1080524865, 2143059967, -1114121, -1140949004, -3, -2361356, -739516, -1074071553, -1074003969, -1, -1280135430, -5324817, -1, -335548482, 582134442, -706937396, -705364068, -540016724, -570495027, -570630659, -587857963, -33628164, -35848193, -2035630093, 42119158, -268503053, -1671444, 261017599, 1325432815, 1954394111, -805306449, -282529488, -1558073088, 1426018736, -170526448, -546832487, -5113037, -34243375, -570427929, 1016332500, -606301707, 915094269, -1080086049, -1837027144, -1361600280, 2147318747, 1067975613, -656420166, -15413034, -141599534, -603435836, 1505950458, -787556946, -79823438, -1326199134, -901591776, -201916417, -262, -67371009, -143312112, -524289, -41943178, -1, -4507851, -411340929, -268437513, -67502145, -17350859, -32901, -71344315, -29377, -75894785, -117379438, -239063587, -12538500, 1485072126, 2076233213, 2123118847, 801906927, -823480413, 786628589, -16876049, -1364262914, 242165211, 1315930109, -696268833, -455082829, -521411968, 6746762, -1396236286, -2038436114, -185612509, 57669627, -143132877, -1041235973, -478153869, 1076028979, -1645895615, 1365298272, -557859073, -339771473, 1442574528, -1058802061, -246350404, -1650402048, -1610612745, -788400696, 1467604861, -2787397, 1476263935, -4481349, -24819, 1572863935, -16809993, -67108865, 2146778388, 1433927541, -268608444, -34865205, -1841359, -134271049, -32769, -5767369, -1116675, -2185, -8231, -33603327, -1359507589, -1360593090, -1073778729, -269553812, -809512977, 1744707583, -41959433, -134758978, 729753407, -134270989, -1140907329, -235200777, 658456383, 2147467263, -1140900929, -16385, -310380553, -420675595, -193005472, -353568129, 1205338070, -990380036, 887604324, -420544526, -1427119361, 1978920959, -287119734, -487068946, 114759245, -540578051, -707510259, -671660453, -738463762, -889949281, -328301948, -121832450, -1142658284, -1863576559, 2146417353, -263185, -76228780, -65538, -1, -67174401, -148007, -33, -221796, -272842924, 369147696, -1625232112, 2138570036, -1189900, 790708019, -1212613127, 799948719, -4456483, 784215839, -290015241, 536832799, -402984963, -1342414991, -838864897, -176769, -268456129, -486418688, -171915327, -340294900, -21938, -519766032, -772751172, -73096060, -585322623, -33554953, -475332625, -1423463824, -2077230421, -4849669, -2080505925, -219032928, -1071915349, -834130468, -134217476, -1349314083, -1073803559, -619913764, -1449131844, -1386890321, -1979118423, -285249779, 1912569855, -16530, -1731022870, -1161904146, -1342177297, -268439634, -1464078708, 1246232575, 1078001186, -10027057, 60102, -277348353, -43646987, -1210581153, 1195769615, -778583572, -612921106, -578775890, -4036478, -1946580497, -1164766570, -1986687009, -12103599, -1073759445, 2013231743, -1363169553, -1082459201, -1414286549, 868185983, -1356133589, -1077936257, -84148365, -2093417722, -1204850272, 564290299, -67121221, -1342177350, -1309195902, -776734797, -25694458, 67104495, -290216278, -168563037, 2083877442, 1702788383, -144191964, -234882162, -857980836, 904682741, -1612267521, 232279415, 1550862252, -574825221, -357380888, -4579409, -98549440, -137838400, 494928389, -246013630, 939541351, -1196072350, -620603549, 2137216273, -150995201, 2071191945, -1302151626, 536934335, -1059008937, 914128709, 1147328110, -268369925, -134509479, 1610575703, -1342177289, 1861484541, -1107833788, 1577058173, -333558568, -136319041, -1, 1060154476, -1090984524, -630918524, -539492875, 779616255, -839568424, -321, -269562385, -285029906, -791084350, -17923776, 235286671, 1275504943, 1344390399, -966276889, 17825984, -747628419, 595427229, 1474759671, 575672208, -1684005538, 872217086, -1155858277, -336593039, 1873735591, -822231622, -355795238, -470820869, -1997537409, -1057132384, -1015285005, -834212130, -593694721, -322142257, -364892500, -951029539, -302125121, -1615106053, -79249765, 1342144479, 2147431935, -33554561, -47873, -855685912, -1, 1988052447, 536827383, 1431368960, -183437936, -537002499, -137497097, 1560590321, -84611081, -2097193, -513, -1645259691, 2105491231, 2130706431, 1458995007, -8567536, -42483883, -33780003, -21004417, -612381022, -505806938, -362027516, -452985106, 275854917, 1920431639, -12600561, -134221825, -805573153, -161, -554172679, -530519488, -16779441, 2000682871, -33604275, -150997129, 6192, 435166195, 1467449341, 2046691505, -1608493775, -4755729, -1083162625, -71365637, -41689215, -3281034, 1853357967, -420712635, -415924289, -270209208, -1088293113, -825311232, -117391116, -42203396, 2080374461, -188709, -542008165, -356831940, -1091125345, -1073796897, -276830049, 1378714472, -1342181951, 757272098, 1073740607, -282199241, -415761549, 170896931, -796075825, -123166849, 2113667055, -217530421, -1107432194, -16385, -806359809, -391188771, -890246622, 15525883, -487690486, 47116238, -1212319899, -1291847681, -68159890, -469829921, -1361180685, -1898008841, -1090588811, -285410071, -1074016265, -840443905, 2147221487, -262145, 1426190596, 1899364271, 2142731795, -142607505, -508232452, -21563393, -41960001, -65, -201337965, 10543906, -236498096, -746195597, 1974565825, -15204415, 921907633, -190058309, -595026732, -656401928, -268649235, -571490699, -440600392, -133131, -358810952, -2004088646, 941674740, -1107882114, 1332789109, -67691015, -1360463693, -1556612430, -609108546, 733546933, -17114945, -240061474, 1552871558, -82775604, -932393844, -1308544889, -532635478, -99042357, -655906006, 1405502603, -939205164, 1884929228, -498859222, 559417357, -1928559445, -286264385, -335837777, 1860677295, -90, -1946186226, 931096183, 251612987, 2013265917, -671232197, 37769424, -137772680, 374692301, 2002666345, -536176194, -1644484728, 807009019, 1069089930, -5505, 2147462911, 2143265466, -4511070, -16450, -257, -201348440, -71333206, -136842268, -499330741, 2015250980, -87107126, -641665744, -788524639, -1147864792, -134892563, -146800880, -1780368555, 2111170033, -140904684, -16777551, -1946681885, -1646463595, -839131947, -832054034, -981663763, -301990281, -578814081, -932319000, -1997406723, -33555201, -69206017, -118492417, -1209026825, 1119023838, -1334313353, 1112948738, -297319313, 1378887291, -139469193, -1714382628, -2353704, -112094959, -549613092, -1567058760, -1718550464, -342315012, -1074972227, -85219702, 316836394, -33279, 1904970288, 2117267315, -260901769, -621461759, -88607770, -294654041, -353603585, -1641159686, -50331921, -2080899877, 1145569279, -143132713, -152044037, 1887453658, -638545712, -1877976819, -34320972, -1071067983, -661345416, -583338277, 1060190561, -994063296, 1088745462, -318837116, -319881377, 1102566613, 1165490103, -121679694, -134744129, -285233233, -538992907, 1811935199, -369234005, -529, -20593, -20505, -1561401854, -1335245632, 1968917183, 1940861695, 536816369, -1226071367, -570908176, 457026619, 1000020667, -1360318719, -1979797897, -50435249, -18646473, -608879292, -805306691, -269304244, -17840167, 2062765935, -16449, -1275080721, -16406, 45764335, -1090552065, -772846337, -570464322, -536896021, 1080817663, -738234288, -965478709, -2082767969, 1290855887, 1993822934, -990381609, -818943025, 168730891, -293610428, -79249354, 669224671, 621166734, 1086506807, 1473768907, -68895696, -67107736, -1414315879, -841676168, -619843344, -1180610531, -1081990469, 1043203389, -54002134, -543485719, -2124882422, -1437445858, -115617074, -1195787391, -1096024366, -2140472445, -67113211, 2003808111, 1862135111, 846461923, -2752, 2002237273, -273154752, 1937223539, 1179423888, -78064940, -611839555, -539167899, -1289358360, -1650810108, -892540499, -1432827684, -285212705, -78450761, -656212031, -264050110, -27787425, -1334349961, -547662981, -135796924, 341863476, 403702016, -550588417, 1600194541, -1080690735, 951127993, -1388580949, -1153717473, -586880702, -204831512, -100644596, -39319550, -1191150794, 705692513, 457203315, -75806957, -416546870, 545911370, -673716192, -775559454, -264113598, 139424, -183369982, -204474641, -1026505020, -589692154, -1740499937, -1563770497, 1348491006, -60710713, -1109853489, -633909413, -1448872304, -477895040, -1778390608, -772418127, -1789923416, -1612057181, -805306693, -1415842113, 407905424, -582449988, 52654751, -1294472, -285103725, -74633006, 1871559083, 1057955850, 4112, -1259563825, -846671428, -100902460, 1838164148, -74153752, -90653988, -1074263896, -285216785, -823206977, -1085589, -1081346, 1207959293, 1157103471, 2097133565, -2097169, -12465, -536875169, 2147478367, 2130706303, -37765492, -866124467, -318782328, -1392509185, 2147449663, -20741, -16794757, 1945873146, -16710, -1, -8406341, -67663041, -155191713, 866117231, 1651407483, 548272812, -479201468, -447742449, 1354229504, -261884429, -225319378, -251682065, -492783986, -792341777, -1287261695, 1393643841, -11274182, -213909521, -382220122, -2002072729, -51404800, -371201558, -923011069, -2135301457, -2066104743, -1042557441, -627353764, -48295149, 1581203952, -436258614, -105268268, -1435893445, -638126888, -1061107126, -8399181, 1058107691, -621022752, -251003468, -12582915, -574619739, -994397789, -1648362021, -348343812, -1078389516, 1717960437, 364735981, -1783841602, -4883137, -457572354, -1076950384, -1976661318, -287957604, -1659497122, -782068, 43591089, -453637880, 1435470000, -1077438561, -67110925, 14874979, -142633168, -1338923040, 2046713291, -2067933195, 1473503712, -789579837, -272814301, -1577073, -1118685, -305156120, -1052289, -1073813756, -538971154, -355523038, -2233, -214486242, -538514758, 573747007, -159390971, 1994225489, -973738098, -203424005, -261031688, -1330369299, -641860609, 1029570301, -1306461192, -1196149518, -1529767778, 683139823, -572993608, -34042628, -417865, -111109, -1433365268, -19869715, -1920939864, -1279457063, -626275097, -615256993, 1651946018, 805366393, 2016559730, -430780849, -799868165, -16580645, 1354797300, -1090957603, 1976418270, -1342502178, -1851873892, -1194637077, -1153521668, -1108399474, 68157712, 1211368313, -304759523, 1063017136, 798797750, -275513546, 648167355, -1145357350, -546318240, -1628569602, -163577944, -537002306, -545456389, -1325465645, -380446736, -1058473386, }; static const uint16_t frontalface_stage_weak_start[] = { 0, 3, 7, 11, 16, 21, 26, 31, 37, 44, 51, 58, 65, 73, 82, 92, 101, 110, 119, 129, }; static const uint16_t frontalface_stage_nweaks[] = { 3, 4, 4, 5, 5, 5, 5, 6, 7, 7, 7, 7, 8, 9, 10, 9, 9, 9, 10, 10, }; static const float frontalface_stage_threshold[] = { -0.752089202404022f, -0.487207829952240f, -1.159232854843140f, -0.756235599517822f, -0.808535814285278f, -0.554997146129608f, -0.877646028995514f, -1.113928794860840f, -0.824362576007843f, -1.223711609840393f, -0.554423093795776f, -0.716156065464020f, -0.674394071102142f, -1.204229831695557f, -0.840205013751984f, -1.197439432144165f, -0.573312819004059f, -0.489259690046310f, -0.591194093227386f, -0.761291623115540f, }; static const struct gs_lbp_cascade frontalface = { .window_w = 24, .window_h = 24, .nfeatures = 136, .nweaks = 139, .nstages = 20, .features = frontalface_features, .weak_feature_idx = frontalface_weak_feature_idx, .weak_left_val = frontalface_weak_left_val, .weak_right_val = frontalface_weak_right_val, .weak_subset_offset = frontalface_weak_subset_offset, .weak_num_subsets = frontalface_weak_num_subsets, .subsets = frontalface_subsets, .stage_weak_start = frontalface_stage_weak_start, .stage_nweaks = frontalface_stage_nweaks, .stage_threshold = frontalface_stage_threshold, }; #endif /* FRONTALFACE_H */
zserge/grayskull
680
A tiny, dependency-free computer vision library in C for embedded systems, drones, and robotics.
C
zserge
Serge Zaitsev
examples/nanomagick/nanomagick.c
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <unistd.h> #include "grayskull.h" // face detection data from opencv lbpcascade_frontalface.xml cascade #include "frontalface.h" static void identify(struct gs_image img, struct gs_image *out, char *argv[]) { (void)out, (void)argv; printf("Portable Graymap, %ux%u (%u) pixels\n", img.w, img.h, img.w * img.h); } static void view(struct gs_image img, struct gs_image *out, char *argv[]) { (void)out, (void)argv; char *term = getenv("TERM"); int use_256 = term && strstr(term, "256color"); int term_width = 80; struct winsize w; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0) { term_width = w.ws_col; } int display_width = term_width - 2; // some margin int display_height = (img.h * display_width) / (img.w * (use_256 ? 1 : 2)); if (use_256) { for (int y = 0; y < display_height; y += 2) { for (int x = 0; x < display_width; x++) { int ix = (x * img.w) / display_width; int iy1 = (y * img.h) / display_height; int iy2 = ((y + 1) * img.h) / display_height; uint8_t p1 = img.data[iy1 * img.w + ix]; uint8_t p2 = (iy2 < (int)img.h) ? img.data[iy2 * img.w + ix] : p1; int c1 = 232 + (p1 * 23) / 255; int c2 = 232 + (p2 * 23) / 255; printf("\x1b[38;5;%d;48;5;%dm▀", c1, c2); } printf("\x1b[0m\n"); } } else { const char *blocks[] = {" ", "░", "▒", "▓", "█"}; for (int y = 0; y < display_height; y++) { for (int x = 0; x < display_width; x++) { int img_x = (x * img.w) / display_width; int img_y = (y * img.h) / display_height; uint8_t pixel = img.data[img_y * img.w + img_x]; int block_index = (pixel * 4) / 255; // Map 0-255 to 0-4 if (block_index > 4) block_index = 4; printf("%s", blocks[block_index]); } printf("\n"); } } printf("\n"); } static void resize(struct gs_image img, struct gs_image *out, char *argv[]) { int w = atoi(argv[0]), h = atoi(argv[1]); if (w <= 0 || h <= 0) { fprintf(stderr, "Error: Invalid width or height\n"); return; } *out = gs_alloc(w, h); gs_resize(*out, img); } static void crop(struct gs_image img, struct gs_image *out, char *argv[]) { int x = atoi(argv[0]), y = atoi(argv[1]), w = atoi(argv[2]), h = atoi(argv[3]); if (x < 0 || y < 0 || w <= 0 || h <= 0 || x + w > (int)img.w || y + h > (int)img.h) { fprintf(stderr, "Error: Invalid crop rectangle\n"); return; } *out = gs_alloc(w, h); gs_crop(*out, img, (struct gs_rect){x, y, w, h}); } static void blur(struct gs_image img, struct gs_image *out, char *argv[]) { int r = atoi(argv[0]); if (r <= 0) { fprintf(stderr, "Error: Invalid radius: %s\n", argv[0]); return; } *out = gs_alloc(img.w, img.h); gs_blur(*out, img, r); } static void threshold(struct gs_image img, struct gs_image *out, char *argv[]) { int t = strcmp(argv[0], "otsu") == 0 ? gs_otsu_threshold(img) : atoi(argv[0]); if (t <= 0) { fprintf(stderr, "Error: Invalid threshold: %s\n", argv[0]); return; } *out = gs_alloc(img.w, img.h); gs_copy(*out, img); gs_threshold(*out, t); } static void adaptive(struct gs_image img, struct gs_image *out, char *argv[]) { int r = atoi(argv[0]), c = atoi(argv[1]); if (r <= 0 || c < 0) { fprintf(stderr, "Error: Invalid radius or constant\n"); return; } *out = gs_alloc(img.w, img.h); gs_adaptive_threshold(*out, img, r, c); } static void morph(struct gs_image img, struct gs_image *out, char *argv[]) { const char *op = argv[0]; int n = atoi(argv[1]); if ((strcmp(op, "erode") != 0 && strcmp(op, "dilate") != 0) || n <= 0) { fprintf(stderr, "Error: Invalid morphological operation or iterations\n"); return; } *out = gs_alloc(img.w, img.h); struct gs_image temp = gs_alloc(img.w, img.h); gs_copy(*out, img); for (int i = 0; i < n; i++) { if (strcmp(op, "erode") == 0) { gs_erode(temp, *out); } else if (strcmp(op, "dilate") == 0) { gs_dilate(temp, *out); } else { fprintf(stderr, "Error: Unknown morphological operation: %s\n", op); gs_free(temp); gs_free(*out); *out = (struct gs_image){0, 0, NULL}; return; } gs_copy(*out, temp); } gs_free(temp); } static void sobel(struct gs_image img, struct gs_image *out, char *argv[]) { (void)argv; *out = gs_alloc(img.w, img.h); gs_sobel(*out, img); } static void blobs(struct gs_image img, struct gs_image *out, char *argv[]) { int n = atoi(argv[0]); if (n <= 0) { fprintf(stderr, "Error: Invalid number of blobs\n"); return; } *out = gs_alloc(img.w, img.h); gs_label *labels = (gs_label *)calloc(img.w * img.h, sizeof(gs_label)); struct gs_blob *blobs = (struct gs_blob *)calloc(n, sizeof(struct gs_blob)); if (!labels || !blobs) { fprintf(stderr, "Error: Memory allocation failed\n"); free(labels); free(blobs); gs_free(*out); *out = (struct gs_image){0, 0, NULL}; return; } unsigned nblobs = gs_blobs(img, labels, blobs, n); for (unsigned i = 0; i < nblobs; i++) { unsigned x1 = GS_MAX(0, (int)blobs[i].box.x - 2), y1 = GS_MAX(0, (int)blobs[i].box.y - 2); unsigned x2 = GS_MIN(img.w, blobs[i].box.x + blobs[i].box.w + 2), y2 = GS_MIN(img.h, blobs[i].box.y + blobs[i].box.h + 2); for (unsigned y = y1; y <= y2; y++) { for (unsigned x = x1; x <= x2; x++) { out->data[y * out->w + x] = 128; } } } gs_for(img, x, y) if (img.data[y * out->w + x] > 128) out->data[y * img.w + x] = 255; } static void draw_line(struct gs_image img, unsigned x1, unsigned y1, unsigned x2, unsigned y2, uint8_t color) { int dx = abs((int)x2 - (int)x1), dy = abs((int)y2 - (int)y1); int sx = x1 < x2 ? 1 : -1, sy = y1 < y2 ? 1 : -1, err = dx - dy; int x = x1, y = y1; while (1) { if (x >= 0 && x < (int)img.w && y >= 0 && y < (int)img.h) img.data[y * img.w + x] = color; if (x == (int)x2 && y == (int)y2) break; int e2 = 2 * err; if (e2 > -dy) err -= dy, x += sx; if (e2 < dx) err += dx, y += sy; } } static void scan(struct gs_image img, struct gs_image *out, char *argv[]) { (void)argv; struct gs_image tmp = gs_alloc(img.w, img.h); // preprocess, remove noise, binarise gs_blur(tmp, img, 1); gs_threshold(tmp, gs_otsu_threshold(tmp) + 10); // find blobs gs_label *labels = calloc(img.w * img.h, sizeof(gs_label)); struct gs_blob blobs[1000]; unsigned n = gs_blobs(tmp, labels, blobs, sizeof(blobs) / sizeof(blobs[0])); // find largest blob unsigned largest = 0; for (unsigned i = 1; i < n; i++) if (blobs[i].area > blobs[largest].area) largest = i; // find corners struct gs_point corners[4]; gs_blob_corners(tmp, labels, &blobs[largest], corners); // perspective correct const unsigned OUTPUT_WIDTH = 800, OUTPUT_HEIGHT = 1000; *out = gs_alloc(OUTPUT_WIDTH, OUTPUT_HEIGHT); gs_perspective_correct(*out, img, corners); gs_free(tmp); free(labels); } static int sort_keypoints(const void *a, const void *b) { const struct gs_keypoint *kp1 = (const struct gs_keypoint *)a, *kp2 = (const struct gs_keypoint *)b; return kp2->response - kp1->response; } static void keypoints(struct gs_image img, struct gs_image *out, char *argv[]) { int n = atoi(argv[0]), t = atoi(argv[1]); if (n <= 0 || t < 0) { fprintf(stderr, "Error: Invalid number of keypoints or threshold\n"); return; } struct gs_keypoint *kps = (struct gs_keypoint *)calloc(5000, sizeof(struct gs_keypoint)); if (!kps) { fprintf(stderr, "Error: Memory allocation failed\n"); return; } struct gs_image tmp = gs_alloc(img.w, img.h); unsigned nkps = gs_fast(img, tmp, kps, 5000, t); // sort keypoints by response (score) qsort(kps, nkps, sizeof(struct gs_keypoint), sort_keypoints); *out = gs_alloc(img.w, img.h); gs_copy(*out, img); for (unsigned i = 0; i < GS_MIN((unsigned)n, nkps); i++) { unsigned x = kps[i].pt.x, y = kps[i].pt.y, r = 2; for (int dy = -r; dy <= (int)r; dy++) gs_set(*out, x, y + dy, 255); for (int dx = -r; dx <= (int)r; dx++) gs_set(*out, x + dx, y, 255); } gs_free(tmp); free(kps); } // Pyramid ORB extraction for nanomagick static unsigned extract_pyramid_orb_nm(struct gs_image img, struct gs_keypoint *kps, unsigned nkps, unsigned threshold, uint8_t *buffer, unsigned n_levels) { if (n_levels > 4) n_levels = 4; struct gs_image pyramid[4]; uint8_t *scoremaps[4]; unsigned total_kps = 0, buffer_offset = 0; pyramid[0] = img; // Generate downsampled levels for (unsigned level = 1; level < n_levels; level++) { unsigned w = pyramid[level - 1].w / 2, h = pyramid[level - 1].h / 2; if (w < 32 || h < 32) { n_levels = level; break; } pyramid[level] = (struct gs_image){w, h, buffer + buffer_offset}; buffer_offset += w * h; gs_downsample(pyramid[level], pyramid[level - 1]); } // Allocate scoremap buffers for (unsigned level = 0; level < n_levels; level++) { scoremaps[level] = buffer + buffer_offset; buffer_offset += pyramid[level].w * pyramid[level].h; } // Extract features from each level for (unsigned level = 0; level < n_levels; level++) { unsigned level_nkps = nkps / n_levels; if (level == n_levels - 1) level_nkps = nkps - total_kps; if (level_nkps == 0) continue; unsigned level_kps = gs_orb_extract(pyramid[level], &kps[total_kps], level_nkps, threshold, scoremaps[level]); // Scale coordinates back to original image size unsigned scale = 1 << level; for (unsigned i = total_kps; i < total_kps + level_kps; i++) { kps[i].pt.x *= scale; kps[i].pt.y *= scale; } total_kps += level_kps; } return total_kps; } static void orb(struct gs_image img, struct gs_image *out, char *argv[]) { struct gs_image template = gs_read_pgm(argv[0]); if (!gs_valid(template)) { printf("Error: Cannot load template image %s\n", argv[0]); return; } static uint8_t buffer[1024 * 1024]; static struct gs_keypoint template_kps[5000], scene_kps[5000]; static struct gs_match matches[300]; // Extract pyramid ORB features unsigned n_template = extract_pyramid_orb_nm(template, template_kps, 2500, 20, buffer, 3); unsigned n_scene = extract_pyramid_orb_nm(img, scene_kps, 2500, 20, buffer, 3); unsigned n_matches = gs_match_orb(template_kps, n_template, scene_kps, n_scene, matches, 300, 60.0f); printf("Template: %u keypoints, Scene: %u keypoints, Matches: %u\n", n_template, n_scene, n_matches); if (n_matches > 0) { // Sort matches by distance for (unsigned i = 0; i < n_matches - 1; i++) for (unsigned j = i + 1; j < n_matches; j++) if (matches[j].distance < matches[i].distance) { struct gs_match temp = matches[i]; matches[i] = matches[j]; matches[j] = temp; } // Create stitched output *out = gs_alloc(template.w + img.w, GS_MAX(template.h, img.h)); for (unsigned i = 0; i < out->w * out->h; i++) out->data[i] = 0; // Stitch images for (unsigned y = 0; y < template.h; y++) for (unsigned x = 0; x < template.w; x++) out->data[y * out->w + x] = template.data[y * template.w + x]; for (unsigned y = 0; y < img.h; y++) for (unsigned x = 0; x < img.w; x++) out->data[y * out->w + (template.w + x)] = img.data[y * img.w + x]; // Draw top matches unsigned draw_matches = GS_MIN(15, n_matches); for (unsigned i = 0; i < draw_matches; i++) { unsigned x1 = template_kps[matches[i].idx1].pt.x, y1 = template_kps[matches[i].idx1].pt.y; unsigned x2 = scene_kps[matches[i].idx2].pt.x + template.w, y2 = scene_kps[matches[i].idx2].pt.y; draw_line(*out, x1, y1, x2, y2, 255); } } gs_free(template); } static void faces(struct gs_image img, struct gs_image *out, char *argv[]) { static uint32_t integral[640 * 480]; // Max typical image size static struct gs_rect rects[100]; int min_neighbors = argv[0] ? atoi(argv[0]) : 1; if (min_neighbors <= 0) { fprintf(stderr, "Error: minimum neighbors must be positive\n"); return; } if (img.w * img.h > 640 * 480) { fprintf(stderr, "Error: Image too large for face detection (max 640x480)\n"); return; } gs_integral(img, integral); unsigned nrects = gs_lbp_detect(&frontalface, integral, img.w, img.h, rects, 100, 1.2f, 1.0f, 4.0f, min_neighbors); *out = gs_alloc(img.w, img.h); gs_copy(*out, img); for (unsigned i = 0; i < nrects; i++) { struct gs_rect r = rects[i]; draw_line(*out, r.x, r.y, r.x + r.w, r.y, 255); draw_line(*out, r.x, r.y + r.h, r.x + r.w, r.y + r.h, 255); draw_line(*out, r.x, r.y, r.x, r.y + r.h, 255); draw_line(*out, r.x + r.w, r.y, r.x + r.w, r.y + r.h, 255); } } struct cmd { const char *name; const char *help; int argc; int hasout; void (*func)(struct gs_image img, struct gs_image *out, char *argv[]); } commands[] = { {"identify", " Show image information", 0, 0, identify}, {"view", " Display image in terminal", 0, 0, view}, {"resize", "<w> <h> Resize image to WxH", 2, 1, resize}, {"crop", "<x> <y> <w> <h> Crop image to rectangle (x,y,w,h)", 4, 1, crop}, {"blur", "<r> Blur image with radius R", 1, 1, blur}, {"threshold", "<t> Apply threshold (0-255 or otsu)", 1, 1, threshold}, {"adaptive", "<r> <c> Apply adaptive threshold, radius R and constant C", 2, 1, adaptive}, {"sobel", " Edge detection (Sobel)", 0, 1, sobel}, {"morph", "<op> <n> Morphological operation (erode/dilate) N times", 2, 1, morph}, {"blobs", "<n> Find up to N blobs", 1, 1, blobs}, {"scan", " Simple document scanner", 0, 1, scan}, {"keypoints", "<n> <t> Detect N keypoints with threshold T", 2, 1, keypoints}, {"orb", "<template.pgm> Find template in scene using ORB features", 1, 1, orb}, {"faces", "<n> Detect faces using LBP cascade with N minNeighbors", 1, 1, faces}, {NULL, NULL, 0, 0, NULL}, }; static void usage(const char *app) { printf("Usage: %s <command> [params] [input.pgm] [output.pgm]\n\n", app); printf("Commands:\n"); for (struct cmd *cmd = commands; cmd->name != NULL; cmd++) printf(" %s %s\n", cmd->name, cmd->help); } int main(int argc, char *argv[]) { if (argc < 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { usage(argv[0]); return 1; } for (struct cmd *cmd = commands; cmd->name != NULL; cmd++) { if (strcmp(argv[1], cmd->name) != 0) continue; // nanomagic <cmd> [params...] <input.pgm> [output.pgm] if (argc != cmd->argc + cmd->hasout + 3) { fprintf(stderr, "Error: Wrong number of arguments for '%s'\n", argv[1]); usage(argv[0]); return 1; } struct gs_image img = gs_read_pgm(argv[cmd->argc + 2]); if (!gs_valid(img)) { fprintf(stderr, "Error: Could not load %s\n", argv[cmd->argc + 2]); return 1; } struct gs_image out = {0, 0, NULL}; cmd->func(img, &out, argv + 2); if (cmd->hasout) { if (!out.data) { fprintf(stderr, "Error: Command '%s' did not produce output image\n", argv[1]); gs_free(img); return 1; } if (gs_write_pgm(out, argv[cmd->argc + 3]) != 0) { fprintf(stderr, "Error: Could not save %s\n", argv[cmd->argc + 3]); gs_free(img); gs_free(out); return 1; } gs_free(out); } gs_free(img); return 0; } printf("Error: Unknown command '%s'\n", argv[1]); return 1; }
zserge/grayskull
680
A tiny, dependency-free computer vision library in C for embedded systems, drones, and robotics.
C
zserge
Serge Zaitsev
examples/wasm/grayskull.c
C
#include <stddef.h> // A simple bump allocator for our WASM module since we don't have stdlib. #define MEMORY_HEAP_SIZE (1024 * 1024 * 8) // 8MB heap for a few buffers static unsigned char memory_heap[MEMORY_HEAP_SIZE]; static size_t heap_ptr = 0; void* gs_alloc(size_t size) { size_t aligned_size = (size + 7) & ~7; if (heap_ptr + aligned_size > MEMORY_HEAP_SIZE) return NULL; void* ptr = &memory_heap[heap_ptr]; heap_ptr += aligned_size; return ptr; } void gs_free(void* ptr) { (void)ptr; /* No-op for bump allocator */ } void gs_reset_allocator(void) { heap_ptr = 0; } // Minimal standard library functions for WASM nostdlib build void* memset(void* s, int c, size_t n) { unsigned char* p = (unsigned char*)s; for (size_t i = 0; i < n; i++) p[i] = (unsigned char)c; return s; } void* memcpy(void* dest, const void* src, size_t n) { unsigned char* d = (unsigned char*)dest; const unsigned char* s = (const unsigned char*)src; for (size_t i = 0; i < n; i++) d[i] = s[i]; return dest; } #define gs_assert(cond) #define GS_NO_STDLIB #define GS_API #include "../../grayskull.h" #include "../nanomagick/frontalface.h" #define NUM_BUFFERS 3 static struct gs_image images[NUM_BUFFERS]; // Functions to be exported to WASM void gs_init_image(int idx, int w, int h) { if (idx < 0 || idx >= NUM_BUFFERS) return; // Simple bump allocation, so we just allocate once on first use. // gs_reset_allocator() must be called from JS if sizes change. if (images[idx].data == NULL) { images[idx].data = gs_alloc(w * h); } images[idx].w = w; images[idx].h = h; } uint8_t* gs_get_image_data(int idx) { if (idx < 0 || idx >= NUM_BUFFERS) return NULL; return images[idx].data; } void gs_copy_image(int dst_idx, int src_idx) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; gs_copy(images[dst_idx], images[src_idx]); } void gs_blur_image(int dst_idx, int src_idx, int radius) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; gs_blur(images[dst_idx], images[src_idx], radius); } uint8_t gs_otsu_threshold_image(int src_idx) { if (src_idx < 0 || src_idx >= NUM_BUFFERS) return 0; return gs_otsu_threshold(images[src_idx]); } void gs_threshold_image(int img_idx, uint8_t threshold) { if (img_idx < 0 || img_idx >= NUM_BUFFERS) return; gs_threshold(images[img_idx], threshold); } void gs_adaptive_threshold_image(int dst_idx, int src_idx, int block_size) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; gs_adaptive_threshold(images[dst_idx], images[src_idx], block_size | 1, 2); } void gs_erode_image(int dst_idx, int src_idx) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; gs_erode(images[dst_idx], images[src_idx]); } void gs_erode_image_iterations(int dst_idx, int src_idx, int iterations) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; // First iteration gs_erode(images[dst_idx], images[src_idx]); // Additional iterations (ping-pong between buffers) int temp_idx = (dst_idx + 1) % NUM_BUFFERS; if (temp_idx == src_idx) temp_idx = (temp_idx + 1) % NUM_BUFFERS; for (int i = 1; i < iterations; i++) { if (i % 2 == 1) { gs_erode(images[temp_idx], images[dst_idx]); } else { gs_erode(images[dst_idx], images[temp_idx]); } } // Ensure result is in dst_idx if (iterations > 1 && iterations % 2 == 0) { gs_copy(images[dst_idx], images[temp_idx]); } } void gs_dilate_image(int dst_idx, int src_idx) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; gs_dilate(images[dst_idx], images[src_idx]); } void gs_dilate_image_iterations(int dst_idx, int src_idx, int iterations) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; // First iteration gs_dilate(images[dst_idx], images[src_idx]); // Additional iterations (ping-pong between buffers) int temp_idx = (dst_idx + 1) % NUM_BUFFERS; if (temp_idx == src_idx) temp_idx = (temp_idx + 1) % NUM_BUFFERS; for (int i = 1; i < iterations; i++) { if (i % 2 == 1) { gs_dilate(images[temp_idx], images[dst_idx]); } else { gs_dilate(images[dst_idx], images[temp_idx]); } } // Ensure result is in dst_idx if (iterations > 1 && iterations % 2 == 0) { gs_copy(images[dst_idx], images[temp_idx]); } } void gs_sobel_image(int dst_idx, int src_idx) { if (dst_idx < 0 || dst_idx >= NUM_BUFFERS || src_idx < 0 || src_idx >= NUM_BUFFERS) return; gs_sobel(images[dst_idx], images[src_idx]); } // Blob detection functions static gs_label labels_buffer[640 * 480]; // Max image size buffer for labels static struct gs_blob blobs_buffer[200]; // Buffer for blob storage unsigned gs_detect_blobs(int src_idx, unsigned max_blobs) { if (src_idx < 0 || src_idx >= NUM_BUFFERS) return 0; if (max_blobs > 200) max_blobs = 200; // Limit to buffer size unsigned size = images[src_idx].w * images[src_idx].h; for (unsigned i = 0; i < size; i++) labels_buffer[i] = 0; for (unsigned i = 0; i < max_blobs; i++) blobs_buffer[i] = (struct gs_blob){0}; return gs_blobs(images[src_idx], labels_buffer, blobs_buffer, max_blobs); } struct gs_blob* gs_get_blob(unsigned idx) { if (idx >= 200) return NULL; return &blobs_buffer[idx]; } gs_label* gs_get_labels_buffer(void) { return labels_buffer; } // Blob corners buffer static struct gs_point blob_corners_buffer[4]; void gs_get_blob_corners(unsigned blob_idx) { if (blob_idx >= 200) return; gs_blob_corners(images[0], labels_buffer, &blobs_buffer[blob_idx], blob_corners_buffer); } struct gs_point* gs_get_blob_corner(unsigned corner_idx) { if (corner_idx >= 4) return NULL; return &blob_corners_buffer[corner_idx]; } // Contour tracing for largest blob static struct gs_contour largest_blob_contour; static uint8_t contour_visited_buffer[640 * 480]; void gs_trace_largest_blob_contour(int src_idx) { if (src_idx < 0 || src_idx >= NUM_BUFFERS) return; // Find largest blob unsigned largest_idx = 0; for (unsigned i = 1; i < 200; i++) { if (blobs_buffer[i].area > blobs_buffer[largest_idx].area) { largest_idx = i; } } if (blobs_buffer[largest_idx].area == 0) return; // Set up visited buffer struct gs_image visited = {images[src_idx].w, images[src_idx].h, contour_visited_buffer}; for (unsigned i = 0; i < visited.w * visited.h; i++) { visited.data[i] = 0; } // Find a starting point on the blob boundary largest_blob_contour.start = (struct gs_point){blobs_buffer[largest_idx].box.x, blobs_buffer[largest_idx].box.y}; // Find actual boundary point by scanning the blob's bounding box for (unsigned y = blobs_buffer[largest_idx].box.y; y < blobs_buffer[largest_idx].box.y + blobs_buffer[largest_idx].box.h; y++) { for (unsigned x = blobs_buffer[largest_idx].box.x; x < blobs_buffer[largest_idx].box.x + blobs_buffer[largest_idx].box.w; x++) { if (x < images[src_idx].w && y < images[src_idx].h && images[src_idx].data[y * images[src_idx].w + x] > 128) { largest_blob_contour.start = (struct gs_point){x, y}; goto found_start; } } } found_start: gs_trace_contour(images[src_idx], visited, &largest_blob_contour); } struct gs_contour* gs_get_largest_blob_contour(void) { return &largest_blob_contour; } // FAST keypoint detection static struct gs_keypoint keypoints_buffer[500]; static uint8_t scoremap_buffer[640 * 480]; unsigned gs_detect_fast_keypoints(int src_idx, unsigned threshold, unsigned max_keypoints) { if (src_idx < 0 || src_idx >= NUM_BUFFERS) return 0; if (max_keypoints > 500) max_keypoints = 500; struct gs_image scoremap = {images[src_idx].w, images[src_idx].h, scoremap_buffer}; return gs_fast(images[src_idx], scoremap, keypoints_buffer, max_keypoints, threshold); } struct gs_keypoint* gs_get_keypoint(unsigned idx) { if (idx >= 500) return NULL; return &keypoints_buffer[idx]; } // ORB feature extraction static struct gs_keypoint orb_keypoints_buffer[300]; static struct gs_keypoint template_keypoints_buffer[300]; static struct gs_match matches_buffer[200]; unsigned gs_extract_orb_features(int src_idx, unsigned threshold, unsigned max_keypoints) { if (src_idx < 0 || src_idx >= NUM_BUFFERS) return 0; if (max_keypoints > 300) max_keypoints = 300; return gs_orb_extract(images[src_idx], orb_keypoints_buffer, max_keypoints, threshold, scoremap_buffer); } struct gs_keypoint* gs_get_orb_keypoint(unsigned idx) { if (idx >= 300) return NULL; return &orb_keypoints_buffer[idx]; } void gs_store_template_keypoints(unsigned count) { if (count > 300) count = 300; for (unsigned i = 0; i < count; i++) { template_keypoints_buffer[i] = orb_keypoints_buffer[i]; } } unsigned gs_match_orb_features(unsigned template_count, unsigned scene_count, float max_distance) { if (template_count > 300) template_count = 300; if (scene_count > 300) scene_count = 300; return gs_match_orb(template_keypoints_buffer, template_count, orb_keypoints_buffer, scene_count, matches_buffer, 200, max_distance); } struct gs_match* gs_get_match(unsigned idx) { if (idx >= 200) return NULL; return &matches_buffer[idx]; } struct gs_keypoint* gs_get_template_keypoint(unsigned idx) { if (idx >= 300) return NULL; return &template_keypoints_buffer[idx]; } // Contour detection for largest blob static struct gs_contour contour_buffer; static uint8_t visited_buffer[640 * 480]; int gs_detect_largest_blob_contour(int src_idx, unsigned max_blobs) { if (src_idx < 0 || src_idx >= NUM_BUFFERS) return 0; // First detect blobs unsigned num_blobs = gs_detect_blobs(src_idx, max_blobs); if (num_blobs == 0) return 0; // Find largest blob unsigned largest_idx = 0; unsigned largest_area = blobs_buffer[0].area; for (unsigned i = 1; i < num_blobs; i++) { if (blobs_buffer[i].area > largest_area) { largest_area = blobs_buffer[i].area; largest_idx = i; } } if (largest_area < 100) return 0; // Skip very small blobs // Initialize visited map unsigned size = images[src_idx].w * images[src_idx].h; for (unsigned i = 0; i < size; i++) visited_buffer[i] = 0; struct gs_image visited = {images[src_idx].w, images[src_idx].h, visited_buffer}; // Find a starting point on the blob boundary struct gs_blob* blob = &blobs_buffer[largest_idx]; contour_buffer.start.x = blob->box.x; contour_buffer.start.y = blob->box.y; // Find first boundary pixel int found = 0; for (unsigned y = blob->box.y; y < blob->box.y + blob->box.h && !found; y++) { for (unsigned x = blob->box.x; x < blob->box.x + blob->box.w && !found; x++) { if (labels_buffer[y * images[src_idx].w + x] == blob->label) { contour_buffer.start.x = x; contour_buffer.start.y = y; found = 1; } } } if (!found) return 0; // Trace contour gs_trace_contour(images[src_idx], visited, &contour_buffer); return contour_buffer.length > 0 ? 1 : 0; } struct gs_contour* gs_get_contour(void) { return &contour_buffer; } // LBP Face detection static uint32_t integral_buffer[640 * 480]; static struct gs_rect faces_buffer[100]; unsigned gs_detect_faces(int src_idx, int min_neighbors) { if (src_idx < 0 || src_idx >= NUM_BUFFERS) return 0; if (images[src_idx].w * images[src_idx].h > 640 * 480) return 0; gs_integral(images[src_idx], integral_buffer); return gs_lbp_detect(&frontalface, integral_buffer, images[src_idx].w, images[src_idx].h, faces_buffer, 100, 1.2f, 1.0f, 4.0f, min_neighbors); } struct gs_rect* gs_get_face(unsigned idx) { if (idx >= 100) return NULL; return &faces_buffer[idx]; }
zserge/grayskull
680
A tiny, dependency-free computer vision library in C for embedded systems, drones, and robotics.
C
zserge
Serge Zaitsev
examples/wasm/grayskull.js
JavaScript
const video = document.getElementById('video'); const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const startButton = document.getElementById('start'); const stopButton = document.getElementById('stop'); const cameraSelect = document.getElementById('cameraSelect'); const addStepButton = document.getElementById('add-step'); const pipelineStepsContainer = document.getElementById('pipeline-steps'); let wasm, memory; let videoStream; let animationFrameId; let imageBuffers = [null, null, null]; // To hold pointers to WASM memory let overlayCtx; // For drawing overlays let templateKeypoints = null; // For ORB template matching const operations = { "blur": { params: [{ name: "radius", type: "range", default: 3, min: 1, max: 20 }] }, "sobel": { params: [] }, "otsu": { params: [] }, "thresh": { params: [{ name: "threshold", type: "range", default: 128, min: 0, max: 255 }] }, "adaptive": { params: [{ name: "block_size", type: "range", default: 15, min: 3, max: 51, step: 2 }] }, "erode": { params: [{ name: "iterations", type: "range", default: 1, min: 1, max: 10 }] }, "dilate": { params: [{ name: "iterations", type: "range", default: 1, min: 1, max: 10 }] }, "blobs": { params: [{ name: "max_blobs", type: "range", default: 10, min: 1, max: 100 }] }, "contour": { params: [] }, "keypoints": { params: [{ name: "threshold", type: "range", default: 10, min: 5, max: 100 }, { name: "max_points", type: "range", default: 300, min: 10, max: 2000 }] }, "orb": { params: [{ name: "threshold", type: "range", default: 30, min: 5, max: 500 }, { name: "max_features", type: "range", default: 100, min: 10, max: 300 }] }, "faces": { params: [{ name: "min_neighbors", type: "range", default: 1, min: 0, max: 10 }] }, }; // --- Grayscale Conversion in JavaScript --- function rgbaToGray(rgba, gray) { for (let i = 0; i < gray.length; i++) { const r = rgba[i * 4], g = rgba[i * 4 + 1], b = rgba[i * 4 + 2]; gray[i] = 0.299 * r + 0.587 * g + 0.114 * b; } } function grayToRgba(gray, rgba) { for (let i = 0; i < gray.length; i++) { rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = gray[i]; rgba[i * 4 + 3] = 255; // Alpha } } // Template capture functionality function captureTemplate() { if (!wasm || !imageBuffers[0]) { alert('Camera not running'); return; } const width = canvas.width; const height = canvas.height; const imageSize = width * height; // Capture current frame as template ctx.drawImage(video, 0, 0, width, height); const imageData = ctx.getImageData(0, 0, width, height); const gray = new Uint8Array(imageSize); rgbaToGray(imageData.data, gray); new Uint8Array(memory.buffer, imageBuffers[0], imageSize).set(gray); // Extract ORB features from template const templateFeatures = wasm.gs_extract_orb_features(0, 20, 200); if (templateFeatures > 0) { wasm.gs_store_template_keypoints(templateFeatures); templateKeypoints = { count: templateFeatures }; document.getElementById('template-status').textContent = `Template captured: ${templateFeatures} features`; console.log(`Template captured with ${templateFeatures} ORB features`); } else { alert('No features detected in template. Try capturing a more textured area.'); } } async function init() { try { const importObject = { env: {} }; // Fallback for WASM loading if streaming fails (MIME type issues) let wasmModule; try { const { instance } = await WebAssembly.instantiateStreaming(fetch('grayskull.wasm'), importObject); wasmModule = instance; } catch (streamError) { console.warn("Streaming failed, trying fallback:", streamError); const response = await fetch('grayskull.wasm'); const bytes = await response.arrayBuffer(); const { instance } = await WebAssembly.instantiate(bytes, importObject); wasmModule = instance; } wasm = wasmModule.exports; memory = wasm.memory; console.log("WebAssembly module loaded."); } catch (e) { console.warn("WASM initialization failed.", e); alert("Failed to load grayskull.wasm. Make sure the file is present and the server is running correctly."); return; } await populateCameraList(); addStepButton.onclick = () => addPipelineStep(); document.getElementById('capture-template').onclick = captureTemplate; addPipelineStep('blur'); // Add a default first step startButton.disabled = false; } async function populateCameraList() { try { if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { throw new Error("Media device enumeration not supported."); } // Request camera permission first to get device labels let permissionStream; try { permissionStream = await navigator.mediaDevices.getUserMedia({ video: true }); } catch (permError) { console.warn("Could not get camera permission for labeling:", permError); } const devices = await navigator.mediaDevices.enumerateDevices(); const videoDevices = devices.filter(d => d.kind === 'videoinput'); // Stop the permission stream if (permissionStream) { permissionStream.getTracks().forEach(track => track.stop()); } cameraSelect.innerHTML = ''; if (videoDevices.length === 0) { const option = document.createElement('option'); option.textContent = 'No cameras found'; cameraSelect.appendChild(option); return; } videoDevices.forEach((device, i) => { const option = document.createElement('option'); option.value = device.deviceId; option.textContent = device.label || `Camera ${i + 1}`; cameraSelect.appendChild(option); }); } catch (error) { console.error("Could not enumerate video devices:", error); // Add a fallback option cameraSelect.innerHTML = '<option value="">Default Camera</option>'; } } startButton.onclick = async () => { if (videoStream) stopCamera(); try { // More flexible constraints - prefer 320x240 but allow fallback const constraints = { video: { width: { ideal: 320, min: 160, max: 640 }, height: { ideal: 240, min: 120, max: 480 }, frameRate: { ideal: 30, max: 60 } } }; // Add device constraint if a specific camera is selected const selectedDeviceId = cameraSelect.value; if (selectedDeviceId) { constraints.video.deviceId = { ideal: selectedDeviceId }; } videoStream = await navigator.mediaDevices.getUserMedia(constraints); video.srcObject = videoStream; await video.play(); canvas.width = video.videoWidth; canvas.height = video.videoHeight; console.log(`Video resolution: ${canvas.width}x${canvas.height}`); if (wasm) { wasm.gs_reset_allocator(); for (let i = 0; i < imageBuffers.length; i++) { wasm.gs_init_image(i, canvas.width, canvas.height); imageBuffers[i] = wasm.gs_get_image_data(i); } } animationFrameId = requestAnimationFrame(processFrame); startButton.disabled = true; stopButton.disabled = false; } catch (error) { console.error("Failed to start camera:", error); alert(`Could not start camera. Error: ${error.message}`); } }; function stopCamera() { if (animationFrameId) cancelAnimationFrame(animationFrameId); if (videoStream) videoStream.getTracks().forEach(track => track.stop()); video.srcObject = null; animationFrameId = null; startButton.disabled = false; stopButton.disabled = true; } stopButton.onclick = stopCamera; function addPipelineStep(opName = 'blur') { const stepDiv = document.createElement('div'); stepDiv.className = 'pipeline-step'; const select = document.createElement('select'); for (const key in operations) { const option = document.createElement('option'); option.value = key; option.textContent = key; if (key === opName) option.selected = true; select.appendChild(option); } stepDiv.appendChild(select); const controlsContainer = document.createElement('span'); stepDiv.appendChild(controlsContainer); const removeBtn = document.createElement('button'); removeBtn.textContent = 'Remove'; removeBtn.onclick = () => stepDiv.remove(); stepDiv.appendChild(removeBtn); select.onchange = () => updateStepControls(controlsContainer, select.value); updateStepControls(controlsContainer, opName); pipelineStepsContainer.appendChild(stepDiv); } function updateStepControls(container, opName) { container.innerHTML = ''; const op = operations[opName]; if (!op || !op.params) return; op.params.forEach(param => { const input = document.createElement('input'); input.type = param.type; input.name = param.name; if (param.type === 'range') { input.min = param.min || 0; input.max = param.max || 255; input.step = param.step || 1; input.value = param.default || 0; container.appendChild(input); const valueSpan = document.createElement('span'); valueSpan.textContent = `(${input.value})`; input.oninput = () => valueSpan.textContent = `(${input.value})`; container.appendChild(valueSpan); } }); } function processFrame() { if (!videoStream || video.paused || video.ended || !wasm) { if (animationFrameId) requestAnimationFrame(processFrame); return; } const width = canvas.width; const height = canvas.height; const imageSize = width * height; // 1. Get video frame and convert to grayscale, placing it in buffer 0 ctx.drawImage(video, 0, 0, width, height); const imageData = ctx.getImageData(0, 0, width, height); const gray = new Uint8Array(imageSize); rgbaToGray(imageData.data, gray); new Uint8Array(memory.buffer, imageBuffers[0], imageSize).set(gray); // 2. Execute pipeline let readIdx = 0; let writeIdx = 1; let overlayData = []; // Store data for overlays pipelineStepsContainer.querySelectorAll('.pipeline-step').forEach(stepDiv => { const op = stepDiv.querySelector('select').value; const inputs = stepDiv.querySelectorAll('input'); const params = Array.from(inputs).map(i => parseInt(i.value, 10)); switch (op) { case 'blur': wasm.gs_blur_image(writeIdx, readIdx, params[0]); break; case 'thresh': wasm.gs_copy_image(writeIdx, readIdx); wasm.gs_threshold_image(writeIdx, params[0]); break; case 'adaptive': wasm.gs_adaptive_threshold_image(writeIdx, readIdx, params[0]); break; case 'erode': wasm.gs_erode_image_iterations(writeIdx, readIdx, params[0] || 1); break; case 'dilate': wasm.gs_dilate_image_iterations(writeIdx, readIdx, params[0] || 1); break; case 'sobel': wasm.gs_sobel_image(writeIdx, readIdx); break; case 'otsu': const threshold = wasm.gs_otsu_threshold_image(readIdx); wasm.gs_copy_image(writeIdx, readIdx); wasm.gs_threshold_image(writeIdx, threshold); break; case 'blobs': wasm.gs_copy_image(writeIdx, readIdx); const numBlobs = wasm.gs_detect_blobs(readIdx, params[0] || 10); overlayData.push({ type: 'blobs', count: numBlobs }); break; case 'contour': wasm.gs_copy_image(writeIdx, readIdx); const hasContour = wasm.gs_detect_largest_blob_contour(readIdx, 50); if (hasContour) { overlayData.push({ type: 'contour', hasContour: true }); } break; case 'keypoints': wasm.gs_copy_image(writeIdx, readIdx); const numKeypoints = wasm.gs_detect_fast_keypoints(readIdx, params[0] || 20, params[1] || 100); overlayData.push({ type: 'keypoints', count: numKeypoints }); break; case 'orb': wasm.gs_copy_image(writeIdx, readIdx); const numOrbFeatures = wasm.gs_extract_orb_features(readIdx, params[0] || 20, params[1] || 100); overlayData.push({ type: 'orb', count: numOrbFeatures }); // If we have template keypoints, try to match if (templateKeypoints && templateKeypoints.count > 0) { const numMatches = wasm.gs_match_orb_features(templateKeypoints.count, numOrbFeatures, 60.0); overlayData.push({ type: 'matches', count: numMatches }); } break; case 'faces': wasm.gs_copy_image(writeIdx, readIdx); const numFaces = wasm.gs_detect_faces(readIdx, params[0] || 1); overlayData.push({ type: 'faces', count: numFaces }); break; } // Swap buffers [readIdx, writeIdx] = [writeIdx, (writeIdx + 1) % 3 === readIdx ? (writeIdx + 2) % 3 : (writeIdx + 1) % 3]; }); // 3. Display result from the last read buffer const resultGray = new Uint8Array(memory.buffer, imageBuffers[readIdx], imageSize); const imageDataOut = ctx.createImageData(width, height); grayToRgba(resultGray, imageDataOut.data); ctx.putImageData(imageDataOut, 0, 0); // 4. Draw overlays drawOverlays(overlayData, width, height); animationFrameId = requestAnimationFrame(processFrame); } function drawOverlays(overlayData, width, height) { if (!overlayData.length) return; // Create overlay canvas for drawing annotations ctx.strokeStyle = '#ff0000'; ctx.fillStyle = '#ff0000'; ctx.lineWidth = 2; overlayData.forEach(overlay => { switch (overlay.type) { case 'blobs': drawBlobs(overlay.count); break; case 'contour': if (overlay.hasContour) { drawContour(); } break; case 'keypoints': drawKeypoints(overlay.count, '#00ff00'); break; case 'orb': drawKeypoints(overlay.count, '#0080ff', true); break; case 'matches': drawMatches(overlay.count); break; case 'faces': drawFaces(overlay.count); break; } }); } function drawBlobs(count) { ctx.strokeStyle = '#ff0000'; ctx.lineWidth = 2; for (let i = 0; i < count; i++) { const blobPtr = wasm.gs_get_blob(i); if (!blobPtr) continue; // Read blob data from WASM memory const blobData = new Uint32Array(memory.buffer, blobPtr, 8); // gs_blob struct const area = blobData[1]; if (area < 50) continue; // Skip very small blobs const x = blobData[2]; const y = blobData[3]; const w = blobData[4]; const h = blobData[5]; const centroidX = blobData[6]; const centroidY = blobData[7]; // Draw bounding box (rectangle) ctx.strokeStyle = '#ff0000'; ctx.strokeRect(x, y, w, h); // Draw centroid ctx.fillStyle = '#ff0000'; ctx.beginPath(); ctx.arc(centroidX, centroidY, 3, 0, 2 * Math.PI); ctx.fill(); // Draw area text ctx.fillStyle = '#ffffff'; ctx.fillText(`${area}`, x, y - 5); // Draw corners const cornersPtr = wasm.gs_get_blob_corners(i); if (cornersPtr) { ctx.fillStyle = '#00ff00'; const cornersData = new Uint32Array(memory.buffer, cornersPtr, 8); // 4 points, 2 coords each for (let j = 0; j < 4; j++) { const cornerX = cornersData[j * 2]; const cornerY = cornersData[j * 2 + 1]; ctx.beginPath(); ctx.arc(cornerX, cornerY, 2, 0, 2 * Math.PI); ctx.fill(); } } } } function drawContour() { const contourPtr = wasm.gs_get_contour(); if (!contourPtr) return; // Read contour data const contourData = new Uint32Array(memory.buffer, contourPtr, 6); // gs_contour struct const startX = contourData[4]; const startY = contourData[5]; const length = contourData[6]; if (length === 0) return; // Draw contour as a highlighted outline ctx.strokeStyle = '#ffff00'; ctx.lineWidth = 2; // For simplicity, draw a circle at the start point to indicate contour detection ctx.beginPath(); ctx.arc(startX, startY, 8, 0, 2 * Math.PI); ctx.stroke(); // Draw length text ctx.fillStyle = '#ffff00'; ctx.fillText(`Contour: ${length}px`, startX + 10, startY - 10); } function drawKeypoints(count, color, withOrientation = false) { ctx.strokeStyle = color; ctx.fillStyle = color; ctx.lineWidth = 1; for (let i = 0; i < count; i++) { const kpPtr = withOrientation ? wasm.gs_get_orb_keypoint(i) : wasm.gs_get_keypoint(i); if (!kpPtr) continue; // Read keypoint data (x, y, response, angle) const kpData = new Uint32Array(memory.buffer, kpPtr, 3); const x = kpData[0]; const y = kpData[1]; const response = kpData[2]; if (response < 10) continue; // Skip weak keypoints // Draw circle ctx.beginPath(); ctx.arc(x, y, 3, 0, 2 * Math.PI); ctx.stroke(); // Draw orientation line for ORB features if (withOrientation) { const angleData = new Float32Array(memory.buffer, kpPtr + 12, 1); const angle = angleData[0]; const length = 8; const endX = x + Math.cos(angle) * length; const endY = y + Math.sin(angle) * length; ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(endX, endY); ctx.stroke(); } } } function drawMatches(count) { // Yellow circles show ORB feature matches between the captured template and current scene // Lower distance numbers indicate better matches (more similar features) // Use "Capture Template" button to set a reference image for matching if (!templateKeypoints || count === 0) return; ctx.strokeStyle = '#ffff00'; ctx.lineWidth = 1; for (let i = 0; i < count; i++) { const matchPtr = wasm.gs_get_match(i); if (!matchPtr) continue; // Read match data (idx1, idx2, distance) const matchData = new Uint32Array(memory.buffer, matchPtr, 3); const templateIdx = matchData[0]; const sceneIdx = matchData[1]; const distance = matchData[2]; if (distance > 40) continue; // Skip poor matches // Get scene keypoint const sceneKpPtr = wasm.gs_get_orb_keypoint(sceneIdx); if (!sceneKpPtr) continue; const sceneKpData = new Uint32Array(memory.buffer, sceneKpPtr, 2); const sceneX = sceneKpData[0]; const sceneY = sceneKpData[1]; // Draw match indicator (yellow circle = matched feature) ctx.fillStyle = '#ffff00'; ctx.beginPath(); ctx.arc(sceneX, sceneY, 5, 0, 2 * Math.PI); ctx.fill(); // Draw match distance (lower = better match) ctx.fillStyle = '#000000'; ctx.fillText(`${distance}`, sceneX + 6, sceneY - 6); ctx.fillStyle = '#ffffff'; ctx.fillText(`${distance}`, sceneX + 6, sceneY - 6); } } function drawFaces(count) { ctx.strokeStyle = '#00ff00'; ctx.lineWidth = 2; for (let i = 0; i < count; i++) { const facePtr = wasm.gs_get_face(i); if (!facePtr) continue; // Read rect data (x, y, w, h) const rectData = new Uint32Array(memory.buffer, facePtr, 4); const x = rectData[0]; const y = rectData[1]; const w = rectData[2]; const h = rectData[3]; // Draw rectangle ctx.strokeRect(x, y, w, h); // Draw label ctx.fillStyle = '#00ff00'; ctx.font = '14px monospace'; ctx.fillText(`Face ${i + 1}`, x, y - 5); } } init();
zserge/grayskull
680
A tiny, dependency-free computer vision library in C for embedded systems, drones, and robotics.
C
zserge
Serge Zaitsev
examples/wasm/index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Grayskull WASM Demo</title> <style> body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; } .controls, .container { display: flex; justify-content: center; margin: 10px 0; } video, canvas { border: 1px solid black; } .pipeline-controls { border: 1px solid #ccc; padding: 10px; margin-top: 10px; } .pipeline-step { display: flex; align-items: center; margin-bottom: 5px; } .pipeline-step select, .pipeline-step input { margin: 0 5px; } .template-controls { border: 1px solid #ddd; padding: 10px; margin: 10px 0; background-color: #f9f9f9; } #template-status { font-weight: bold; color: #007700; } .info-panel { margin: 10px 0; padding: 10px; border: 1px solid #ccc; background-color: #f5f5f5; font-family: monospace; font-size: 12px; } </style> </head> <body> <h1>Grayskull WebAssembly Demo</h1> <div class="controls"> <select id="cameraSelect"></select> <button id="start">Start Camera</button> <button id="stop" disabled>Stop Camera</button> </div> <div class="container"> <div> <h3>Original</h3> <video id="video" width="320" height="240" autoplay muted playsinline></video> </div> <div> <h3>Processed</h3> <canvas id="canvas" width="320" height="240"></canvas> </div> </div> <div class="pipeline-controls"> <h3>Processing Pipeline</h3> <div id="pipeline-steps"></div> <button id="add-step">Add Step</button> </div> <div class="template-controls"> <h3>Object Tracking</h3> <button id="capture-template">Capture Template</button> <span id="template-status">No template captured</span> <p>Add an "orb" step to your pipeline, then capture a template to enable object tracking.</p> </div> <div class="info-panel"> <h4>Available Operations:</h4> <p><strong>blur</strong> - Gaussian blur filter</p> <p><strong>thresh</strong> - Binary threshold</p> <p><strong>adaptive</strong> - Adaptive threshold</p> <p><strong>erode/dilate</strong> - Morphological operations</p> <p><strong>sobel</strong> - Edge detection</p> <p><strong>otsu</strong> - Automatic threshold selection</p> <p><strong>blobs</strong> - Connected component analysis (red boxes)</p> <p><strong>keypoints</strong> - FAST corner detection (green circles)</p> <p><strong>orb</strong> - ORB features with orientation (blue circles with lines)</p> <p><strong>contours</strong> - Boundary tracing (colored boxes with length info)</p> </div> <script src="grayskull.js"></script> </body> </html>
zserge/grayskull
680
A tiny, dependency-free computer vision library in C for embedded systems, drones, and robotics.
C
zserge
Serge Zaitsev
grayskull.h
C/C++ Header
#ifndef GRAYSKULL_H #define GRAYSKULL_H #include <limits.h> #include <stdint.h> #ifndef GS_API #define GS_API static inline #endif #define GS_MIN(a, b) ((a) < (b) ? (a) : (b)) #define GS_MAX(a, b) ((a) > (b) ? (a) : (b)) struct gs_image { unsigned w, h; uint8_t *data; }; struct gs_rect { unsigned x, y, w, h; }; struct gs_point { unsigned x, y; }; typedef uint16_t gs_label; struct gs_blob { gs_label label; unsigned area; struct gs_rect box; struct gs_point centroid; }; struct gs_contour { struct gs_rect box; struct gs_point start; unsigned length; }; struct gs_keypoint { struct gs_point pt; unsigned response; float angle; uint32_t descriptor[8]; }; struct gs_match { unsigned idx1, idx2; unsigned distance; }; struct gs_lbp_cascade { uint16_t window_w, window_h; uint16_t nfeatures, nweaks, nstages; const int8_t *features; /* [nfeatures * 4] */ const uint16_t *weak_feature_idx; const float *weak_left_val, *weak_right_val; const uint16_t *weak_subset_offset, *weak_num_subsets; const int32_t *subsets; const uint16_t *stage_weak_start, *stage_nweaks; const float *stage_threshold; }; static inline int gs_valid(struct gs_image img) { return img.data && img.w > 0 && img.h > 0; } #ifdef GS_NO_STDLIB // no asserts, no memory allocation, no file I/O #define gs_assert(cond) static inline float gs_atan2(float y, float x) { if (x == 0.0f) { return (y > 0.0f ? 1.570796f : (y < 0.0f ? -1.570796f : 0.0f)); } float r, angle, abs_y = (y >= 0.0f ? y : -y); if (x >= 0.0f) r = (x - abs_y) / (x + abs_y), angle = 0.785398f - 0.785398f * r; else r = (x + abs_y) / (abs_y - x), angle = 3.0f * 0.785398f - 0.785398f * r; return (y < 0.0f ? -angle : angle); } static inline float gs_sin(float x) { while (x > 3.141592f) x -= 6.283185f; while (x < -3.141592f) x += 6.283185f; int sign = 1; if (x < 0) x = -x, sign = -1; if (x > 1.570796f) x = 3.141592f - x; float x2 = x * x, res = x * (1.0f - x2 * (0.16666667f - 0.0083333310f * x2)); return sign * res; } #else #include <math.h> #include <stdio.h> #include <stdlib.h> #define gs_assert(cond) \ if (!(cond)) { \ fprintf(stderr, "Assertion failed: %s\n", #cond); \ abort(); \ } static inline float gs_atan2(float y, float x) { return atan2f(y, x); } static inline float gs_sin(float x) { return sinf(x); } GS_API struct gs_image gs_alloc(unsigned w, unsigned h) { if (w == 0 || h == 0) return (struct gs_image){0, 0, NULL}; uint8_t *data = (uint8_t *)calloc(w * h, sizeof(uint8_t)); return (struct gs_image){w, h, data}; } GS_API void gs_free(struct gs_image img) { free(img.data); } GS_API struct gs_image gs_read_pgm(const char *path) { struct gs_image img = {0, 0, NULL}; FILE *f = (path[0] == '-' && !path[1]) ? stdin : fopen(path, "rb"); if (!f) return img; unsigned w, h, maxval; if (fscanf(f, "P5\n%u %u\n%u\n", &w, &h, &maxval) != 3 || maxval != 255) goto end; img = gs_alloc(w, h); if (!gs_valid(img)) goto end; if (fread(img.data, sizeof(uint8_t), w * h, f) != (size_t)(w * h)) { gs_free(img); img = (struct gs_image){0, 0, NULL}; } end: fclose(f); return img; } GS_API int gs_write_pgm(struct gs_image img, const char *path) { if (!gs_valid(img)) return -1; FILE *f = (path[0] == '-' && !path[1]) ? stdout : fopen(path, "wb"); if (!f) return -1; fprintf(f, "P5\n%u %u\n255\n", img.w, img.h); size_t written = fwrite(img.data, sizeof(uint8_t), img.w * img.h, f); fclose(f); return (written == (size_t)(img.w * img.h)) ? 0 : -1; } #endif // GS_NO_STDLIB #define gs_for(img, x, y) \ for (unsigned y = 0; y < (img).h; y++) \ for (unsigned x = 0; x < (img).w; x++) GS_API uint8_t gs_get(struct gs_image img, unsigned x, unsigned y) { return (gs_valid(img) && x < img.w && y < img.h) ? img.data[y * img.w + x] : 0; } GS_API void gs_set(struct gs_image img, unsigned x, unsigned y, uint8_t value) { if (gs_valid(img) && x < img.w && y < img.h) img.data[y * img.w + x] = value; } // // Image processing // GS_API void gs_crop(struct gs_image dst, struct gs_image src, struct gs_rect roi) { gs_assert(gs_valid(dst) && gs_valid(src) && roi.x + roi.w <= src.w && roi.y + roi.h <= src.h && dst.w == roi.w && dst.h == roi.h); gs_for(roi, x, y) gs_set(dst, x, y, gs_get(src, roi.x + x, roi.y + y)); } GS_API void gs_copy(struct gs_image dst, struct gs_image src) { gs_crop(dst, src, (struct gs_rect){0, 0, src.w, src.h}); } GS_API void gs_resize_nn(struct gs_image dst, struct gs_image src) { gs_for(dst, x, y) { unsigned sx = x * src.w / dst.w, sy = y * src.h / dst.h; gs_set(dst, x, y, gs_get(src, sx, sy)); } } GS_API void gs_resize(struct gs_image dst, struct gs_image src) { gs_assert(gs_valid(dst) && gs_valid(src)); gs_for(dst, x, y) { float sx = ((float)x + 0.5f) * src.w / dst.w - 0.5f; // 0.5f centers the pixel float sy = ((float)y + 0.5f) * src.h / dst.h - 0.5f; sx = GS_MAX(0.0f, GS_MIN(sx, src.w - 1.0f)); sy = GS_MAX(0.0f, GS_MIN(sy, src.h - 1.0f)); unsigned sx_int = (unsigned)sx, sy_int = (unsigned)sy; unsigned sx1 = GS_MIN(sx_int + 1, src.w - 1), sy1 = GS_MIN(sy_int + 1, src.h - 1); float dx = sx - sx_int, dy = sy - sy_int; uint8_t c00 = gs_get(src, sx_int, sy_int), c01 = gs_get(src, sx1, sy_int), c10 = gs_get(src, sx_int, sy1), c11 = gs_get(src, sx1, sy1); uint8_t p = (c00 * (1 - dx) * (1 - dy)) + (c01 * dx * (1 - dy)) + (c10 * (1 - dx) * dy) + (c11 * dx * dy); gs_set(dst, x, y, p); } } GS_API void gs_downsample(struct gs_image dst, struct gs_image src) { gs_assert(gs_valid(src) && gs_valid(dst) && dst.w == src.w / 2 && dst.h == src.h / 2); gs_for(dst, x, y) { unsigned src_x = x * 2, src_y = y * 2; unsigned sum = gs_get(src, src_x, src_y) + gs_get(src, src_x + 1, src_y) + gs_get(src, src_x, src_y + 1) + gs_get(src, src_x + 1, src_y + 1); gs_set(dst, x, y, (uint8_t)(sum / 4)); } } GS_API void gs_histogram(struct gs_image img, unsigned hist[256]) { gs_assert(gs_valid(img) && hist != NULL); for (unsigned i = 0; i < 256; i++) hist[i] = 0; for (unsigned i = 0; i < img.w * img.h; i++) hist[img.data[i]]++; } GS_API uint8_t gs_otsu_threshold(struct gs_image img) { gs_assert(gs_valid(img)); unsigned hist[256] = {0}, wb = 0, wf = 0, threshold = 0; gs_histogram(img, hist); float sum = 0, sumB = 0, varMax = -1.0; for (unsigned i = 0; i < 256; i++) sum += (float)i * hist[i]; for (unsigned t = 0; t < 256; t++) { wb += hist[t]; if (wb == 0) continue; wf = img.w * img.h - wb; if (wf == 0) break; sumB += (float)t * hist[t]; float mB = (float)sumB / wb; float mF = (float)(sum - sumB) / wf; float varBetween = (float)wb * (float)wf * (mB - mF) * (mB - mF); if (varBetween > varMax) varMax = varBetween, threshold = t; } return (uint8_t)threshold; } GS_API void gs_threshold(struct gs_image img, uint8_t thresh) { gs_assert(gs_valid(img)); for (unsigned i = 0; i < img.w * img.h; i++) img.data[i] = (img.data[i] > thresh) ? 255 : 0; } GS_API void gs_adaptive_threshold(struct gs_image dst, struct gs_image src, unsigned radius, int c) { gs_assert(gs_valid(dst) && gs_valid(src) && dst.w == src.w && dst.h == src.h); gs_for(src, x, y) { unsigned sum = 0, count = 0; for (int dy = -radius; dy <= (int)radius; dy++) { for (int dx = -radius; dx <= (int)radius; dx++) { int sy = (int)y + dy, sx = (int)x + dx; if (sy >= 0 && sy < (int)src.h && sx >= 0 && sx < (int)src.w) { sum += gs_get(src, sx, sy); count++; } } } int threshold = sum / count - c; gs_set(dst, x, y, (gs_get(src, x, y) > threshold) ? 255 : 0); } } #define gs_sharpen ((struct gs_image){3, 3, (uint8_t[]){0, -1, 0, -1, 5, -1, 0, -1, 0}}) // norm 1 #define gs_emboss ((struct gs_image){3, 3, (uint8_t[]){-2, -1, 0, -1, 1, 1, 0, 1, 2}}) // norm 1 #define gs_blur_box ((struct gs_image){3, 3, (uint8_t[]){1, 1, 1, 1, 1, 1, 1, 1, 1}}) // norm 9 #define gs_blur_gaussian \ ((struct gs_image){3, 3, (uint8_t[]){1, 2, 1, 2, 4, 2, 1, 2, 1}}) // norm 16 GS_API void gs_filter(struct gs_image dst, struct gs_image src, struct gs_image kernel, unsigned norm) { gs_assert(gs_valid(src) && gs_valid(dst) && dst.w == src.w && dst.h == src.h && norm > 0); gs_for(dst, x, y) { int sum = 0; gs_for(kernel, i, j) { sum += gs_get(src, x + i - kernel.w / 2, y + j - kernel.h / 2) * (int8_t)gs_get(kernel, i, j); } sum = sum / norm; gs_set(dst, x, y, GS_MIN(255, GS_MAX(0, sum))); } } GS_API void gs_blur(struct gs_image dst, struct gs_image src, unsigned radius) { gs_assert(gs_valid(src) && gs_valid(dst) && dst.w == src.w && dst.h == src.h); gs_for(src, x, y) { unsigned sum = 0, count = 0; for (int dy = -radius; dy <= (int)radius; dy++) { for (int dx = -radius; dx <= (int)radius; dx++) { int sy = y + dy, sx = x + dx; if (sy >= 0 && sy < (int)src.h && sx >= 0 && sx < (int)src.w) { sum += gs_get(src, sx, sy); count++; } } } gs_set(dst, x, y, (uint8_t)(sum / count)); } } enum { GS_ERODE, GS_DILATE }; static inline void gs_morph(struct gs_image dst, struct gs_image src, int op) { gs_assert(gs_valid(dst) && gs_valid(src) && dst.w == src.w && dst.h == src.h); gs_for(src, x, y) { uint8_t val = op == GS_ERODE ? 255 : 0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { int sy = (int)y + dy, sx = (int)x + dx; if (sy >= 0 && sy < (int)src.h && sx >= 0 && sx < (int)src.w) { uint8_t pixel = gs_get(src, sx, sy); if (op == GS_DILATE && pixel > val) val = pixel; if (op == GS_ERODE && pixel < val) val = pixel; } } } gs_set(dst, x, y, val); } } GS_API void gs_erode(struct gs_image dst, struct gs_image src) { gs_morph(dst, src, GS_ERODE); } GS_API void gs_dilate(struct gs_image dst, struct gs_image src) { gs_morph(dst, src, GS_DILATE); } GS_API void gs_sobel(struct gs_image dst, struct gs_image src) { gs_assert(gs_valid(dst) && gs_valid(src) && dst.w == src.w && dst.h == src.h); for (unsigned y = 1; y < src.h - 1; y++) { for (unsigned x = 1; x < src.w - 1; x++) { int gx = -src.data[(y - 1) * src.w + (x - 1)] + src.data[(y - 1) * src.w + (x + 1)] - 2 * src.data[y * src.w + (x - 1)] + 2 * src.data[y * src.w + (x + 1)] - src.data[(y + 1) * src.w + (x - 1)] + src.data[(y + 1) * src.w + (x + 1)]; int gy = -src.data[(y - 1) * src.w + (x - 1)] - 2 * src.data[(y - 1) * src.w + x] - src.data[(y - 1) * src.w + (x + 1)] + src.data[(y + 1) * src.w + (x - 1)] + 2 * src.data[(y + 1) * src.w + x] + src.data[(y + 1) * src.w + (x + 1)]; int magnitude = ((gx < 0 ? -gx : gx) + (gy < 0 ? -gy : gy)) / 2; dst.data[y * dst.w + x] = (uint8_t)GS_MAX(0, GS_MIN(magnitude, 255)); } } } // // Connected components (blobs) // static inline gs_label gs_root(gs_label x, gs_label *parents) { while (parents[x] != x) x = parents[x] = parents[parents[x]]; return x; } GS_API unsigned gs_blobs(struct gs_image img, gs_label *labels, struct gs_blob *blobs, unsigned nblobs) { gs_assert(gs_valid(img) && labels != NULL && blobs != NULL && nblobs > 0); unsigned w = img.w; gs_label next = 1, parents[nblobs + 1]; unsigned cx[nblobs], cy[nblobs]; for (unsigned i = 0; i < img.w * img.h; i++) labels[i] = 0; for (unsigned i = 0; i < nblobs; i++) blobs[i] = (struct gs_blob){0, 0, {UINT_MAX, UINT_MAX, 0, 0}, {0, 0}}; for (unsigned i = 0; i <= nblobs; i++) parents[i] = i; // first pass: label and union gs_for(img, x, y) { if (gs_get(img, x, y) < 128) continue; // skip background pixels gs_label left = (x > 0) ? labels[y * w + (x - 1)] : 0; gs_label top = (y > 0) ? labels[(y - 1) * w + x] : 0; // 4-connectivity: pick smallest from left and top, if any is non-zero gs_label n = (left && top ? GS_MIN(left, top) : (left ? left : (top ? top : 0))); if (!n) { // new component if (next > nblobs) continue; // out of labels blobs[next - 1] = (struct gs_blob){next, 1, {x, y, x, y}, {x, y}}; cx[next - 1] = x, cy[next - 1] = y; labels[y * w + x] = next++; } else { // existing component labels[y * w + x] = n; struct gs_blob *b = &blobs[n - 1]; cx[n - 1] += x, cy[n - 1] += y; b->area++; b->box.x = GS_MIN(x, b->box.x), b->box.y = GS_MIN(y, b->box.y); // keep bottom-right point coordinates in w/h of the rect, adjust later b->box.w = GS_MAX(x, b->box.w), b->box.h = GS_MAX(y, b->box.h); // union if labels are different if (left && top && left != top) { gs_label root1 = gs_root(left, parents), root2 = gs_root(top, parents); if (root1 != root2) parents[GS_MAX(root1, root2)] = GS_MIN(root1, root2); } } } // merge blobs for (int i = 0; i < next - 1; i++) { gs_label root = gs_root(blobs[i].label, parents); if (root != blobs[i].label) { struct gs_blob *broot = &blobs[root - 1]; broot->area += blobs[i].area; broot->box.x = GS_MIN(broot->box.x, blobs[i].box.x); broot->box.y = GS_MIN(broot->box.y, blobs[i].box.y); broot->box.w = GS_MAX(broot->box.w, blobs[i].box.w); broot->box.h = GS_MAX(broot->box.h, blobs[i].box.h); cx[root - 1] += cx[i], cy[root - 1] += cy[i]; blobs[i].area = 0; } } // second pass: update labels gs_for(img, x, y) { gs_label l = labels[y * w + x]; if (l) labels[y * w + x] = gs_root(l, parents); } // compact blobs unsigned m = 0; for (int i = 0; i < next - 1; i++) { if (blobs[i].area == 0) continue; // fix rect width/height from bottom-right point to actual width/height blobs[i].box.w = blobs[i].box.w - blobs[i].box.x + 1; blobs[i].box.h = blobs[i].box.h - blobs[i].box.y + 1; // calculate centroids blobs[i].centroid.x = cx[i] / blobs[i].area; blobs[i].centroid.y = cy[i] / blobs[i].area; // move to compacted position blobs[m++] = blobs[i]; } return m; // number of non-empty blobs } GS_API void gs_blob_corners(struct gs_image img, gs_label *labels, struct gs_blob *b, struct gs_point c[4]) { gs_assert(gs_valid(img) && b && labels); struct gs_point tl = b->centroid, tr = b->centroid, br = b->centroid, bl = b->centroid; int min_sum = INT_MAX, max_sum = INT_MIN, min_diff = INT_MAX, max_diff = INT_MIN; for (unsigned y = b->box.y; y < b->box.y + b->box.h; y++) { for (unsigned x = b->box.x; x < b->box.x + b->box.w; x++) { if (gs_get(img, x, y) < 128) continue; // skip background pixels if (labels[y * img.w + x] != b->label) continue; int sum = (int)x + (int)y, diff = (int)x - (int)y; if (sum < min_sum) min_sum = sum, tl = (struct gs_point){x, y}; if (sum > max_sum) max_sum = sum, br = (struct gs_point){x, y}; if (diff < min_diff) min_diff = diff, bl = (struct gs_point){x, y}; if (diff > max_diff) max_diff = diff, tr = (struct gs_point){x, y}; } } c[0] = tl, c[1] = tr, c[2] = br, c[3] = bl; } GS_API void gs_perspective_correct(struct gs_image dst, struct gs_image src, struct gs_point c[4]) { gs_assert(gs_valid(dst) && gs_valid(src)); float w = dst.w - 1.0f, h = dst.h - 1.0f; gs_for(dst, x, y) { float u = x / w, v = y / h; float top_x = c[0].x * (1 - u) + c[1].x * u; float top_y = c[0].y * (1 - u) + c[1].y * u; float bot_x = c[3].x * (1 - u) + c[2].x * u; float bot_y = c[3].y * (1 - u) + c[2].y * u; float src_x = top_x * (1 - v) + bot_x * v; float src_y = top_y * (1 - v) + bot_y * v; src_x = GS_MAX(0.0f, GS_MIN(src_x, src.w - 1.0f)); src_y = GS_MAX(0.0f, GS_MIN(src_y, src.h - 1.0f)); unsigned sx = (unsigned)src_x, sy = (unsigned)src_y; unsigned sx1 = GS_MIN(sx + 1, src.w - 1), sy1 = GS_MIN(sy + 1, src.h - 1); float dx = src_x - sx, dy = src_y - sy; uint8_t c00 = gs_get(src, sx, sy), c01 = gs_get(src, sx1, sy), c10 = gs_get(src, sx, sy1), c11 = gs_get(src, sx1, sy1); dst.data[y * dst.w + x] = (uint8_t)((c00 * (1 - dx) * (1 - dy)) + (c01 * dx * (1 - dy)) + (c10 * (1 - dx) * dy) + (c11 * dx * dy)); } } GS_API void gs_trace_contour(struct gs_image img, struct gs_image visited, struct gs_contour *c) { gs_assert(gs_valid(img) && gs_valid(visited) && img.w == visited.w && img.h == visited.h); static const int dx[] = {1, 1, 0, -1, -1, -1, 0, 1}; static const int dy[] = {0, 1, 1, 1, 0, -1, -1, -1}; c->length = 0; c->box = (struct gs_rect){c->start.x, c->start.y, 1, 1}; struct gs_point p = c->start; unsigned dir = 7, seenstart = 0; for (;;) { if (!gs_get(visited, p.x, p.y)) c->length++; gs_set(visited, p.x, p.y, 255); int ndir = (dir + 1) % 8, found = 0; for (int i = 0; i < 8; i++) { int d = (ndir + i) % 8, nx = p.x + dx[d], ny = p.y + dy[d]; if (nx >= 0 && nx < (int)img.w && ny >= 0 && ny < (int)img.h && gs_get(img, nx, ny) > 128) { p = (struct gs_point){(unsigned)nx, (unsigned)ny}; dir = (d + 6) % 8; found = 1; break; } } if (!found) break; // open contour c->box.x = GS_MIN(c->box.x, p.x); c->box.y = GS_MIN(c->box.y, p.y); c->box.w = GS_MAX(c->box.w, p.x - c->box.x + 1); c->box.h = GS_MAX(c->box.h, p.y - c->box.y + 1); if (p.x == c->start.x && p.y == c->start.y) { if (seenstart) break; // stop: second time at the starting point seenstart = 1; } } } GS_API unsigned gs_fast(struct gs_image img, struct gs_image scoremap, struct gs_keypoint *kps, unsigned nkps, unsigned threshold) { gs_assert(gs_valid(img) && kps && nkps > 0); static const int dx[16] = {0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2, -3, -3, -3, -2, -1}; static const int dy[16] = {-3, -3, -2, -1, 0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2, -3}; unsigned n = 0; // first pass: compute score map for (unsigned y = 3; y < img.h - 3; y++) { for (unsigned x = 3; x < img.w - 3; x++) { uint8_t p = gs_get(img, x, y); int run = 0, score = 0; for (int i = 0; i < 16 + 9; i++) { int idx = (i % 16); uint8_t v = gs_get(img, x + dx[idx], y + dy[idx]); if (v > p + threshold) { run = (run > 0) ? run + 1 : 1; } else if (v < p - threshold) { run = (run < 0) ? run - 1 : -1; } else { run = 0; } if (run >= 9 || run <= -9) { score = 255; for (int j = 0; j < 16; j++) { int d = gs_get(img, x + dx[j], y + dy[j]) - p; if (d < 0) d = -d; if (d < score) score = d; } break; } } gs_set(scoremap, x, y, score); } } // second pass: non-maximum suppression for (unsigned y = 3; y < img.h - 3; y++) { for (unsigned x = 3; x < img.w - 3; x++) { int s = gs_get(scoremap, x, y), is_max = 1; if (s == 0) continue; for (int yy = -1; yy <= 1 && is_max; yy++) { for (int xx = -1; xx <= 1; xx++) { if (xx == 0 && yy == 0) continue; if (gs_get(scoremap, x + xx, y + yy) > s) { is_max = 0; break; } } } if (is_max && n < nkps) kps[n++] = (struct gs_keypoint){{x, y}, (unsigned)s, 0, {0}}; } } return n; } // // ORB (Oriented FAST and Rotated BRIEF) // // clang-format: off static const int gs_brief_pattern[256][4] = { {1, 0, 1, 3}, {0, 0, 3, 2}, {-1, 1, -1, -1}, {0, -4, -3, -1}, {-2, 1, -2, -3}, {3, 0, 0, -3}, {-1, 0, -2, 1}, {-1, -1, -1, 4}, {0, -2, 2, -2}, {0, -4, -3, 0}, {1, 0, 0, -1}, {-3, -1, -1, 2}, {1, -4, 1, -1}, {-1, 1, 2, 2}, {-2, -1, 1, 2}, {-1, 0, -2, -2}, {2, 3, 0, 2}, {1, -1, 1, 3}, {0, 3, -5, 2}, {0, -1, 0, -4}, {0, 1, 3, -1}, {-2, -1, 2, 1}, {-1, 1, 0, 2}, {-1, -1, -1, -3}, {1, 1, 0, 0}, {-3, -1, -1, -2}, {0, 1, 4, 0}, {1, 0, -4, 0}, {0, 5, 0, 1}, {0, -2, 2, 2}, {2, -2, 3, -3}, {1, 4, -2, -1}, {0, -1, -3, 0}, {-2, 1, -2, 3}, {-2, -1, 2, -2}, {0, 3, -3, 0}, {1, 2, -2, -3}, {1, 1, 1, 1}, {-1, 0, 1, -1}, {4, 1, -2, 1}, {-2, 2, 2, -2}, {2, 1, 2, 4}, {0, -2, -2, -2}, {0, 1, 1, 2}, {0, 3, -1, 5}, {1, -2, -2, 1}, {0, 1, 1, 0}, {-2, -3, -1, 2}, {0, -2, 0, 1}, {-2, 0, 0, -2}, {1, 1, 2, 2}, {-3, -2, 1, 1}, {1, 8, 1, 2}, {2, 1, -1, 2}, {-2, 0, -1, 0}, {5, -4, 1, -3}, {-1, 2, 0, -2}, {-1, 1, -1, 0}, {0, -1, 4, 1}, {-4, 0, -1, 2}, {-2, 0, 1, 2}, {-2, -1, -1, -1}, {4, 1, -3, 2}, {4, 2, -3, -1}, {3, -1, 1, 2}, {-2, 0, -6, -2}, {-1, -2, 3, -3}, {-1, 0, 3, -3}, {2, 0, -2, 1}, {0, -1, 0, -1}, {0, 1, 3, -2}, {4, -4, 0, 1}, {1, -1, 0, -1}, {-1, 2, 1, -1}, {2, 1, 2, 1}, {-2, -1, 1, 1}, {0, 0, 3, -1}, {1, 0, 0, 2}, {2, 2, 3, 0}, {1, -1, 1, 0}, {0, 1, -2, 4}, {-2, -2, 2, 2}, {1, 1, 0, -2}, {0, -1, 2, 0}, {-2, -1, 1, -1}, {-2, 0, 0, -1}, {-1, 0, -3, -3}, {-1, 0, 1, 3}, {2, 0, 0, -2}, {0, -1, 1, -2}, {1, 3, 0, 1}, {1, -1, 0, 0}, {0, -2, 0, 1}, {3, 2, 4, -2}, {2, 0, 4, -2}, {-2, -1, -4, -1}, {-2, 0, 1, 4}, {2, -1, -2, 1}, {-3, 4, 2, -1}, {-3, 3, 0, 2}, {-3, -1, 0, 0}, {-1, 1, -2, 0}, {0, 1, 1, -2}, {-3, 3, 1, -1}, {3, 0, 2, 0}, {4, 4, 0, 2}, {1, 3, -2, 1}, {2, -4, -2, -4}, {-1, 1, 3, 0}, {3, -3, -3, 0}, {1, 0, -4, 0}, {-3, 1, 1, -2}, {-1, -2, 0, 2}, {-2, 1, -1, -2}, {0, -2, -1, -2}, {4, 0, -1, 0}, {0, 0, 1, 2}, {-1, -1, -1, -5}, {-3, 3, 3, 0}, {1, 1, 6, 2}, {0, -2, -3, 0}, {-2, -3, -1, -2}, {3, 2, 0, 3}, {0, -2, 3, 1}, {-2, 0, -2, -3}, {2, 4, -3, 1}, {-1, -1, -1, -2}, {0, -2, 1, 0}, {15, -10, -14, 4}, {12, -5, -12, -1}, {-10, 6, 1, 14}, {8, -10, 3, 14}, {9, -14, -1, -5}, {-8, 10, 3, -3}, {-4, -11, -10, 10}, {6, -12, 3, 4}, {-15, 4, 1, -4}, {-1, -15, 10, -2}, {-10, -11, 14, -5}, {15, -12, -3, -5}, {-13, -15, -10, 2}, {8, -6, -11, 7}, {-6, -4, -14, -3}, {-8, -14, 4, -15}, {15, -11, -7, 1}, {-7, -5, -1, 8}, {-10, 7, -13, 14}, {15, 1, -11, 14}, {12, -4, 2, -2}, {5, 8, -5, -7}, {-14, -4, -13, -13}, {-15, -8, 6, 12}, {13, -8, -5, -7}, {-11, -2, 12, 14}, {-13, 5, -11, -11}, {3, 11, -2, 10}, {14, -12, 9, -3}, {-6, 9, 2, -8}, {-8, -9, -8, -2}, {3, 13, -10, -15}, {7, 15, -1, -15}, {9, 1, -15, -1}, {7, -14, -2, 5}, {-8, -8, 3, -9}, {3, -10, -10, -13}, {-9, 3, -8, -6}, {4, -1, -1, 13}, {-15, 4, 14, -9}, {11, -12, 13, -10}, {9, -15, 13, -11}, {11, 7, -15, 14}, {-12, 6, -14, -6}, {-11, 11, -6, -15}, {6, -10, -3, 15}, {-1, -12, -3, 8}, {4, 8, -1, 13}, {-8, -11, 13, -1}, {-12, -4, -3, -14}, {11, 15, 3, 3}, {-12, -12, 10, -5}, {11, -11, 4, -5}, {14, -6, -8, -10}, {-10, -8, 7, -1}, {10, -2, -5, -4}, {10, -3, -8, 14}, {2, 9, -15, -1}, {-8, 12, -5, -4}, {-4, -12, 0, -12}, {-11, 8, -11, -8}, {15, -6, 1, 12}, {15, 10, -7, 6}, {3, 13, -2, -8}, {11, -7, 0, 3}, {1, 3, -6, 11}, {1, 5, -7, 7}, {3, 11, -10, -7}, {-2, 1, 12, -6}, {-7, 1, -12, -7}, {1, -1, -4, -2}, {3, 1, 1, -5}, {1, 5, -4, 0}, {-14, 4, 6, -7}, {3, 8, -2, 5}, {-6, 3, -7, 10}, {-5, -5, 3, -5}, {-3, 9, -11, -2}, {-8, 1, 1, -8}, {-1, 2, 0, -2}, {4, -3, 3, -8}, {8, -12, -11, 7}, {0, 9, -4, 0}, {-5, 8, 7, -6}, {-2, -9, 12, -1}, {3, -9, 14, -5}, {-2, 2, 5, 3}, {-1, -10, 9, 9}, {-8, -10, 9, -6}, {-5, 8, -8, 10}, {1, -1, 1, -6}, {4, -5, 4, -1}, {9, 8, 9, -1}, {3, 7, -8, -1}, {-4, -11, 1, 7}, {-9, 5, 2, -2}, {-4, -10, -12, -2}, {-12, 0, -2, 1}, {-1, -8, 2, 2}, {0, 5, 0, 11}, {-10, 0, 5, -8}, {1, -7, -4, 5}, {6, 13, 0, -2}, {1, -2, 6, -4}, {-9, -7, -11, 9}, {9, 11, -1, 8}, {4, 7, 7, -11}, {8, 12, -10, 2}, {-3, 5, -2, -7}, {-9, 2, 2, 1}, {1, 0, 1, 1}, {2, -5, 4, -14}, {-11, -1, 2, -1}, {-7, -9, -2, -11}, {10, -1, -8, -11}, {10, 3, 10, 3}, {9, 0, -9, 1}, {4, 4, 4, 11}, {-2, 1, 0, -12}, {-2, 0, -5, -7}, {-7, 8, -9, 1}, {-13, -3, -6, 4}, {3, -9, -4, -7}, {-11, -1, 5, -5}, {-7, 2, 15, 0}, {-3, 2, 13, 6}, {1, 0, 2, 1}, {-7, -4, -4, 3}}; // clang-format: on GS_API float gs_compute_orientation(struct gs_image img, unsigned x, unsigned y, unsigned r) { gs_assert(gs_valid(img) && x >= r && y >= r && x < img.w - r && y < img.h - r); float m01 = 0, m10 = 0; for (int dy = -(int)r; dy <= (int)r; dy++) { for (int dx = -(int)r; dx <= (int)r; dx++) { if (dx * dx + dy * dy <= (int)(r * r)) { uint8_t intensity = gs_get(img, x + dx, y + dy); m01 += dy * intensity; m10 += dx * intensity; } } } return gs_atan2(m01, m10); } GS_API void gs_brief_descriptor(struct gs_image img, struct gs_keypoint *kp) { gs_assert(gs_valid(img) && kp); int x = kp->pt.x, y = kp->pt.y; float angle = kp->angle, sin_a = gs_sin(angle), cos_a = gs_sin((float)(angle + 1.57079f)); for (int i = 0; i < 8; i++) kp->descriptor[i] = 0; for (int i = 0; i < 256; i++) { float dx1 = gs_brief_pattern[i][0] * cos_a - gs_brief_pattern[i][1] * sin_a; float dy1 = gs_brief_pattern[i][0] * sin_a + gs_brief_pattern[i][1] * cos_a; float dx2 = gs_brief_pattern[i][2] * cos_a - gs_brief_pattern[i][3] * sin_a; float dy2 = gs_brief_pattern[i][2] * sin_a + gs_brief_pattern[i][3] * cos_a; int x1 = x + (int)dx1, y1 = y + (int)dy1, x2 = x + (int)dx2, y2 = y + (int)dy2; uint8_t intensity1 = gs_get(img, x1, y1), intensity2 = gs_get(img, x2, y2); if (intensity1 > intensity2) kp->descriptor[i / 32] |= (1U << (i % 32)); } } static void gs_sort_keypoints(struct gs_keypoint *kps, unsigned n) { for (unsigned i = 0; i < n - 1; i++) { for (unsigned j = 0; j < n - 1 - i; j++) { if (kps[j].response < kps[j + 1].response) { struct gs_keypoint temp = kps[j]; kps[j] = kps[j + 1]; kps[j + 1] = temp; } } } } GS_API unsigned gs_orb_extract(struct gs_image img, struct gs_keypoint *kps, unsigned nkps, unsigned threshold, uint8_t *scoremap_buffer) { gs_assert(gs_valid(img) && kps && nkps > 0 && scoremap_buffer); struct gs_image scoremap = {img.w, img.h, scoremap_buffer}; static struct gs_keypoint candidates[5000]; unsigned n_fast = gs_fast(img, scoremap, candidates, GS_MIN(nkps * 4, 5000), threshold); if (n_fast > 1) gs_sort_keypoints(candidates, n_fast); unsigned n_orb = 0, radius = 15; for (unsigned i = 0; i < n_fast && n_orb < nkps; i++) { unsigned x = candidates[i].pt.x, y = candidates[i].pt.y; if (x >= radius && y >= radius && x < img.w - radius && y < img.h - radius) { kps[n_orb] = candidates[i]; kps[n_orb].angle = gs_compute_orientation(img, x, y, radius); gs_brief_descriptor(img, &kps[n_orb]); n_orb++; } } return n_orb; } static inline unsigned gs_hamming_distance(const uint32_t desc1[8], const uint32_t desc2[8]) { unsigned dist = 0; for (int i = 0; i < 8; i++) { uint32_t eor = desc1[i] ^ desc2[i]; while (eor) dist += eor & 1, eor >>= 1; } return dist; } GS_API unsigned gs_match_orb(const struct gs_keypoint *kps1, unsigned n1, const struct gs_keypoint *kps2, unsigned n2, struct gs_match *matches, unsigned max_matches, float max_distance) { gs_assert(kps1 && kps2 && matches); unsigned n = 0; for (unsigned i = 0; i < n1 && n < max_matches; i++) { float best_dist = max_distance + 1, second_best = max_distance + 1; unsigned best_idx = 0; for (unsigned j = 0; j < n2; j++) { float d = gs_hamming_distance(kps1[i].descriptor, kps2[j].descriptor); if (d < best_dist) second_best = best_dist, best_dist = d, best_idx = j; else if (d < second_best) second_best = d; } if (best_dist <= max_distance && best_dist < 0.8f * second_best) matches[n++] = (struct gs_match){i, best_idx, (unsigned)best_dist}; } return n; } // // Template matching // GS_API void gs_match_template(struct gs_image img, struct gs_image tmpl, struct gs_image result) { gs_assert(gs_valid(img) && gs_valid(tmpl) && gs_valid(result)); gs_assert(img.w >= tmpl.w && img.h >= tmpl.h); gs_assert(result.w == img.w - tmpl.w + 1 && result.h == img.h - tmpl.h + 1); gs_for(result, rx, ry) { unsigned long long sum = 0; for (unsigned ty = 0; ty < tmpl.h; ty++) { for (unsigned tx = 0; tx < tmpl.w; tx++) { int diff = (int)gs_get(img, rx + tx, ry + ty) - (int)gs_get(tmpl, tx, ty); sum += (unsigned long long)(diff * diff); } } // Normalize to 0-255: lower values = better match unsigned long long max_diff = (unsigned long long)tmpl.w * tmpl.h * 255ULL * 255ULL; unsigned score = (unsigned)(sum * 255ULL / max_diff); gs_set(result, rx, ry, (uint8_t)(255 - GS_MIN(score, 255))); } } GS_API struct gs_point gs_find_best_match(struct gs_image result) { gs_assert(gs_valid(result)); struct gs_point best = {0, 0}; uint8_t best_score = 0; gs_for(result, x, y) { uint8_t score = gs_get(result, x, y); if (score > best_score) { best_score = score; best.x = x; best.y = y; } } return best; } // // Integral image // GS_API void gs_integral(struct gs_image src, unsigned *ii) { gs_assert(gs_valid(src) && ii); unsigned row = 0; gs_for(src, x, y) { if (x == 0) row = 0; row += gs_get(src, x, y); ii[y * src.w + x] = row + (y ? ii[(y - 1) * src.w + x] : 0); } } static inline uint32_t gs_integral_sum(const unsigned *ii, unsigned iw, unsigned x, unsigned y, unsigned w, unsigned h) { gs_assert(ii && iw > 0 && x + w <= iw); unsigned x2 = x + w - 1, y2 = y + h - 1; unsigned A = (x > 0 && y > 0) ? ii[(y - 1) * iw + (x - 1)] : 0; unsigned B = (y > 0) ? ii[(y - 1) * iw + x2] : 0; unsigned C = (x > 0) ? ii[y2 * iw + (x - 1)] : 0; unsigned D = ii[y2 * iw + x2]; return D + A - B - C; } // // LBP cascade detection // static inline int gs_lbp_code(const unsigned *ii, unsigned iw, int x, int y, int fx, int fy, int fw, int fh) { /* 3x3 LBP grid: TL TC TR / L C R / BL BC BR */ unsigned tl = gs_integral_sum(ii, iw, x + fx, y + fy, fw, fh); unsigned tc = gs_integral_sum(ii, iw, x + fx + fw, y + fy, fw, fh); unsigned tr = gs_integral_sum(ii, iw, x + fx + 2 * fw, y + fy, fw, fh); unsigned l = gs_integral_sum(ii, iw, x + fx, y + fy + fh, fw, fh); unsigned c = gs_integral_sum(ii, iw, x + fx + fw, y + fy + fh, fw, fh); unsigned r = gs_integral_sum(ii, iw, x + fx + 2 * fw, y + fy + fh, fw, fh); unsigned bl = gs_integral_sum(ii, iw, x + fx, y + fy + 2 * fh, fw, fh); unsigned bc = gs_integral_sum(ii, iw, x + fx + fw, y + fy + 2 * fh, fw, fh); unsigned br = gs_integral_sum(ii, iw, x + fx + 2 * fw, y + fy + 2 * fh, fw, fh); return ((tl >= c) << 7) | ((tc >= c) << 6) | ((tr >= c) << 5) | ((r >= c) << 4) | ((br >= c) << 3) | ((bc >= c) << 2) | ((bl >= c) << 1) | ((l >= c) << 0); } static inline int gs_lbp_match(int code, const int32_t *subsets, int n) { int idx = code / 32, bit = code % 32; return (idx < n) && (subsets[idx] & (1 << bit)); } GS_API unsigned gs_lbp_window(const struct gs_lbp_cascade *c, const unsigned *ii, unsigned iw, unsigned ih, int x, int y, float scale) { int win_w = (int)(c->window_w * scale), win_h = (int)(c->window_h * scale); if (x + win_w > (int)iw || y + win_h > (int)ih) return 0; for (int si = 0; si < c->nstages; si++) { int start = c->stage_weak_start[si], n = c->stage_nweaks[si]; float sum = 0.0f; for (int i = 0; i < n; i++) { int wi = start + i, fi = c->weak_feature_idx[wi]; int fx = (int)(c->features[fi * 4 + 0] * scale); int fy = (int)(c->features[fi * 4 + 1] * scale); int fw = (int)(c->features[fi * 4 + 2] * scale); int fh = (int)(c->features[fi * 4 + 3] * scale); if (fw < 1) fw = 1; if (fh < 1) fh = 1; int code = gs_lbp_code(ii, iw, x, y, fx, fy, fw, fh); int match = gs_lbp_match(code, &c->subsets[c->weak_subset_offset[wi]], c->weak_num_subsets[wi]); sum += match ? c->weak_left_val[wi] : c->weak_right_val[wi]; } if (sum < c->stage_threshold[si]) return 0; } return 1; } GS_API unsigned gs_lbp_detect(const struct gs_lbp_cascade *c, const unsigned *ii, unsigned iw, unsigned ih, struct gs_rect *rects, unsigned max_rects, float scale_factor, float min_scale, float max_scale, int step) { unsigned n = 0; for (float scale = min_scale; scale <= max_scale && n < max_rects; scale *= scale_factor) { int win_w = (int)(c->window_w * scale), win_h = (int)(c->window_h * scale); if (win_w > (int)iw || win_h > (int)ih) break; for (int y = 0; y + win_h <= (int)ih && n < max_rects; y += step) { for (int x = 0; x + win_w <= (int)iw && n < max_rects; x += step) { if (gs_lbp_window(c, ii, iw, ih, x, y, scale)) { rects[n].x = x; rects[n].y = y; rects[n].w = win_w; rects[n].h = win_h; n++; } } } } return n; } #endif // GRAYSKULL_H
zserge/grayskull
680
A tiny, dependency-free computer vision library in C for embedded systems, drones, and robotics.
C
zserge
Serge Zaitsev
test.c
C
#include <assert.h> #include "grayskull.h" static void test_crop(void) { uint8_t data[4 * 4] = { 0, 0, 0, 0, // 0, 1, 0, 0, // 0, 1, 1, 0, // 0, 0, 0, 0 // }; struct gs_image img = {4, 4, data}; struct gs_rect rect = {1, 1, 3, 2}; uint8_t cropped_data[3 * 2]; struct gs_image cropped = {3, 2, cropped_data}; gs_crop(cropped, img, rect); uint8_t expected[3 * 2] = { 1, 0, 0, // 1, 1, 0 // }; gs_for(cropped, x, y) assert(cropped.data[y * cropped.w + x] == expected[y * cropped.w + x]); } static void test_resize(void) { // Downscale: 4x4 -> 2x2 uint8_t data_4x4[4 * 4] = { 0, 50, 100, 150, // 25, 75, 125, 175, // 50, 100, 150, 200, // 75, 125, 175, 225 // }; struct gs_image img_4x4 = {4, 4, data_4x4}; uint8_t data_2x2[2 * 2]; struct gs_image resized_2x2 = {2, 2, data_2x2}; gs_resize(resized_2x2, img_4x4); uint8_t expected_2x2[2 * 2] = { 37, 137, // (0+50+25+75)/4=37.5, (100+150+125+175)/4=137.5 87, 187 // (50+100+75+125)/4=62.5, (150+200+175+225)/4=162.5 }; gs_for(resized_2x2, x, y) { assert(resized_2x2.data[y * resized_2x2.w + x] == expected_2x2[y * resized_2x2.w + x]); } // Upscale: 2x2 -> 4x4 struct gs_image img_2x2 = {2, 2, expected_2x2}; uint8_t data_upscaled[4 * 4]; struct gs_image upscaled_4x4 = {4, 4, data_upscaled}; gs_resize(upscaled_4x4, img_2x2); uint8_t expected_4x4[4 * 4] = { 37, 62, 112, 137, // 49, 74, 124, 149, // 74, 99, 149, 174, // 87, 112, 162, 187 // }; gs_for(upscaled_4x4, x, y) { assert(upscaled_4x4.data[y * upscaled_4x4.w + x] == expected_4x4[y * upscaled_4x4.w + x]); } // Same size resize uint8_t data_same[2 * 2] = {10, 20, 30, 40}; struct gs_image img_same = {2, 2, data_same}; uint8_t data_same_result[2 * 2]; struct gs_image same_result = {2, 2, data_same_result}; gs_resize(same_result, img_same); gs_for(same_result, x, y) { assert(same_result.data[y * same_result.w + x] == data_same[y * img_same.w + x]); } } #define W 255 // use one-letter define to align with "0" for black static void test_blur(void) { uint8_t data[3 * 3] = { 0, 0, 0, // 0, W, 0, // 0, 0, 0 // }; struct gs_image src = {3, 3, data}; uint8_t blurred_data[3 * 3]; struct gs_image dst = {3, 3, blurred_data}; gs_blur(dst, src, 1); uint8_t center = dst.data[1 * 3 + 1]; assert(center == 28); // (0+0+0+0+2555+0+0+0+0)/9 = 28.33 uint8_t corner = dst.data[0 * 3 + 0]; assert(corner == 63); // (0+0+0+255)/4 } static void test_morph(void) { uint8_t data_erode[5 * 5] = { 0, 0, 0, 0, 0, // 0, W, W, W, 0, // 0, W, W, W, 0, // 0, W, W, W, 0, // 0, 0, 0, 0, 0 // }; struct gs_image src_erode = {5, 5, data_erode}; uint8_t eroded_data[5 * 5]; struct gs_image dst_erode = {5, 5, eroded_data}; gs_erode(dst_erode, src_erode); assert(dst_erode.data[2 * 5 + 2] == 255); // center pixel should remain white assert(dst_erode.data[1 * 5 + 1] == 0); // edge pixel should become black uint8_t data_dilate[5 * 5] = { 0, 0, 0, 0, 0, // 0, 0, 0, 0, 0, // 0, 0, W, 0, 0, // 0, 0, 0, 0, 0, // 0, 0, 0, 0, 0 // }; struct gs_image src_dilate = {5, 5, data_dilate}; uint8_t dilated_data[5 * 5]; struct gs_image dst_dilate = {5, 5, dilated_data}; gs_dilate(dst_dilate, src_dilate); // center pixel should remain white, as well as top/bottom/left/right assert(dst_dilate.data[2 * 5 + 2] == 255); assert(dst_dilate.data[1 * 5 + 2] == 255 && dst_dilate.data[3 * 5 + 2] == 255 && dst_dilate.data[2 * 5 + 1] == 255 && dst_dilate.data[2 * 5 + 3] == 255); assert(dst_dilate.data[0 * 5 + 0] == 0); // corner pixel should remain black } static void test_sobel(void) { uint8_t data[5 * 5] = { 0, 0, W, W, W, // vertical edge 0, 0, W, W, W, // 0, 0, W, W, W, // 0, 0, W, W, W, // 0, 0, W, W, W // }; struct gs_image src = {5, 5, data}; uint8_t sobel_data[5 * 5] = {0}; struct gs_image dst = {5, 5, sobel_data}; gs_sobel(dst, src); assert(dst.data[2 * 5 + 2] > 100 && dst.data[3 * 5 + 2] > 100); // edge at column 2 assert(dst.data[2 * 5 + 0] == 0); // away from edge should be 0 uint8_t data_horizontal[5 * 5] = { 0, 0, 0, 0, 0, // horizontal edge 0, 0, 0, 0, 0, // W, W, W, W, W, // W, W, W, W, W, // W, W, W, W, W // }; struct gs_image src_h = {5, 5, data_horizontal}; uint8_t sobel_data_h[5 * 5] = {0}; struct gs_image dst_h = {5, 5, sobel_data_h}; gs_sobel(dst_h, src_h); assert(dst_h.data[2 * 5 + 2] > 100 && dst_h.data[2 * 5 + 3] > 100); // edge at row 2 assert(dst_h.data[0 * 5 + 2] == 0); // away from edge should be 0 } static void test_histogram(void) { uint8_t data[3 * 3] = { 0, 50, 100, // 50, 100, 150, // 100, 150, 200 // }; struct gs_image img = {3, 3, data}; unsigned hist[256]; gs_histogram(img, hist); assert(hist[0] == 1 && hist[50] == 2 && hist[100] == 3 && hist[150] == 2 && hist[200] == 1); unsigned total = 0; for (int i = 0; i < 256; i++) total += hist[i]; assert(total == 9); } static void test_threshold(void) { uint8_t data[2 * 2] = { 50, 150, // 75, 200 // }; struct gs_image img = {2, 2, data}; gs_threshold(img, 100); assert(data[0] == 0 && data[1] == 255 && data[2] == 0 && data[3] == 255); } static void test_otsu(void) { uint8_t data[3 * 3] = { 40, 50, 60, // dark cluster 45, 55, 50, // dark cluster 190, 200, 210 // bright cluster }; struct gs_image img = {3, 3, data}; uint8_t otsu_thresh = gs_otsu_threshold(img); assert(otsu_thresh == 60); // anything above 60 = white, below = black uint8_t uniform_data[4] = {0, 85, 170, 255}; struct gs_image uniform_img = {2, 2, uniform_data}; uint8_t uniform_thresh = gs_otsu_threshold(uniform_img); assert(uniform_thresh == 85); // above 85 = white, below = black uint8_t same_data[4] = {128, 128, 128, 128}; struct gs_image same_img = {2, 2, same_data}; uint8_t same_thresh = gs_otsu_threshold(same_img); assert(same_thresh == 0); // no variation, should return 0 } static void test_adaptive_threshold(void) { uint8_t data[5 * 5] = { 50, 50, 200, 50, 50, // 50, 50, 200, 50, 50, // 50, 50, 200, 50, 50, // 200, 200, 100, 200, 200, // 200, 200, 100, 200, 200 // }; uint8_t threshold[5 * 5] = { 0, 0, W, 0, 0, // 0, 0, W, 0, 0, // 0, 0, W, 0, 0, // W, W, 0, W, W, // 0, W, 0, W, 0 // }; uint8_t threshold_5[5 * 5] = { W, 0, W, 0, W, // W, 0, W, 0, W, // 0, 0, W, 0, 0, // W, W, 0, W, W, // W, W, 0, W, W // }; struct gs_image src = {5, 5, data}; uint8_t adaptive_data[5 * 5]; struct gs_image dst = {5, 5, adaptive_data}; gs_adaptive_threshold(dst, src, 1, 0); for (unsigned i = 0; i < 25; i++) assert(dst.data[i] == threshold[i]); gs_adaptive_threshold(dst, src, 1, 5); for (unsigned i = 0; i < 25; i++) assert(dst.data[i] == threshold_5[i]); } static void test_blobs(void) { uint8_t data[6 * 5] = { W, W, 0, 0, W, 0, // W, 0, 0, W, W, 0, // 0, 0, W, W, 0, 0, // W, W, W, 0, 0, W, // 0, W, 0, 0, 0, W // }; struct gs_image img = {6, 5, data}; gs_label labels[6 * 5] = {0}; struct gs_blob blobs[10] = {0}; unsigned n = gs_blobs(img, labels, blobs, 10); assert(n == 3); struct gs_blob expected[] = { {1, 3, {0, 0, 2, 2}, {0, 0}}, // {2, 9, {0, 0, 5, 5}, {2, 2}}, // {6, 2, {5, 3, 1, 2}, {5, 3}} // }; (void)expected; for (unsigned i = 0; i < n; i++) { assert(blobs[i].label == expected[i].label); assert(blobs[i].area == expected[i].area); assert(blobs[i].box.x == expected[i].box.x && blobs[i].box.y == expected[i].box.y); assert(blobs[i].box.w == expected[i].box.w && blobs[i].box.h == expected[i].box.h); assert(blobs[i].centroid.x == expected[i].centroid.x && blobs[i].centroid.y == expected[i].centroid.y); } } static void test_trace_contour(void) { uint8_t data[5 * 5] = { 0, W, W, W, 0, // 0, W, W, W, 0, // 0, W, 0, W, W, // 0, W, W, W, 0, // 0, 0, W, 0, W // }; uint8_t visited_data[5 * 5] = {0}; uint8_t expected_visisted_data[5 * 5] = { 0, W, W, W, 0, // 0, W, 0, W, 0, // 0, W, 0, 0, W, // 0, W, 0, W, 0, // 0, 0, W, 0, 0 // }; struct gs_image img = {5, 5, data}; struct gs_image visited = {5, 5, visited_data}; struct gs_contour contour; contour.start = (struct gs_point){1, 0}; gs_trace_contour(img, visited, &contour); assert(contour.length == 10); assert(contour.box.x == 1 && contour.box.y == 0 && contour.box.w == 4 && contour.box.h == 5); gs_for(visited, x, y) { assert(visited.data[y * visited.w + x] == expected_visisted_data[y * visited.w + x]); } } static void test_integral(void) { uint8_t data[3 * 3] = { 1, 2, 3, // 4, 5, 6, // 7, 8, 9 // }; struct gs_image img = {3, 3, data}; unsigned ii[3 * 3] = {0}; gs_integral(img, ii); unsigned expected_ii[3 * 3] = { 1, 3, 6, // 5, 12, 21, // 12, 27, 45 // }; for (unsigned i = 0; i < 9; i++) assert(ii[i] == expected_ii[i]); unsigned sum = gs_integral_sum(ii, 3, 1, 1, 2, 2); // ((1,1), (2,2)) assert(sum == 28); // 5+6+8+9, or 45+12-21-27 } static void test_template_matching(void) { uint8_t data[5 * 5] = { 0, 0, 0, 0, 0, // exact match 0, 100, 150, 200, 0, // 0, 125, 175, 225, 0, // 0, 110, 160, 210, 0, // 0, 0, 0, 0, 0 // }; uint8_t tmpl_data[3 * 3] = { 100, 150, 200, // 125, 175, 225, // 110, 160, 210 // }; struct gs_image img = {5, 5, data}; struct gs_image tmpl = {3, 3, tmpl_data}; uint8_t result_data[3 * 3]; struct gs_image result = {3, 3, result_data}; gs_match_template(img, tmpl, result); struct gs_point best = gs_find_best_match(result); assert(best.x == 1 && best.y == 1 && gs_get(result, best.x, best.y) == 255); uint8_t simple_img[4 * 4] = { 50, 50, 50, 50, // simple pattern 50, W, W, 50, // 50, W, W, 50, // 50, 50, 50, 50 // }; uint8_t simple_tmpl[2 * 2] = { W, W, // W, W // }; struct gs_image simple = {4, 4, simple_img}; struct gs_image simple_t = {2, 2, simple_tmpl}; uint8_t simple_result_data[3 * 3]; struct gs_image simple_result = {3, 3, simple_result_data}; gs_match_template(simple, simple_t, simple_result); struct gs_point simple_best = gs_find_best_match(simple_result); assert(simple_best.x == 1 && simple_best.y == 1); } int main(void) { test_crop(); test_resize(); test_blur(); test_histogram(); test_threshold(); test_adaptive_threshold(); test_otsu(); test_morph(); test_sobel(); test_blobs(); test_trace_contour(); test_integral(); test_template_matching(); return 0; }
zserge/grayskull
680
A tiny, dependency-free computer vision library in C for embedded systems, drones, and robotics.
C
zserge
Serge Zaitsev
h/index.html
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Nokia Composer - Help</title> <style> @font-face { font-family: 'N'; src: url('../N.ttf'); } * { margin: 0; padding: 0; font-family: 'N'; } body { margin: 40px auto; max-width: 650px; line-height: 1.5; font-size: 18px; color: #333; padding: 0 10px; background: #7b8; font-size: 3vmin; } a { color: #666; } p {margin-top: 1rem; } h1, h2 { line-height: 1.2; margin-top: 1rem; } </style> </head> <body> <h1>Nokia Composer</h1> <p> Composer was a classic Nokia phone application which allowed to compose ring tones phones by pressing the phones buttons to make certain sounds.</p> <h2>Notes and rests</h2> <p> A melody in composer format is a sequence of notes, separated by whitespace. Notes can be upper-case or lower-case from <b>C</b> (do) to <b>B</b> (ti). </p> <p> &gt;&nbsp; <a target="_blank" href="../#eyJicG0iOiIxMjAiLCJzb25nIjoiYyBkIGUgZiBnIGEgYiJ9">c d e f g a b</a> </p> <p>Note duration can be written before the note symbol. Dot increases the note duration by half. Default note duration is 1/4th.</p> <p> &gt;&nbsp; <a target="_blank" href="../#eyJicG0iOiIxNDAiLCJzb25nIjoiNC5jIDhkIDQuZSA4YyA0ZSA0YyA0ZSJ9">4.c 8d 4.e 8c 4e 4c 4e</a> </p> <p>Rests are indicated by the "-" character</p> <p> &gt;&nbsp; <a target="_blank" href="../#eyJicG0iOiIxNDAiLCJzb25nIjoiMTYuZyAzMi0gMTYuZyAzMi0gMTYuZyAzMi0gMWUifQ=="> 16.g 32- 16.g 32- 16.g 32- 1e</a> </p> <p><b>"#"</b> makes the note sharp (must be written in front of the note), e.g. "8.#f". There are no flat notes.</p> <p>Octave can be written after the note. Default octave is 1. Supported octaves are 1 to 3.</p> <p> &gt;&nbsp; <a target="_blank" href="../#eyJicG0iOiIxMjAiLCJzb25nIjoiMTZlMiAxNmQyIDgjZiA4I2cgMTYjYzIgMTZiIDhkIDhlIDE2YiAxNmEgOCNjIDhlIDJhIn0="> 16e2 16d2 8#f 8#g 16#c2 16b 8d 8e 16b 16a 8#c 8e 2a </a> </p> <p>Tempo can be set in the BPM field.</p> <p>You can share composed melodies by sending the complete URL. It contains the tempo and the melody. You may bookmark melodies in your browser to play them later.</p> <p>Have fun!</p> <p><a target="_blank" href="../">Launch Composer</a></p> <p>P.S. if you found an issue or would like to contribute - it's on <a href="https://github.com/zserge/nokia-composer/">github</a>.</p> </body> </html>
zserge/nokia-composer
143
Nokia Composer in 512 bytes
HTML
zserge
Serge Zaitsev
index.html
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Nokia Composer</title> <style> @font-face { font-family: 'N'; src: url('N.ttf'); } * { margin: 0; padding: 0; font-family: 'N'; font-size: 5vmin; border: 0; outline: 0; background: #7b8; color: #333; } a { font-weight: bold; text-decoration: none; } body { width: 15rem; margin: 4rem auto; } input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type=number] { -moz-appearance: textfield; } </style> </head> <body> <div style="display:flex;flex-direction:column;align-items:stretch;"> <div style="display:flex;margin-bottom:1rem;"> <label for="bpm">BPM:<input id="bpm" value="120" size="3" type="number" min="1" max="800" /></label> <span style="flex:1"></span> <a target="_blank" href="h/">?</a> </div> <div id="song" contenteditable="true" spellcheck="false"></div> <a id="btn" style="margin:1rem;text-align:center;" href="javascript:void(0)" onclick="togglePlayback()" >Play</a > </div> <script> // This is a little shim to make the composer a bit more usable // Safari does not support AudioContext yet window.AudioContext = window.AudioContext || window.webkitAudioContext; // Load song from the URL try { const data = JSON.parse(atob(location.hash.slice(1))); bpm.value = data.bpm; song.innerText = data.song; } catch (ignored) { // Nokia ringtone, by default bpm.value = '120'; song.innerText = `16e2 16d2 8#f 8#g 16#c2 16b 8d 8e 16b 16a 8#c 8e 2a 2-`; } // Toggle playback on Ctrl+Enter song.onkeydown = e => { if (e.ctrlKey && e.keyCode === 13) { e.preventDefault(); togglePlayback(); } }; // Auto-song to URI (song.oninput = bpm.oninput = () => { location.hash = btoa( JSON.stringify({bpm: bpm.value, song: song.innerText}), ); })(); // Play song or stop the playback function togglePlayback() { if (C) { stop(); btn.innerText = 'Play'; } else { btn.innerText = 'Stop'; play(song.innerText, c(bpm.value, 40, 400)); } } </script> <script src="n.min.js"></script> <script>new Image().src='https://nullitics.com/file.gif?u=nokia&r='+encodeURI(document.referrer)+'&d='+screen.width</script> <noscript><img src=https://nullitics.com/file.gif></noscript> </body> </html>
zserge/nokia-composer
143
Nokia Composer in 512 bytes
HTML
zserge
Serge Zaitsev
n.js
JavaScript
C = 0; // Initial value for audio context is zero stop = _ => C && C.close((C = 0)); // interrupt the playback, if any c = (x = 0, a, b) => (x < a && (x = a), x > b ? b : x); // clamping function (a<=x<=b) play = (s, bpm) => { // Create audio context, square oscillator and gain to mute/unmute it C = new AudioContext(); (z = C.createOscillator()) .connect((g = C.createGain())) .connect(C.destination); z.type = 'square'; z.start(); t = 0; // current time counter, in seconds v = (x, v) => x.setValueAtTime(v, t); // setValueAtTime shorter alias for (m of s.matchAll(/(\d*)?(\.?)(#?)([a-g-])(\d*)/g)) { k = m[4].charCodeAt(); // note ASCII [0x41..0x47] or [0x61..0x67] n = 0 | ((((k & 7) * 1.6 + 8) % 12) + !!m[3] + 12 * c(m[5], 1, 3)); // note index [0..35] v(z.frequency, 261.63 * 2 ** (n / 12)); v(g.gain, (~k & 8) / 8); // note duration, measured in 1/10 seconds to simplify further ratios, // i.e. multiply by 7 instead of 0.7 d = (24 / bpm / c(m[1] || 4, 1, 64)) * (1 + !!m[2] / 2); t = t + d*7; v(g.gain, 0); t = t + d*3; } };
zserge/nokia-composer
143
Nokia Composer in 512 bytes
HTML
zserge
Serge Zaitsev
n.min.js
JavaScript
C=0;stop=t=>C&&C.close(C=0);c=(t=0,e,a)=>(t<e&&(t=e),t>a?a:t);play=(e,a)=>{C=new AudioContext;(z=C.createOscillator()).connect(g=C.createGain()).connect(C.destination);z.type="square";z.start();t=0;v=(e,a)=>e.setValueAtTime(a,t);for(m of e.matchAll(/(\d*)?(\.?)(#?)([a-g-])(\d*)/g)){k=m[4].charCodeAt();n=0|((k&7)*1.6+8)%12+!!m[3]+12*c(m[5],1,3);v(z.frequency,261.63*2**(n/12));v(g.gain,(~k&8)/8);d=24/a/c(m[1]||4,1,64)*(1+!!m[2]/2);t=t+d*7;v(g.gain,0);t=t+d*3}};
zserge/nokia-composer
143
Nokia Composer in 512 bytes
HTML
zserge
Serge Zaitsev
api_test.go
Go
package pennybase import ( "bytes" "encoding/json" "io" "net/http" "net/http/httptest" "net/url" "path/filepath" "strings" "testing" ) func TestServerREST(t *testing.T) { testDir := testData(t, filepath.Join("testdata", "rest")) s := must(NewServer( testDir, filepath.Join(testDir, "templates"), filepath.Join(testDir, "static"), )).T(t) defer s.Store.Close() ts := httptest.NewServer(s) defer ts.Close() tests := []struct { name string method string path string body any auth [2]string // user, pass status int validate func(*testing.T, *http.Response) }{ // Public endpoints { name: "List books unauthorized", method: http.MethodGet, path: "/api/books/", status: http.StatusOK, validate: func(t *testing.T, resp *http.Response) { var books []Resource must0(t, json.NewDecoder(resp.Body).Decode(&books)) if len(books) != 2 { t.Errorf("Expected 2 books, got %d", len(books)) } }, }, { name: "Get static file", method: http.MethodGet, path: "/static/test.txt", status: http.StatusOK, validate: func(t *testing.T, resp *http.Response) { body := must(io.ReadAll(resp.Body)).T(t) if !bytes.Equal(body, []byte("Static text file\n")) { t.Errorf("Static file content mismatch: %s", body) } }, }, // Template rendering { name: "Render books template", method: http.MethodGet, path: "/books.html", status: http.StatusOK, validate: func(t *testing.T, resp *http.Response) { body, _ := io.ReadAll(resp.Body) if !strings.Contains(string(body), "The Go Programming Language") || !strings.Contains(string(body), "1984") { t.Error(string(body)) t.Error("Template missing book data") } }, }, // Authentication tests { name: "Create book unauthenticated", method: http.MethodPost, path: "/api/books/", body: Resource{"title": "New Book"}, status: http.StatusUnauthorized, }, { name: "Create book invalid credentials", method: http.MethodPost, path: "/api/books/", body: Resource{"title": "New Book"}, auth: [2]string{"user1", "wrongpass"}, status: http.StatusUnauthorized, }, // Authorized operations { name: "Create book valid user", method: http.MethodPost, path: "/api/books/", body: Resource{"title": "Valid Book", "author": "Unknown Author", "year": 2023}, auth: [2]string{"user1", "user1pass"}, status: http.StatusCreated, validate: func(t *testing.T, resp *http.Response) { loc := resp.Header.Get("Location") if !strings.HasPrefix(loc, "/api/books/") { t.Error("Missing Location header") } }, }, { name: "Update book unauthorized", method: http.MethodPut, path: "/api/books/book1", body: Resource{"title": "Updated Title"}, auth: [2]string{"user1", "user1pass"}, status: http.StatusUnauthorized, }, // Admin operations { name: "Delete book as admin", method: http.MethodDelete, path: "/api/books/book2", auth: [2]string{"admin", "admin123"}, status: http.StatusOK, }, // Validation tests { name: "Create invalid book", method: http.MethodPost, path: "/api/books/", body: Resource{"title": "Book 123", "year": 3000}, auth: [2]string{"user1", "user1pass"}, status: http.StatusInternalServerError, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { var body io.Reader if tc.body != nil { b := must(json.Marshal(tc.body)).T(t) body = bytes.NewReader(b) } u := must(url.JoinPath(ts.URL, tc.path)).T(t) req := must(http.NewRequest(tc.method, u, body)).T(t) if tc.auth[0] != "" { req.SetBasicAuth(tc.auth[0], tc.auth[1]) } resp := must(http.DefaultClient.Do(req)).T(t) defer resp.Body.Close() if resp.StatusCode != tc.status { t.Errorf("Expected status %d, got %d", tc.status, resp.StatusCode) } if tc.validate != nil { tc.validate(t, resp) } }) } } func TestServerTemplate(t *testing.T) { dir := testData(t, filepath.Join("testdata", "rest")) s := must(NewServer(dir, filepath.Join(dir, "templates"), "" /*staticDir*/)).T(t) req := httptest.NewRequest(http.MethodGet, "/books.html", nil) w := httptest.NewRecorder() s.Mux.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected status 200 OK, got %d", w.Code) } gotBody := w.Body.String() if !strings.Contains(gotBody, "<div class=\"book\">The Go Programming Language (2015)</div>") { t.Errorf("Got unexpected body: %v", gotBody) } if !strings.Contains(gotBody, "<div class=\"book\">1984 (1949)</div>") { t.Errorf("Got unexpected body: %v", gotBody) } } func TestServerStaticFiles(t *testing.T) { dir := testData(t, filepath.Join("testdata", "rest")) s := must(NewServer(dir, "" /*tmplDir*/, filepath.Join(dir, "static"))).T(t) req := httptest.NewRequest(http.MethodGet, "/static/test.txt", nil) w := httptest.NewRecorder() s.Mux.ServeHTTP(w, req) if gotBody := w.Body.String(); gotBody != "Static text file\n" { t.Errorf("Static file serving failed: %v", gotBody) } }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
authz_test.go
Go
package pennybase import ( "errors" "path/filepath" "testing" ) func TestAuthorization(t *testing.T) { tests := []struct { name string resource string id string action string username string password string wantErr bool expectedErr error }{ { name: "Public read access", resource: "books", action: "read", username: "", password: "", wantErr: false, }, { name: "Create with editor role", resource: "books", action: "create", username: "alice", password: "alicepass", wantErr: false, }, { name: "Update own post via owner field", resource: "books", id: "book123", action: "update", username: "bob", password: "bobpass", wantErr: false, }, { name: "Delete without admin role", resource: "books", action: "delete", username: "alice", password: "alicepass", wantErr: true, expectedErr: errors.New("unauthorized"), }, { name: "Full access via owner field as a list", resource: "books", action: "update", id: "book123", username: "alice", password: "alicepass", wantErr: false, }, { name: "Invalid credentials", resource: "books", action: "create", username: "alice", password: "wrongpass", wantErr: true, expectedErr: errors.New("unauthicated"), }, { name: "Admin delete access", resource: "books", action: "delete", username: "admin", password: "admin123", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { dir := testData(t, filepath.Join("testdata", "authz")) store := must(NewStore(dir)).T(t) defer store.Close() // Setup test resource if needed // if tt.id != "" { // store.Create("books", Resource{ // "_id": tt.id, // "title": "Test Book", // "owner": tt.username, // "admins": []string{tt.username}, // }) // } // u, _ := store.AuthenticateBasic(tt.username, tt.password) err := store.Authorize(tt.resource, tt.id, tt.action, u) if (err != nil) != tt.wantErr { t.Errorf("Authorize() error = %v, wantErr %v", err, tt.wantErr) } // if tt.expectedErr != nil && !errors.Is(err, tt.expectedErr) { // t.Errorf("Expected error %v, got %v", tt.expectedErr, err) // } }) } }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
cmd/pennybase/main.go
Go
package main import ( "log" "net/http" "os" "github.com/zserge/pennybase" ) func main() { server, err := pennybase.NewServer("data", "templates", "static") if err != nil { log.Fatal(err) } logger := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s %s", r.Method, r.URL.String()) next.ServeHTTP(w, r) }) } if salt := os.Getenv("SALT"); salt != "" { pennybase.SessionKey = salt } port := os.Getenv("PORT") if port == "" { port = "8080" } log.Printf("Starting server on port %s...\n", port) log.Fatal(http.ListenAndServe(":"+port, logger(server))) }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
csvdb_test.go
Go
package pennybase import ( "crypto/rand" "path/filepath" "slices" "strconv" "sync" "testing" ) var _ DB = (*csvDB)(nil) func TestDBBasicOperations(t *testing.T) { db := must(NewCSVDB(filepath.Join(t.TempDir(), "test.csv"))).T(t) defer db.Close() id := rand.Text() if rec, err := db.Get(id); err == nil { t.Fatalf("want not record, got %v", rec) } initialRec := Record{id, "1", "foo"} must0(t, db.Create(initialRec)) if rec := must(db.Get(id)).T(t); !slices.Equal(rec, initialRec) { t.Fatalf("get after create got %v, want %v", rec, initialRec) } updatedRec := Record{id, "2", "bar"} must0(t, db.Update(updatedRec)) if rec := must(db.Get(id)).T(t); !slices.Equal(rec, updatedRec) { t.Fatalf("get after update got %v, want %v", rec, updatedRec) } if err := db.Update(updatedRec); err == nil { t.Fatal("want error on same value update") } must0(t, db.Delete(id)) if rec, err := db.Get(id); err == nil { t.Fatalf("got unexpected record after delete: %v", rec) } if err := db.Update(Record{id, "3", "qux"}); err == nil { t.Fatal("want error on update after delete") } } func TestEmptyIterator(t *testing.T) { db, _ := NewCSVDB(filepath.Join(t.TempDir(), "test.csv")) defer db.Close() count := 0 for range db.Iter() { count++ } if count != 0 { t.Fatalf("Expected 0 records, got %d", count) } } func TestIteratorWithDeletes(t *testing.T) { db := must(NewCSVDB(filepath.Join(t.TempDir(), "test.csv"))).T(t) defer db.Close() for i := range 10 { must0(t, db.Create(Record{strconv.Itoa(i), "1", "data"})) must0(t, db.Delete(strconv.Itoa(i))) } must0(t, db.Create(Record{"active", "1", "data"})) count := 0 for r := range db.Iter() { if r[0] == "active" { count++ } else if r[1] != "0" { t.Errorf("Unexpected record: %v", r) } } if count != 1 { t.Errorf("Expected 1 active record, got %d", count) } } func TestConcurrent(t *testing.T) { db := must(NewCSVDB(filepath.Join(t.TempDir(), "test.csv"))).T(t) defer db.Close() var wg sync.WaitGroup for i := range 1000 { wg.Add(1) go func() { defer wg.Done() id := strconv.Itoa(i) must0(t, db.Create(Record{id, "1", "data"})) must(db.Get(id)).T(t) }() } wg.Wait() for i := range 1000 { id := strconv.Itoa(i) must(db.Get(id)).T(t) } } func BenchmarkWrite(b *testing.B) { db, _ := NewCSVDB(filepath.Join(b.TempDir(), "test.csv")) defer db.Close() b.ResetTimer() for i := range b.N { id := strconv.Itoa(i) _ = db.Create(Record{id, "1", "data"}) } } func BenchmarkRead(b *testing.B) { db, _ := NewCSVDB(filepath.Join(b.TempDir(), "test.csv")) defer db.Close() for i := range 1000 { id := strconv.Itoa(i) _ = db.Create(Record{id, "1", "data"}) } b.ResetTimer() for i := range b.N { id := strconv.Itoa(i % 1000) _, _ = db.Get(id) } }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
examples/chat/templates/index.html
HTML
<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/htmx.org@latest"></script> <script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script> <script src="https://unpkg.com/htmx.org/dist/ext/sse.js"></script> </head> <body> {{if not .User}} <form hx-post="/api/login"> <input name="username" placeholder="Username" required> <input name="password" type="password" placeholder="Password" required> <button type="submit">Login</button> </form> {{else}} <div id="messages-container" hx-ext="sse" sse-connect="/api/events/messages"> <div hx-get="/messages" hx-trigger="load,sse:created" hx-swap="innerHTML"></div> </div> <form hx-post="/api/messages/" hx-swap="none" hx-ext="json-enc" _="on htmx:afterRequest reset() me"> <input type="text" name="content" placeholder="Type your message here..." required> <button type="submit">Send</button> </form> {{end}} <script> htmx.logAll(); </script> </body> </html> {{define "messages"}} {{range .Store.List "messages" "created_at"}} <div class="message"> <strong>{{.author}}:</strong> <span>{{.content}}</span> {{ if call $.Authorize "messages" ._id "delete" }} <button class="delete" hx-delete="/api/messages/{{._id}}" hx-target="closest .message" hx-swap="outerHTML">×</button> {{ end }} </div> {{end}} {{end}}
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
examples/login/templates/index.html
HTML
<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/htmx.org@latest"></script> <script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script> </head> <body> {{if not .User}} <form hx-post="/api/login"> <input name="username" placeholder="Username" required> <input name="password" type="password" placeholder="Password" required> <button type="submit">Login</button> </form> {{else}} <p>Welcome, {{.User._id}}!</p> <button hx-post="/api/logout">Logout</button> {{end}} </body> </html>
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
examples/todo/templates/index.html
HTML
<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/htmx.org@latest"></script> <script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script> </head> <body> <div hx-get="/todo-list" hx-trigger="load" hx-target="this"> </div> </body> </html> {{define "todo-list"}} <div id="todo-list" hx-get="/todo-list" hx-trigger="todo-changed from:body"> {{range .Store.List "todo" "_id"}} {{template "todo-item" .}} {{end}} </div> <form hx-post="/api/todo/" hx-swap="none" hx-ext="json-enc" _="on htmx:afterRequest reset() me"> <input type="text" name="description" required> <button>Add</button> </form> {{end}} {{define "todo-item"}} <div class="todo" id="todo-{{._id}}"> <span class="{{if .completed}}completed{{end}}">{{.description}}</span> <button hx-put="/api/todo/{{._id}}" hx-ext="json-enc" hx-vals='{"completed":{{if .completed}}0{{else}}1{{end}}}' _="on click toggle .completed on previous span"> {{if .completed}}Undo{{else}}Complete{{end}} </button> <button hx-delete="/api/todo/{{._id}}" hx-target="closest .todo" hx-swap="outerHTML"> Delete </button> </div> {{end}}
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
pennybase.go
Go
package pennybase import ( "context" "crypto/rand" "crypto/sha256" "encoding/base32" "encoding/csv" "encoding/json" "errors" "fmt" "html/template" "io" "log" "net/http" "os" "path/filepath" "regexp" "slices" "sort" "strconv" "strings" "sync" "time" ) type Record []string type Resource map[string]any type FieldType string const ( Number FieldType = "number" Text FieldType = "text" List FieldType = "list" ) type FieldSchema struct { Resource string Field string Type FieldType Min float64 Max float64 Regex string } type Schema []FieldSchema type DB interface { Create(r Record) error Update(r Record) error Get(id string) (Record, error) Delete(id string) error Iter() func(yield func(Record, error) bool) Close() error } var ID = func() string { return rand.Text() } var Salt = func() string { return rand.Text() } var HashPasswd = func(passwd, salt string) string { sum := sha256.Sum256([]byte(salt + passwd)) return base32.StdEncoding.EncodeToString(sum[:]) } var SessionKey = Salt() func (field FieldSchema) Validate(v any) bool { if v == nil { return false } switch field.Type { case Number: n, ok := v.(float64) return ok && ((field.Min == 0 && field.Max == 0) || (n >= field.Min && (field.Max < field.Min || n <= field.Max))) case Text: s, ok := v.(string) return ok && (field.Regex == "" || regexp.MustCompile(field.Regex).MatchString(s)) case List: _, ok := v.([]string) return ok } return false } func (s Schema) Record(res Resource) (Record, error) { rec := Record{} for _, field := range s { v := res[field.Field] if v == nil { v = map[FieldType]any{Number: 0.0, Text: "", List: []string{}}[field.Type] } if !field.Validate(v) { return nil, fmt.Errorf("invalid field \"%s\"", field.Field) } switch field.Type { case Number: rec = append(rec, fmt.Sprintf("%g", v)) case Text: rec = append(rec, v.(string)) case List: rec = append(rec, strings.Join(v.([]string), ",")) } } return rec, nil } func (s Schema) Resource(rec Record) (Resource, error) { res := Resource{} for i, field := range s { if i >= len(rec) { return nil, fmt.Errorf("record length %d is less than schema length %d", len(rec), len(s)) } switch field.Type { case Number: n, err := strconv.ParseFloat(rec[i], 64) if err != nil { return nil, err } res[field.Field] = n case Text: res[field.Field] = rec[i] case List: if rec[i] != "" { res[field.Field] = strings.Split(rec[i], ",") } else { res[field.Field] = []string{} } default: return nil, fmt.Errorf("unknown field type %s", field.Type) } } return res, nil } type csvDB struct { mu sync.Mutex f *os.File w *csv.Writer index map[string]int64 version map[string]int64 } func NewCSVDB(path string) (*csvDB, error) { f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return nil, err } db := &csvDB{f: f, w: csv.NewWriter(f), index: map[string]int64{}, version: map[string]int64{}} r := csv.NewReader(f) r.FieldsPerRecord = -1 for { pos := r.InputOffset() rec, err := r.Read() if errors.Is(err, io.EOF) { break } if err != nil { return nil, err } if len(rec) > 0 { db.index[rec[0]] = pos db.version[rec[0]], _ = strconv.ParseInt(rec[1], 10, 64) } } return db, nil } func (db *csvDB) Close() error { db.mu.Lock() defer db.mu.Unlock() db.w.Flush() return db.f.Close() } func (db *csvDB) append(r Record) error { pos, _ := db.f.Seek(0, io.SeekEnd) err := db.w.Write(r) if err != nil { return err } db.w.Flush() db.index[r[0]] = pos db.version[r[0]], err = strconv.ParseInt(r[1], 10, 64) return err } func (db *csvDB) Create(r Record) error { db.mu.Lock() defer db.mu.Unlock() if r[0] == "" || r[1] != "1" || db.version[r[0]] != 0 { return errors.New("invalid record") } return db.append(r) } func (db *csvDB) Update(r Record) error { db.mu.Lock() defer db.mu.Unlock() if len(r) == 0 || r[1] != strconv.FormatInt(db.version[r[0]]+1, 10) { return errors.New("invalid record version") } return db.append(r) } func (db *csvDB) Delete(id string) error { db.mu.Lock() defer db.mu.Unlock() if db.version[id] < 1 { return errors.New("record not found") } return db.append(Record{id, "0"}) } func (db *csvDB) Get(id string) (Record, error) { db.mu.Lock() defer db.mu.Unlock() if db.version[id] < 1 { return nil, errors.New("record not found") } offset, ok := db.index[id] if !ok { return nil, nil } if _, err := db.f.Seek(offset, io.SeekStart); err != nil { return nil, err } r := csv.NewReader(db.f) rec, err := r.Read() if err != nil { return nil, err } if len(rec) > 0 && rec[0] != id { log.Println(rec) return nil, errors.New("corrupted index") } return rec, nil } func (db *csvDB) Iter() func(yield func(Record, error) bool) { return func(yield func(Record, error) bool) { db.mu.Lock() defer db.mu.Unlock() if _, err := db.f.Seek(0, io.SeekStart); err != nil { yield(nil, err) return } r := csv.NewReader(db.f) r.FieldsPerRecord = -1 for { rec, err := r.Read() if errors.Is(err, io.EOF) { break } if err != nil { yield(nil, err) return } if len(rec) < 2 { continue } id, version := rec[0], rec[1] if version == "0" || version != strconv.FormatInt(db.version[id], 10) { continue // deleted items or outdated versions } if !yield(rec, nil) { return } } } } func SignSession(username string) string { data := fmt.Sprintf("%s:%d", username, time.Now().Unix()) sum := sha256.Sum256([]byte(SessionKey + data)) sig := base32.StdEncoding.EncodeToString(sum[:])[:16] return fmt.Sprintf("%s.%s", data, sig) } func VerifySession(session string) (string, bool) { parts := strings.Split(session, ".") if len(parts) != 2 { return "", false } data, sig := parts[0], parts[1] sum := sha256.Sum256([]byte(SessionKey + data)) expectedSig := base32.StdEncoding.EncodeToString(sum[:])[:16] if sig != expectedSig { return "", false } if parts = strings.Split(data, ":"); len(parts) == 2 { if ts, err := strconv.ParseInt(parts[1], 10, 64); err == nil { if time.Now().Unix()-ts < 86400 { // 24 hours return parts[0], true } } } return "", false } type Store struct { Dir string Schemas map[string]Schema Resources map[string]DB } func NewStore(dir string) (*Store, error) { s := &Store{Dir: dir, Schemas: map[string]Schema{}, Resources: map[string]DB{}} schemaDB, err := NewCSVDB(s.Dir + "/_schemas.csv") if err != nil { return nil, err } for rec, err := range schemaDB.Iter() { if err != nil { return nil, err } if len(rec) != 8 { return nil, fmt.Errorf("invalid schema record: %v", rec) } schema := FieldSchema{ Resource: rec[2], Field: rec[3], Type: FieldType(rec[4]), Regex: rec[7], } schema.Min, _ = strconv.ParseFloat(rec[5], 64) schema.Max, _ = strconv.ParseFloat(rec[6], 64) s.Schemas[schema.Resource] = append(s.Schemas[schema.Resource], schema) if _, ok := s.Resources[schema.Resource]; !ok { db, err := NewCSVDB(s.Dir + "/" + schema.Resource + ".csv") if err != nil { return nil, err } s.Resources[schema.Resource] = db } } return s, nil } func (s *Store) Create(resource string, r Resource) (string, error) { db, ok := s.Resources[resource] if !ok { return "", fmt.Errorf("resource %s not found", resource) } newID := ID() r["_id"] = newID r["_v"] = 1.0 rec, err := s.Schemas[resource].Record(r) if err != nil { return "", err } if err := db.Create(rec); err != nil { return "", err } return newID, nil } func (s *Store) Update(resource string, r Resource) error { db, ok := s.Resources[resource] if !ok { return fmt.Errorf("resource %s not found", resource) } orig, err := s.Get(resource, r["_id"].(string)) if err != nil { return fmt.Errorf("record not found: %w", err) } for _, field := range s.Schemas[resource] { if _, ok := r[field.Field]; !ok { r[field.Field] = orig[field.Field] } } r["_v"] = orig["_v"].(float64) + 1 rec, err := s.Schemas[resource].Record(r) if err != nil { return err } return db.Update(rec) } func (s *Store) Delete(resource, id string) error { db, ok := s.Resources[resource] if !ok { return fmt.Errorf("resource %s not found", resource) } return db.Delete(id) } func (s *Store) Get(resource, id string) (Resource, error) { db, ok := s.Resources[resource] if !ok { return nil, fmt.Errorf("resource %s not found", resource) } rec, err := db.Get(id) if err != nil { return nil, err } if len(rec) < 2 { return nil, nil // record not found } return s.Schemas[resource].Resource(rec) } func (s *Store) List(resource, sortBy string) ([]Resource, error) { db, ok := s.Resources[resource] if !ok { return nil, fmt.Errorf("resource %s not found", resource) } res := []Resource{} for rec, err := range db.Iter() { if err != nil { return nil, err } if len(rec) < 2 { continue } r, err := s.Schemas[resource].Resource(rec) if err != nil { return res, err } res = append(res, r) } if sortBy != "" { sort.Slice(res, func(i, j int) bool { if res[i][sortBy] == nil { return false } if res[j][sortBy] == nil { return true } switch res[i][sortBy].(type) { case string: return res[i][sortBy].(string) < res[j][sortBy].(string) case float64: return res[i][sortBy].(float64) < res[j][sortBy].(float64) default: return false } }) } return res, nil } func (s *Store) Close() error { for _, db := range s.Resources { if err := db.Close(); err != nil { return err } } return nil } func (s *Store) Authenticate(r *http.Request) (Resource, error) { if cookie, err := r.Cookie("session"); err == nil { if username, ok := VerifySession(cookie.Value); ok { u, err := s.Get("_users", username) if err != nil { return nil, fmt.Errorf("users error: %w", err) } return u, nil } } if username, password, ok := r.BasicAuth(); ok { return s.AuthenticateBasic(username, password) } return nil, errors.New("unauthenticated") } func (s *Store) AuthenticateBasic(username, password string) (Resource, error) { u, err := s.Get("_users", username) if err != nil { return nil, fmt.Errorf("users error: %w", err) } if u["password"] != HashPasswd(password, u["salt"].(string)) { return nil, errors.New("unauthenticated") } return u, nil } func (s *Store) Authorize(resource, id, action string, user Resource) error { permissions, err := s.List("_permissions", "") if err != nil { return fmt.Errorf("permissions error: %w", err) } for _, p := range permissions { if p["resource"] != resource || (p["action"] != "*" && p["action"] != action) { continue } if p["field"] == "" && p["role"] == "" { // public return nil } if user == nil { return errors.New("unauthenticated") } // Any role? Or user has the role? if p["role"] == "*" || slices.Contains(user["roles"].([]string), p["role"].(string)) { return nil } if id != "" { res, err := s.Get(resource, id) if err != nil { return err } username := user["_id"].(string) if user, ok := res[p["field"].(string)]; ok && user == username { return nil // user name matches requested resource field (string) } else if users, ok := res[p["field"].(string)].([]string); ok && slices.Contains(users, username) { return nil // user name is in the requested resource field (list) } } } return errors.New("unauthorized") } type Event struct { Action string `json:"action"` ID string `json:"id"` Data Resource `json:"data"` } type Broker struct { channels map[string]map[chan Event]bool // resource -> channels mu sync.RWMutex } func (b *Broker) Subscribe(resource string, ch chan Event) { b.mu.Lock() defer b.mu.Unlock() if b.channels[resource] == nil { b.channels[resource] = make(map[chan Event]bool) } b.channels[resource][ch] = true } func (b *Broker) Unsubscribe(resource string, ch chan Event) { b.mu.Lock() defer b.mu.Unlock() if subs := b.channels[resource]; subs != nil { delete(subs, ch) } } func (b *Broker) Publish(resource string, evt Event) { b.mu.RLock() defer b.mu.RUnlock() if subs := b.channels[resource]; subs != nil { for ch := range subs { select { case ch <- evt: default: } } } } type Hook func(trigger, resource string, user, r Resource) error func nopHook(trigger, resource string, user, r Resource) error { return nil } type Server struct { Store *Store Broker *Broker Mux *http.ServeMux Hook Hook } func NewServer(dataDir, tmplDir, staticDir string) (*Server, error) { store, err := NewStore(dataDir) if err != nil { return nil, err } s := &Server{Store: store, Broker: &Broker{channels: map[string]map[chan Event]bool{}}, Mux: http.NewServeMux(), Hook: nopHook} auth := func(next http.HandlerFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { resource := r.PathValue("resource") action := map[string]string{"GET": "read", "POST": "create", "PUT": "update", "DELETE": "delete"}[r.Method] user, _ := s.Store.Authenticate(r) if resource != "" && action != "" { if err := s.Store.Authorize(resource, r.PathValue("id"), action, user); err != nil { http.Error(w, err.Error(), http.StatusUnauthorized) return } } next(w, r.WithContext(context.WithValue(r.Context(), "user", user))) }) } s.Mux.Handle("GET /api/{resource}/", auth(s.handleList)) s.Mux.Handle("POST /api/{resource}/", auth(s.handleCreate)) s.Mux.Handle("GET /api/{resource}/{id}", auth(s.handleGet)) s.Mux.Handle("PUT /api/{resource}/{id}", auth(s.handleUpdate)) s.Mux.Handle("DELETE /api/{resource}/{id}", auth(s.handleDelete)) s.Mux.HandleFunc("GET /api/events/{resource}", s.handleEvents) s.Mux.HandleFunc("POST /api/login", s.handleLogin) s.Mux.HandleFunc("POST /api/logout", s.handleLogout) if tmplDir != "" { if tmpl, err := template.ParseGlob(filepath.Join(tmplDir, "*")); err == nil { for _, t := range tmpl.Templates() { if t.Name() == "index.html" { s.Mux.Handle("GET /", s.handleTemplate(t, "index.html")) } s.Mux.Handle(fmt.Sprintf("GET /%s", t.Name()), s.handleTemplate(tmpl, t.Name())) } } else { log.Fatal("Error parsing templates:", err) } } if staticDir != "" { s.Mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir)))) } return s, nil } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.Mux.ServeHTTP(w, r) } func (s *Server) handleList(w http.ResponseWriter, r *http.Request) { res, err := s.Store.List(r.PathValue("resource"), r.FormValue("sort_by")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } _ = json.NewEncoder(w).Encode(res) } func (s *Server) handleCreate(w http.ResponseWriter, r *http.Request) { var res Resource if err := json.NewDecoder(r.Body).Decode(&res); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } resource := r.PathValue("resource") if err := s.Hook("create", resource, r.Context().Value("user").(Resource), res); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } id, err := s.Store.Create(resource, res) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } s.Broker.Publish(resource, Event{Action: "created", ID: res["_id"].(string), Data: res}) w.Header().Set("Location", fmt.Sprintf("/api/%s/%s", resource, id)) w.Header().Set("HX-Trigger", fmt.Sprintf("%s-changed", resource)) w.WriteHeader(http.StatusCreated) } func (s *Server) handleGet(w http.ResponseWriter, r *http.Request) { res, err := s.Store.Get(r.PathValue("resource"), r.PathValue("id")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if res == nil { http.NotFound(w, r) return } _ = json.NewEncoder(w).Encode(res) } func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) { res := Resource{} if err := json.NewDecoder(r.Body).Decode(&res); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } resource := r.PathValue("resource") res["_id"] = r.PathValue("id") if err := s.Hook("update", resource, r.Context().Value("user").(Resource), res); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := s.Store.Update(resource, res); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } s.Broker.Publish(resource, Event{Action: "updated", ID: res["_id"].(string), Data: res}) w.Header().Set("HX-Trigger", fmt.Sprintf("%s-changed", resource)) w.WriteHeader(http.StatusOK) } func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) { res, _ := s.Store.Get(r.PathValue("resource"), r.PathValue("id")) if err := s.Hook("delete", r.PathValue("resource"), r.Context().Value("user").(Resource), res); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := s.Store.Delete(r.PathValue("resource"), r.PathValue("id")); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } s.Broker.Publish(r.PathValue("resource"), Event{Action: "deleted", Data: res}) w.Header().Set("HX-Trigger", fmt.Sprintf("%s-changed", r.PathValue("resource"))) w.WriteHeader(http.StatusOK) } func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { username, password := r.FormValue("username"), r.FormValue("password") if _, err := s.Store.AuthenticateBasic(username, password); err != nil { http.Error(w, "Invalid credentials", http.StatusUnauthorized) return } http.SetCookie(w, &http.Cookie{ Name: "session", Value: SignSession(username), Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: 86400, // 24 hours }) w.Header().Set("HX-Redirect", "/") w.WriteHeader(http.StatusOK) } func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{Name: "session", Value: "", Path: "/", HttpOnly: true, MaxAge: -1}) w.Header().Set("HX-Redirect", "/") w.WriteHeader(http.StatusOK) } func (s *Server) handleTemplate(tmpl *template.Template, name string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user, _ := s.Store.Authenticate(r) data := map[string]any{ "Store": s.Store, "Request": r, "User": user, "ID": r.URL.Query().Get("_id"), "Authorize": func(resource, id, action string) bool { return s.Store.Authorize(resource, id, action, user) == nil }, } if err := tmpl.ExecuteTemplate(w, name, data); err != nil { log.Println("Error executing template:", name, err) } } } func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) { flusher, ok := w.(http.Flusher) if !ok { http.Error(w, "SSE not supported", http.StatusBadRequest) return } w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") resource := r.PathValue("resource") user, err := s.Store.Authenticate(r) if err != nil { http.Error(w, "unauthenticated", http.StatusUnauthorized) return } events := make(chan Event, 10) s.Broker.Subscribe(resource, events) defer s.Broker.Unsubscribe(resource, events) for { select { case e := <-events: if e.Action == "delete" || s.Store.Authorize(resource, e.ID, "read", user) == nil { data, _ := json.Marshal(e.Data) fmt.Fprintf(w, "event: %s\ndata: %s\n\n", e.Action, data) flusher.Flush() } case <-r.Context().Done(): return } } }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
schema_test.go
Go
package pennybase import ( "fmt" "math" "reflect" "slices" "testing" ) const testID = "test0001" func TestFieldSchema(t *testing.T) { tests := []struct { name string field FieldSchema value any expected bool }{ // Number validation { name: "valid number within range", field: FieldSchema{Type: Number, Min: 5, Max: 10}, value: 7.0, expected: true, }, { name: "number at min boundary", field: FieldSchema{Type: Number, Min: 5, Max: 10}, value: 5.0, expected: true, }, { name: "number at max boundary", field: FieldSchema{Type: Number, Min: 5, Max: 10}, value: 10.0, expected: true, }, { name: "number below min", field: FieldSchema{Type: Number, Min: 5, Max: 10}, value: 4.9, expected: false, }, { name: "number above max", field: FieldSchema{Type: Number, Min: 5, Max: 10}, value: 10.1, expected: false, }, { name: "invalid number type", field: FieldSchema{Type: Number}, value: "not a number", expected: false, }, // Text validation { name: "text matches regex", field: FieldSchema{Type: Text, Regex: "^[a-z]+$"}, value: "lowercase", expected: true, }, { name: "text doesn't match regex", field: FieldSchema{Type: Text, Regex: "^[a-z]+$"}, value: "Uppercase", expected: false, }, { name: "empty text with regex", field: FieldSchema{Type: Text, Regex: "^.*$"}, value: "", expected: true, }, // List validation { name: "valid string list", field: FieldSchema{Type: List}, value: []string{"a", "b"}, expected: true, }, { name: "empty list", field: FieldSchema{Type: List}, value: []string{}, expected: true, }, { name: "invalid list type", field: FieldSchema{Type: List}, value: "not a list", expected: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.expected != tt.field.Validate(tt.value) { t.Errorf("expected %v, got %v", tt.expected, tt.field.Validate(tt.value)) } }) } } func TestSchemaRecordConversion(t *testing.T) { testSchema := Schema{ {Field: "_id", Type: Text, Regex: "^[A-Za-z0-9]+$"}, {Field: "_v", Type: Number, Min: 1}, {Field: "name", Type: Text, Regex: "^[A-Z][a-z]*$"}, {Field: "age", Type: Number, Min: 0, Max: 150}, {Field: "tags", Type: List}, } tests := []struct { name string resource Resource expectedRec Record expectErr bool }{ { name: "valid complete resource", resource: Resource{ "_id": testID, "_v": 1.0, "name": "John", "age": 30.0, "tags": []string{"admin", "user"}, }, expectedRec: Record{ testID, "1", "John", "30", "admin,user", }, expectErr: false, }, { name: "missing optional fields", resource: Resource{ "_id": testID, "_v": 1.0, "name": "John", }, expectedRec: Record{ testID, "1", "John", "0", "", }, expectErr: false, }, { name: "invalid _id format", resource: Resource{ "_id": "?", "_v": 1.0, }, expectErr: true, }, { name: "invalid name regex", resource: Resource{ "_id": testID, "_v": 1.0, "name": "john", // lowercase "age": 30.0, }, expectErr: true, }, { name: "age out of range", resource: Resource{ "_id": testID, "_v": 1.0, "age": 200.0, }, expectErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { rec, err := testSchema.Record(tt.resource) if gotErr := (err != nil); gotErr != tt.expectErr { t.Errorf("expected error %v, got %v", tt.expectErr, err) } else if !slices.Equal(rec, tt.expectedRec) { t.Errorf("expected %v, got %v", tt.expectedRec, rec) } }) } } func TestSchemaResourceConversion(t *testing.T) { testSchema := Schema{ {Field: "_id", Type: Text, Regex: "^[A-Za-z0-9]+$"}, {Field: "_v", Type: Number, Min: 1}, {Field: "name", Type: Text}, {Field: "age", Type: Number}, {Field: "tags", Type: List}, } tests := []struct { name string record Record expectedRes Resource expectErr bool }{ { name: "valid complete record", record: Record{testID, "2", "Alice", "25", "staff,manager"}, expectedRes: Resource{ "_id": testID, "_v": 2.0, "name": "Alice", "age": 25.0, "tags": []string{"staff", "manager"}, }, expectErr: false, }, { name: "invalid record length", record: Record{"ID", "1", "extra"}, expectErr: true, }, { name: "invalid version format", record: Record{testID, "invalid", "Alice", "25"}, expectErr: true, }, { name: "invalid number format", record: Record{testID, "1", "Alice", "notanumber"}, expectErr: true, }, { name: "empty list field", record: Record{testID, "1", "Bob", "40", ""}, expectedRes: Resource{ "_id": testID, "_v": 1.0, "name": "Bob", "age": 40.0, "tags": []string{}, }, expectErr: false, }, { name: "single list item", record: Record{testID, "1", "Charlie", "35", "admin"}, expectedRes: Resource{ "_id": testID, "_v": 1.0, "name": "Charlie", "age": 35.0, "tags": []string{"admin"}, }, expectErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { res, err := testSchema.Resource(tt.record) if tt.expectErr { if err == nil { t.Errorf("expected error but got nil") } return } else if err != nil { t.Errorf("unexpected error: %v", err) } else if len(res) != len(tt.expectedRes) { t.Errorf("expected resource length %d, got %d", len(tt.expectedRes), len(res)) } else { for k, v := range res { if !reflect.DeepEqual(v, tt.expectedRes[k]) { t.Errorf("expected %#v, got %#v", tt.expectedRes[k], v) } } } }) } } func TestSchema_EdgeCases(t *testing.T) { t.Run("empty resource", func(t *testing.T) { schema := Schema{} resource := Resource{} rec := must(schema.Record(resource)).T(t) if len(rec) != 0 { t.Fatal("expected empty record for empty schema and resource, got:", rec) } res := must(schema.Resource(rec)).T(t) if len(res) != 0 { t.Fatal("expected empty resource for empty record, got:", res) } }) t.Run("large numbers", func(t *testing.T) { schema := Schema{{Field: "big", Type: Number}} resource := Resource{"big": math.MaxFloat64} rec := must(schema.Record(resource)).T(t) want := Record{fmt.Sprintf("%g", math.MaxFloat64)} if !slices.Equal(rec, want) { t.Fatalf("expected %v, got %v", want, rec) } }) t.Run("special characters in text", func(t *testing.T) { schema := Schema{{Field: "text", Type: Text}} resource := Resource{"text": "特殊字符 日本語"} rec := must(schema.Record(resource)).T(t) want := Record{"特殊字符 日本語"} if !slices.Equal(rec, want) { t.Fatalf("expected %v, got %v", want, rec) } }) }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
store_test.go
Go
package pennybase import ( "errors" "testing" ) func TestStoreCRUD(t *testing.T) { originalID := ID defer func() { ID = originalID }() tests := []struct { name string operation func(*Store) error wantErr bool postCheck func(*Store) error }{ { name: "Create valid book", operation: func(s *Store) error { ID = func() string { return "test-id-1" } _, err := s.Create("books", Resource{ "title": "The Go Programming Language", "author": "Alan Donovan", "publication_year": 2015.0, "genres": []string{"Programming"}, "isbn": "123-0123456789", }) return err }, wantErr: false, postCheck: func(s *Store) error { res, err := s.Get("books", "test-id-1") if err != nil { return err } if res["title"] != "The Go Programming Language" || res["_v"].(float64) != 1.0 { return errors.New("created book mismatch") } return nil }, }, { name: "Create invalid book (missing title)", operation: func(s *Store) error { _, err := s.Create("books", Resource{ "author": "Anonymous", "publication_year": 2023.0, "genres": []string{"Mystery"}, "isbn": "999-9999999999", }) return err }, wantErr: true, }, { name: "Update book", operation: func(s *Store) error { ID = func() string { return "test-id-2" } _, err := s.Create("books", Resource{ "title": "Original Title", "author": "Author", "publication_year": 2020.0, "genres": []string{"Old"}, "isbn": "111-1111111111", }) if err != nil { return err } return s.Update("books", Resource{ "_id": "test-id-2", "title": "Updated Title", "author": "Author", "publication_year": 2020.0, "genres": []string{"New"}, "isbn": "111-1111111111", }) }, wantErr: false, postCheck: func(s *Store) error { res, err := s.Get("books", "test-id-2") if err != nil { return err } if res["title"] != "Updated Title" || res["_v"].(float64) != 2.0 { return errors.New("update failed") } return nil }, }, { name: "Delete book", operation: func(s *Store) error { ID = func() string { return "test-id-3" } _, err := s.Create("books", Resource{ "title": "To Delete", "author": "Author", "publication_year": 2021.0, "genres": []string{"Temp"}, "isbn": "333-3333333333", }) if err != nil { return err } return s.Delete("books", "test-id-3") }, wantErr: false, postCheck: func(s *Store) error { _, err := s.Get("books", "test-id-3") if err == nil { return errors.New("book not deleted") } return nil }, }, { name: "List books sorted", operation: func(s *Store) error { ID = func() string { return "book1" } _, err := s.Create("books", Resource{ "title": "Book A", "author": "Author A", "publication_year": 2000.0, "genres": []string{"Genre A"}, "isbn": "111-0000000000", }) if err != nil { return err } ID = func() string { return "book2" } _, err = s.Create("books", Resource{ "title": "Book B", "author": "Author B", "publication_year": 2020.0, "genres": []string{"Genre B"}, "isbn": "222-0000000000", }) return err }, wantErr: false, postCheck: func(s *Store) error { books, err := s.List("books", "publication_year") if err != nil || len(books) != 2 { return errors.New("list failed") } if books[0]["publication_year"].(float64) != 2000.0 || books[1]["publication_year"].(float64) != 2020.0 { return errors.New("incorrect sort order") } return nil }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { dir := testData(t, "testdata/basic") store, err := NewStore(dir) if err != nil { t.Fatalf("NewStore: %v", err) } err = tt.operation(store) if (err != nil) != tt.wantErr { t.Errorf("got error %v, wantErr %v", err, tt.wantErr) } if tt.postCheck != nil { if err := tt.postCheck(store); err != nil { t.Errorf("postCheck failed: %v", err) } } }) } }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
testdata/rest/templates/books.html
HTML
{{define "books.html"}} {{range .Store.List "books" ""}} <div class="book">{{.title}} ({{.year}})</div> {{end}} {{end}}
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
util_test.go
Go
package pennybase import ( "os" "testing" ) type mustResult[T any] struct { Val T Err error } func (m mustResult[T]) T(t *testing.T) T { t.Helper() must0(t, m.Err) return m.Val } func must[T any](v T, err error) mustResult[T] { return mustResult[T]{v, err} } func must0(t *testing.T, err error) { t.Helper() if err != nil { t.Fatalf("Expected no error, got: %v", err) } } func testData(t *testing.T, src string) string { t.Helper() dst := t.TempDir() must0(t, os.CopyFS(dst, os.DirFS(src))) return dst }
zserge/pennybase
818
Poor man's Backend-as-a-Service (BaaS), similar to Firebase/Supabase/Pocketbase
Go
zserge
Serge Zaitsev
.eslintrc.js
JavaScript
module.exports = { "env": { "browser": true, "es6": true }, "extends": "eslint:recommended", "globals": { "Atomics": "readonly", "SharedArrayBuffer": "readonly" }, "parserOptions": { "ecmaVersion": 2018 }, "rules": { } };
zserge/q
48
Tiny and simple VueJS clone
JavaScript
zserge
Serge Zaitsev
counter.html
HTML
<html> <style> ul, li { list-style: none; display: inline; } .active { text-decoration: underline; } </style> <body> <div id="counter"> <button q-on:click="clicks++" q-bind:disabled="clicks >= 5">Click me</button> <button q-on:click="clicks=0">Reset</button> <p q-text="`Clicked ${clicks} times`"></p> <ul q-each="[0,1,2,3,4,5]"> <li q-text="$it" q-bind:class="$it == $parent.clicks ? 'active' : ''"></li> </ul> </div> </body> <script src="q.js"></script> <script> Q(counter, {clicks: 0}); </script> </html>
zserge/q
48
Tiny and simple VueJS clone
JavaScript
zserge
Serge Zaitsev
q.js
JavaScript
const call = (expr, ctx) => new Function(`with(this){${`return ${expr}`}}`).bind(ctx)(); const directives = { html: (el, _, val, ctx) => (el.innerHTML = call(val, ctx)), text: (el, _, val, ctx) => (el.innerText = call(val, ctx)), if: (el, _, val, ctx) => (el.hidden = !call(val, ctx)), on: (el, name, val, ctx) => (el[`on${name}`] = () => call(val, ctx)), model: (el, name, val, ctx) => { el.value = ctx[val]; el.oninput = () => (ctx[val] = el.value); }, bind: (el, name, value, ctx) => { const v = call(value, ctx); if (name === 'style') { el.removeAttribute('style'); for (const k in v) { el.style[k] = v[k]; } } else if (name === 'class') { el.setAttribute('class', [].concat(v).join(' ')); } else { v ? el.setAttribute(name, v) : el.removeAttribute(name); } }, each: (el, name, val, ctx) => { const items = call(val, ctx); if (!el.$each) { el.$each = el.children[0]; } el.innerText = ''; for (let it of items) { const childNode = document.importNode(el.$each); const childCtx = {$parent: ctx, $it: it}; childNode.$q = childCtx; Q(childNode, childCtx); el.appendChild(childNode); } }, }; let $dep; const walk = (node, q) => { for (const {name, value} of node.attributes) { if (name.startsWith('q-')) { const [directive, event] = name.substring(2).split(':'); const d = directives[directive]; $dep = () => d(node, event, value, q); $dep(); $dep = undefined; } } for (const child of node.children) { if (!child.$q) { walk(child, q); } } }; const proxy = q => { const deps = {}; for (const name in q) { deps[name] = []; let prop = q[name]; Object.defineProperty(q, name, { get() { if ($dep) { deps[name].push($dep); } return prop; }, set(value) { prop = value; if (!name.startsWith('$')) { for (const dep of deps[name]) { dep(value); } } }, }); } return q; }; const Q = (el, q) => walk(el, proxy(q));
zserge/q
48
Tiny and simple VueJS clone
JavaScript
zserge
Serge Zaitsev
q.min.js
JavaScript
let call=(t,e)=>new Function(`with(this){${"return "+t}}`).bind(e)(),directives={html:(t,e,n,o)=>t.innerHTML=call(n,o),text:(t,e,n,o)=>t.innerText=call(n,o),if:(t,e,n,o)=>t.hidden=!call(n,o),on:(t,e,n,o)=>t["on"+e]=()=>call(n,o),model:(t,e,n,o)=>{t.value=o[n],t.oninput=()=>o[n]=t.value},bind:(t,e,n,o)=>{let i=call(n,o);if("style"===e){t.removeAttribute("style");for(let e in i)t.style[e]=i[e]}else"class"===e?t.setAttribute("class",[].concat(i).join(" ")):i?t.setAttribute(e,i):t.removeAttribute(e)},each:(t,e,n,o)=>{let i=call(n,o);t.$each||(t.$each=t.children[0]),t.innerText="";for(let e of i){let n=document.importNode(t.$each),i={$parent:o,$it:e};n.$q=i,Q(n,i),t.appendChild(n)}}};let $dep;let walk=(t,e)=>{for(let{name:n,value:o}of t.attributes)if(n.startsWith("q-")){let[i,l]=n.substring(2).split(":"),s=directives[i];$dep=()=>s(t,l,o,e),$dep(),$dep=void 0}for(let n of t.children)n.$q||walk(n,e)},proxy=t=>{let e={};for(let n in t){e[n]=[];let o=t[n];Object.defineProperty(t,n,{get:()=>($dep&&e[n].push($dep),o),set(t){if(o=t,!n.startsWith("$"))for(let o of e[n])o(t)}})}return t},Q=(t,e)=>walk(t,proxy(e));
zserge/q
48
Tiny and simple VueJS clone
JavaScript
zserge
Serge Zaitsev
test.js
JavaScript
const assert = require('assert'); const jsdom = require('jsdom'); const fs = require('fs'); // Global map of tests const $ = {}; $['call'] = () => { assert.equal(call('2+3', null), 5); assert.equal(call('a', {a:42}), 42); assert.equal(call('a+b', {a:1, b: 2}), 3); assert.equal(call('Math.pow(2, a)', {a: 3}), 8); global.FOO = 'hello' assert.equal(call('FOO', {}), 'hello'); }; $['proxy:simple'] = () => { const a = proxy({x: 1, y: 2}); let called = 0; let testCallback = () => called++; $dep = testCallback; a.x; // subscribe to "x" assert.equal(called, 0); a.x = 1; assert.equal(called, 1); a.x = 'foo'; assert.equal(called, 2); a.y = 'first'; assert.equal(called, 2); a.y; // subscribe to "y" a.y = 'second'; assert.equal(called, 3); }; $['Q:simple'] = () => { const model = {name: 'John'}; const view = ` <main> <p q-text="name"></p> </main> `; const el = new jsdom.JSDOM(view).window.document.querySelector('main'); Q(el, model); assert.equal(el.querySelector('p').innerText, 'John'); model.name = 'Jane'; assert.equal(el.querySelector('p').innerText, 'Jane'); }; // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Try running "+" tests only, otherwise run all tests, skipping "-" tests. if ( Object.keys($) .filter(t => t.startsWith('+')) .map(t => $[t]()).length == 0 ) { for (let t in $) { if (t.startsWith('-')) { console.log('SKIP:', t); } else { console.log('TEST:', t); $[t](); } } }
zserge/q
48
Tiny and simple VueJS clone
JavaScript
zserge
Serge Zaitsev
todo.html
HTML
<html> <style> ul, li { list-style: none; } .done { text-decoration: line-through; } </style> <body> <div id="app"> <input q-model="draft" /> <button q-on:click="addTask(draft)" q-bind:disabled="!draft.length">Add task</button> <button q-on:click="deleteCompleted()" q-bind:disabled="tasks.length == 0">Delete completed</button> <ul q-each="tasks"> <li q-text="$it.name" q-bind:class="$it.done ? 'done': null" q-on:click="$it.done = !$it.done" ></li> </ul> </div> </body> <script src="q.js"></script> <script> const todo = { draft: '', addTask: name => { todo.tasks = [...todo.tasks, proxy({name, done: false})]; todo.draft = ''; }, deleteCompleted: () => { todo.tasks = todo.tasks.filter(t => !t.done); }, tasks: [{name:'foo', done: true},{name:'bar',done:false}].map(proxy), }; Q(app, todo); </script> </html>
zserge/q
48
Tiny and simple VueJS clone
JavaScript
zserge
Serge Zaitsev
tab.c
C
#include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define C4 60 /* Tabs support a range C3..B6, C4 is a middle C reference */ static char *RST = "\x1b[0m"; /* Normal style */ static char *TXT = "\x1b[37m"; /* Text: white */ static char *DIM = "\x1b[35m"; /* Dimmed: magenta */ static char *ACC = "\x1b[1;33m"; /* Accent: bold yellow */ static char *ERR = "\x1b[31m"; /* Error: red */ static char INDENT[100] = {0}; static char VINDENT[100] = {0}; static char *SHARP = "♯"; static char *VLINE = "│"; static char *HLINE = "─"; static char *DLINE = "┊"; static char *FE = "○"; static char *FF = "●"; static char *FL = "◐"; static char *FR = "◑"; static char *FT = "◕"; static char *FQ = "◔"; static char *FB = "◒"; static char *FU = "◓"; static char *FO = "▼"; static char *FP = "+"; static char *FES = "◦"; static char *FFS = "•"; static void decolorize(void) { RST = TXT = DIM = ACC = ERR = ""; } static void asciify(void) { SHARP = "#"; VLINE = "|"; HLINE = "-"; DLINE = ":"; FE = "o"; FF = "x"; FL = "<"; FR = ">"; FT = "^"; FB = "v"; FQ = "~"; FU = "@"; FO = "+"; FP = "+"; FES = "."; FFS = "*"; } #define NLINES 10 /* Max height of a multi-line buffer */ #define LINESZ 1024 /* Max width of a multi-line buffer */ static char ln[NLINES][LINESZ]; /* Multiline buffer, global for all renderers */ struct instr { void (*reset)(void *); void (*sym)(void *, int); void (*note)(void *, int); void *ctx; }; /* Like snprintf, but to append a formatted string */ static void strcatf(const char *ln, const char *fmt, ...) { va_list va; int n = strlen(ln); va_start(va, fmt); vsnprintf((char *)ln + n, LINESZ - n - 1, fmt, va); va_end(va); } int isempty(const char *s) { return s[strspn(s, " \n")] == '\0'; } /* ------------------- String fretted instruments ------------------------- */ struct frets { int n; /* Number of strings */ char *tuning; /* One letter per string */ char *frets; /* Fret labels, e.g. 0 1 2 3 4 5 6 7..., optional */ int roots[NLINES]; /* Note numbers for each open string */ int hasnotes; }; static void frets_reset(void *ctx) { int i; struct frets *f = (struct frets *)ctx; f->hasnotes = 0; for (i = 0; i < f->n; i++) { snprintf(ln[i], LINESZ - 1, "%s%c%s-%s", DIM, f->tuning[i], VLINE, RST); } } static void frets_sym(void *ctx, int c) { int i; struct frets *f = (struct frets *)ctx; if (c == '\n') { if (f->hasnotes) { for (i = 0; i < f->n; i++) { printf("%s%s\n", INDENT, ln[i]); } frets_reset(f); } } else if (c == ' ') { for (i = 0; i < f->n; i++) { strcatf(ln[i], "%s--%s", DIM, RST); } } else if (c == '|') { for (i = 0; i < f->n; i++) { strcatf(ln[i], "%s%s-%s", DIM, VLINE, RST); } } } static void frets_note(void *ctx, int n) { int i; struct frets *f = (struct frets *)ctx; int index = -1; int fret = -1; f->hasnotes = 1; for (i = 0; i < f->n; i++) { int j = n - f->roots[i]; if (j >= 0 && (fret == -1 || j <= fret)) { index = i; fret = j; } } if (index == -1) { for (i = 0; i < f->n; i++) { strcatf(ln[i], "%sx%s-%s", ERR, DIM, RST); } } else { char fretsym[LINESZ] = {0}; if (f->frets) { char labels[LINESZ], *c, *p; strncpy(labels, f->frets, LINESZ - 1); for (c = p = labels; *c; c++) { if (*c == ' ') { *c = 0; if (fret-- == 0) { strncpy(fretsym, p, LINESZ - 1); break; } p = c + 1; } } } else { snprintf(fretsym, LINESZ - 1, "%d", fret); } for (i = 0; i < f->n; i++) { if (index != i) { strcatf(ln[i], "%s%s%s", DIM, strlen(fretsym) == 1 ? "--" : "---", RST); } else if (fretsym[0]) { strcatf(ln[i], "%s%s%s-%s", ACC, fretsym, DIM, RST); } else { strcatf(ln[i], "%sx%s-%s", ERR, fretsym, DIM, RST); } } } } /* TODO: support diatonic instruments: canjo, Seagull Guitar */ /* TODO: 5-string banjo */ /* TODO: Balalaika */ struct frets frets_diddley = {1, "C", NULL, {C4}, 0}; struct frets frets_gd = {2, "gD", NULL, {C4 + 7, C4 + 2}, 0}; struct frets frets_gc = {2, "gD", NULL, {C4 + 7, C4}, 0}; struct frets frets_cbg = {3, "gDG", NULL, {C4 + 7, C4 + 2, C4 - 5}, 0}; struct frets frets_uke = {4, "AECg", NULL, {C4 + 9, C4 + 4, C4, C4 + 7}, 0}; struct frets frets_mandolin = {4, "EADG", NULL, {C4 + 16, C4 + 9, C4 + 2, C4 - 5}, 0}; struct frets frets_guitar = { 6, "eBGDAE", NULL, {C4 + 16, C4 + 11, C4 + 7, C4 + 2, C4 - 3, C4 - 8}, 0}; struct frets frets_violin = { 4, "EADG", "0 L1 1 L2 2 3 H3 4 H4", {C4 + 16, C4 + 9, C4 + 2, C4 - 5}, 0}; static struct instr diddley = {frets_reset, frets_sym, frets_note, &frets_diddley}; static struct instr gd = {frets_reset, frets_sym, frets_note, &frets_gd}; static struct instr gc = {frets_reset, frets_sym, frets_note, &frets_gc}; static struct instr cbg = {frets_reset, frets_sym, frets_note, &frets_cbg}; static struct instr uke = {frets_reset, frets_sym, frets_note, &frets_uke}; static struct instr mandolin = {frets_reset, frets_sym, frets_note, &frets_mandolin}; static struct instr guitar = {frets_reset, frets_sym, frets_note, &frets_guitar}; static struct instr violin = {frets_reset, frets_sym, frets_note, &frets_violin}; /* -------------- Flutes, Brass, Woodwinds ------------------- */ struct flute { int n; /* number of rows in a tab */ int w; /* width of a single tab */ int k; /* key of the instrument */ int r; /* range of the instrument in semitones */ const char *charts[64]; /* All possible fingering charts, each NxW chars */ }; static void flute_reset(void *ctx) { int i; struct flute *flute = (struct flute *)ctx; for (i = 0; i < flute->n; i++) { ln[i][0] = 0; } } static void flute_sym(void *ctx, int c) { int i; struct flute *flute = (struct flute *)ctx; switch (c) { case ' ': for (i = 0; i < flute->n; i++) strcatf(ln[i], " "); break; case '|': for (i = 0; i < flute->n; i++) strcatf(ln[i], "%s ", VLINE); break; case '\n': for (i = 0; i < flute->n; i++) printf("%s%s\n", INDENT, ln[i]); flute_reset(ctx); break; } } static void flute_note(void *ctx, int c) { int i; struct flute *flute = (struct flute *)ctx; const char *fingering; if (c < flute->k || c >= flute->k + flute->r) { for (i = 0; i < flute->n; i++) { strcatf(ln[i], "%s%s%s", ERR, "x ", RST); } return; } fingering = flute->charts[c - flute->k]; for (i = 0; i < flute->n * flute->w; i++) { char *s = ln[i / flute->w]; switch (fingering[i]) { case 'B': strcatf(s, "%s%s%s", DIM, FFS, RST); break; case 'X': strcatf(s, "%s%s%s", ACC, FFS, RST); break; case 'O': strcatf(s, "%s%s%s", ACC, FES, RST); break; case 'x': strcatf(s, "%s%s%s", ACC, FF, RST); break; case 'o': strcatf(s, "%s%s%s", ACC, FE, RST); break; case 'l': strcatf(s, "%s%s%s", ACC, FL, RST); break; case 'r': strcatf(s, "%s%s%s", ACC, FR, RST); break; case 'u': strcatf(s, "%s%s%s", ACC, FU, RST); break; case 'b': strcatf(s, "%s%s%s", ACC, FB, RST); break; case 'q': strcatf(s, "%s%s%s", ACC, FQ, RST); break; case 'Q': strcatf(s, "%s%s%s", ACC, FT, RST); break; case 'k': strcatf(s, "%s%s%s", DIM, FO, RST); break; case '+': strcatf(s, "%s%s%s", DIM, FP, RST); break; default: strcatf(s, "%s%c%s", DIM, fingering[i], RST); break; } if (i % flute->w == flute->w - 1) { strcatf(s, " "); } } } /* TODO: more ocarina types TODO: Traverse flute TODO: Clarinet, Oboe, Duduk? TODO: Bansuri? Quena? Shakuhachi? */ /* Recorder German */ struct flute flute_german = { 8, /* 8 rows: 7 holes + octave */ 1, /* 1 column */ C4, /* C-4 */ 27, /* Octaves + 1 higher notes */ { "Xxxxxxxx", /* C-4 */ "Xxxxxxxl", /* C#4 */ "Xxxxxxxo", /* D-4 */ "Xxxxxxlo", /* D#4 */ "Xxxxxxoo", /* E-4 */ "Xxxxxooo", /* F-4 */ "Xxxxoxxx", /* F#4 */ "Xxxxoooo", /* G-4 */ "Xxxoxxlo", /* G#4 */ "Xxxooooo", /* A-4 */ "Xxoxxooo", /* A#4 */ "Xxoooooo", /* B-4 */ "Xoxooooo", /* C-5 */ "Oxxooooo", /* C#5 */ "Ooxooooo", /* D-5 */ "Ooxxxxxo", /* D#5 */ "Bxxxxxoo", /* E-5 */ "Bxxxxooo", /* F-5 */ "Bxxxoxox", /* F#5 */ "Bxxxoooo", /* G-5 */ "Bxxxoxxx", /* G#5 */ "Bxxooooo", /* A-5 */ "Bxxoxxxo", /* A#5 */ "Bxxoxxoo", /* B-5 */ "Bxooxxoo", /* C-6 */ "Bxrxxoxx", /* C#6 */ "Bxoxxoxl", /* D-6 */ }, }; /* Recorder Baroque */ struct flute flute_baroque = { 8, /* 8 rows: 7 holes + octave */ 1, /* 1 column */ C4, /* C-4 */ 27, /* Octaves + 1 higher notes */ { "Xxxxxxxx", /* C-4 */ "Xxxxxxxl", /* C#4 */ "Xxxxxxxo", /* D-4 */ "Xxxxxxlo", /* D#4 */ "Xxxxxxoo", /* E-4 */ "Xxxxxoxx", /* F-4 */ "Xxxxoxxo", /* F#4 */ "Xxxxoooo", /* G-4 */ "Xxxoxxlo", /* G#4 */ "Xxxooooo", /* A-4 */ "Xxoxxooo", /* A#4 */ "Xxoooooo", /* B-4 */ "Xoxooooo", /* C-5 */ "Oxxooooo", /* C#5 */ "Ooxooooo", /* D-5 */ "Ooxxxxxo", /* D#5 */ "Bxxxxxoo", /* E-5 */ "Bxxxxoxo", /* F-5 */ "Bxxxoxoo", /* F#5 */ "Bxxxoooo", /* G-5 */ "Bxxoxooo", /* G#5 */ "Bxxooooo", /* A-5 */ "Bxxoxxxo", /* A#5 */ "Bxxoxxoo", /* B-5 */ "Bxooxxoo", /* C-6 */ "Bxrxxoxx", /* C#6 */ "Bxoxxoxl", /* D-6 */ }, }; /* Irish Tin Whistle in D */ struct flute flute_tinwhistle = { 7, /* 4 rows: 6 holes + overblow */ 1, /* 1 column */ C4 + 2, /* D-4 */ 25, /* Octaves + 1 higher notes */ { "xxxxxx ", /* D-4 */ "xxxxxl ", /* D#4 */ "xxxxxo ", /* E-4 */ "xxxxlo ", /* F-4 */ "xxxxoo ", /* F#4 */ "xxxooo ", /* G-4 */ "xxlooo ", /* G#4 */ "xxoooo ", /* A-4 */ "xoxxxx ", /* A#4 */ "xooooo ", /* B-4 */ "oxxooo ", /* C-5 */ "oooooo ", /* C#5 */ "oxxxxx ", /* D-5 */ "xxxxxl+", /* D#5 */ "xxxxxo+", /* E-5 */ "xxxxlo+", /* F-5 */ "xxxxoo+", /* F#5 */ "xxxooo+", /* G-5 */ "xxlooo+", /* G#5 */ "xxoooo+", /* A-5 */ "xoxxxx+", /* A#5 */ "xooooo+", /* B-5 */ "oxxooo+", /* C-6 */ "oooooo+", /* C#6 */ "oxxxxx+", /* D-6 */ }, }; /* Pendant Ocarina in C (4 holes + 2 optional octave holes)*/ struct flute flute_pendant = { 3, /* 3 rows: 2x2 holes + 1 octave row */ 4, /* 4 cols: octave keys are drawn somewhat apart */ C4, /* Key of C */ 17, /* One octave + 4 higher notes */ { " xx xx ", /* C-4 */ " xr xx ", /* C#4 */ " xo xx ", /* D-4 */ " xx xr ", /* D#4 */ " xx xo ", /* E-4 */ " xo xo ", /* F-4 */ " ox xx ", /* F#4 */ " oo xx ", /* G-4 */ " ox xo ", /* G#4 */ " oo xo ", /* A-4 */ " oo ox ", /* A#4 */ " ox oo ", /* B-4 */ " oo oo ", /* C-5 */ " oo ox x o", /* C#5 */ " oo oo x o", /* D-5 */ " oo ox o o", /* D#5 */ " oo oo o o", /* E-5 */ }, }; /* Xaphoon (Pocket Sax) in C */ struct flute flute_xaphoon = { 9, /* 8 rows + 1 octave row */ 1, /* 4 cols: octave keys are drawn somewhat apart */ C4, /* Key of C */ 25, /* Two octaves + 1 Do */ { "Xxxxxxxxx", /* C-4 */ "Xxxxxxxxl", /* C#4 */ "Xxxxxxxxo", /* D-4 */ "Xxxxxxxox", /* D#4 */ "Xxxxxxxoo", /* E-4 */ "Xxxxxxooo", /* F-4 */ "Xxxxxoxxx", /* F#4 */ "Xxxxxoooo", /* G-4 */ "Xxxxoxxxo", /* G#4 */ "Xxxxooooo", /* A-4 */ "Xxxoooooo", /* A#4 */ "Xxoxxxooo", /* B-4 */ "Xxooooooo", /* C-5 */ "Oxxxxoooo", /* C#5 */ "Oxooooooo", /* D-5 */ "Xoxxxoooo", /* D#5 */ "Xoooooooo", /* E-5 */ "Ooooooooo", /* F-5 */ "Xoxxxxxxx", /* F#5, lowered by lip pressure */ "Xoxxxxxxx", /* G-5 */ "Xoxxxxxxl", /* G#5 */ "Xxxxxxxxo", /* A-5 */ "Xxxxxxxoo", /* A#5 */ "Xxxxxxooo", /* B-5 */ "Xxxxxoooo", /* C-6 */ }, }; /* Alto Saxophone in Bb */ struct flute flute_sax = { 8, /* 7 rows: 3+3+1 buttons and a delimiter */ 3, /* 3 columns: octave key, main keys, additional keys */ C4 - 2, /* Bb */ 32, /* 2 octaves + 6 lower notes + 1 higher */ { " x x x -b x x x b ", /* A#3 */ " x x x -l x x x b ", /* B-3 */ " x x x - x x x b ", /* C-4 */ " x x x -r x x x b ", /* C#4 */ " x x x - x x x ", /* D-4 */ " x x x - x x x u ", /* D#4 */ " x x x - x x o ", /* E-4 */ " x x x - x o o ", /* F-4 */ " x x x - o x o ", /* F#4 */ " x x x - o o o ", /* G-4 */ " x x x -u o o o ", /* G#4 */ " x x o - o o o ", /* A-4 */ " x o o - x o o ", /* A#4 */ " x o o - o o o ", /* B-4 */ " o x o - o o o ", /* C-5 */ " o o o - o o o ", /* C#5 */ "kx x x - x x x ", /* D-5 */ "kx x x - x x x u ", /* D#5 */ "kx x x - x x o ", /* E-5 */ "kx x x - x o o ", /* F-5 */ "kx x x - o x o ", /* F#5 */ "kx x x - o o o ", /* G-5 */ "kx x x -u o o o ", /* G#5 */ "kx x o - o o o ", /* A-5 */ "kx o o - x o o ", /* A#5 */ "kx o o - o o o ", /* B-5 */ "ko x o - o o o ", /* C-6 */ "ko o o - o o o ", /* C#6 */ "kxr x x - x x x b ", /* D-6 */ "kxQ x x - x x x b ", /* D#6 */ "kxQ x x - lx x x b ", /* E-6 */ "kxx x x - lx x x b ", /* F-6 */ }, }; /* Trumpet in Bb */ struct flute flute_trumpet = { 4, /* 4 rows: Partial note + 3 buttons */ 1, /* 1 column */ C4 - 6, /* F#3 */ 31, /* 2 octaves + 6 lower notes + 1 higher */ { "Cxxx", /* F#3 - 1st partial */ "Cxox", /* G-3 */ "Coxx", /* G#3 */ "Cxxo", /* A-3 */ "Cxoo", /* A#3 */ "Coxo", /* B-3 */ "Cooo", /* C-4 */ "Gxxx", /* C#4 - 2nd partial */ "Gxox", /* D-4 */ "Goxx", /* D#4 */ "Gxxo", /* E-4 */ "Gxoo", /* F-4 */ "Goxo", /* F#4 */ "Gooo", /* G-4 */ "coxx", /* G#4 - 3rd partial */ "cxxo", /* A-4 */ "cxoo", /* A#4 */ "coxo", /* B-4 */ "cooo", /* C-5 */ "exxo", /* C#5 - 4th partial */ "exoo", /* D-5 */ "eoxo", /* D#5 */ "eooo", /* E-5 */ "gxoo", /* F-5 - 5th partial */ "goxo", /* F#5 */ "gooo", /* G-5 */ "+oxx", /* G#5 - 7th partial (6th is too flat)*/ "+xxo", /* A-5 */ "+xoo", /* A#5 */ "+oxo", /* B-5 */ "+ooo", /* C-6 */ }, }; /* Native American Flute in A (6 holes)*/ struct flute flute_naf6 = { 6, /* 6 rows, no overblow */ 1, /* 1 column */ C4 - 3, /* A-4 */ 18, /* One octave + 6 higher notes */ { "xxxxxx", /* A-3 */ "xxxxxQ", /* A#3 */ "xxxxxl", /* B-3 */ "xxxxxo", /* C-4 */ "xxxxox", /* C#4 */ "xxxxoo", /* D-4 */ "xxxoxo", /* D#4 */ "xxxooo", /* E-4 */ "xxoxoo", /* F-4 */ "xxoooo", /* F#4 */ "xoxooo", /* G-5 */ "oxxooo", /* G#5 */ "ooxooo", /* A-5 */ "oxxxxx", /* A#5 */ "rxxxxl", /* B-5 */ "rxxxxo", /* C-6 */ "rxxxlo", /* C#5 */ "rxxxoo", /* D-6 */ }, }; /* Native American Flute in A (5 holes)*/ struct flute flute_naf5 = { 5, /* 6 rows, no overblow */ 1, /* 1 column */ C4 - 3, /* A-4 */ 18, /* One octave + 6 higher notes */ { "xxxxx", /* A-3 */ "xxxxQ", /* A#3 */ "xxxxl", /* B-3 */ "xxxxo", /* C-4 */ "xxxox", /* C#4 */ "xxxoo", /* D-4 */ "xxoxo", /* D#4 */ "xxooo", /* E-4 */ "xoxox", /* F-4 */ "xoxoo", /* F#4 */ "xoooo", /* G-5 */ "ooxoo", /* G#5 */ "ooooo", /* A-5 */ "oxxxx", /* A#5 */ "rxxxl", /* B-5 */ "rxxxo", /* C-6 */ "rxxlo", /* C#5 */ "rxxoo", /* D-6 */ }, }; /* Native American Flute in A (4 holes)*/ struct flute flute_naf4 = { /* A:ACDEG, E:EGABD etc */ 5, /* 4 rows + overblow */ 1, /* 1 column */ C4 - 3, /* A-4 */ 18, /* One octave + 4 higher notes */ { "xxxx ", /* A-3 */ "xxxQ ", /* A#3 */ "xxxl ", /* B-3 */ "xxxo ", /* C-4 */ "xxox ", /* C#4 */ "xxoo ", /* D-4 */ "xoxo ", /* D#4 */ "xooo ", /* E-4 */ "oxxo ", /* F-4 */ "qxoo ", /* F#4 */ "ooox ", /* G-5 */ "oooo ", /* G#5 */ "oxxx+", /* A-5 */ "xxxQ+", /* A#5 */ "xxxl+", /* B-5 */ "xxxo+", /* C-6 */ "xxlo+", /* C#5 */ "xxoo+", /* D-6 */ }, }; struct instr german = {flute_reset, flute_sym, flute_note, &flute_german}; struct instr baroque = {flute_reset, flute_sym, flute_note, &flute_baroque}; struct instr tinwhistle = {flute_reset, flute_sym, flute_note, &flute_tinwhistle}; struct instr xaphoon = {flute_reset, flute_sym, flute_note, &flute_xaphoon}; struct instr pendant = {flute_reset, flute_sym, flute_note, &flute_pendant}; struct instr trumpet = {flute_reset, flute_sym, flute_note, &flute_trumpet}; struct instr sax = {flute_reset, flute_sym, flute_note, &flute_sax}; struct instr naf = {flute_reset, flute_sym, flute_note, &flute_naf6}; struct instr naf5 = {flute_reset, flute_sym, flute_note, &flute_naf5}; struct instr naf4 = {flute_reset, flute_sym, flute_note, &flute_naf4}; /* --------------------- Harmonica ----------------------- */ struct harp { int k; /* key */ int r; /* range in semitones */ char *layout; }; static void harp_reset(void *ctx) { (void)ctx; ln[0][0] = 0; } static void harp_sym(void *ctx, int c) { switch (c) { case ' ': strcatf(ln[0], " "); break; case '|': strcatf(ln[0], "%s%s %s", DIM, VLINE, RST); break; case '\n': printf("%s%s\n", INDENT, ln[0]); harp_reset(ctx); break; } } static void harp_note(void *ctx, int c) { int i; char *p; struct harp *harp = (struct harp *)ctx; if (c < harp->k || c >= harp->k + harp->r) { strcatf(ln[0], "%s%s %s", ERR, "x", RST); return; } p = harp->layout; for (i = c - harp->k; i > 0; i--) { p = p + strlen(p) + 1; } strcatf(ln[0], "%s%s %s", ACC, p, RST); } struct harp d_harp = { C4, 37, /* Octave 4 */ "+1\0-1'\0-1\0+1'\0+2\0-2\"\0-2'\0-2\0-3\"\0-3\"\0-3'\0-3\0" /* Octave 5 */ "+4\0-4'\0-4\0+4'\0+5\0-5\0+5'\0+6\0-6'\0-6\0+6'\0-7\0" /* Octave 6 */ "+7\0-7'\0-8\0+8'\0+8\0-9\0+9'\0+9\0-9'\0-10\0+10\"\0+10'\0+10\0-10'", }; struct harp c_harp = { C4, 38, /* Octave 4 */ "+1\0+1^\0-1\0-1^\0+2\0-2\0-2^\0+3\0+3^\0-3\0-3^\0-4\0" /* Octave 5 */ "+5\0+5^\0-5\0-5^\0+6\0-6\0-6^\0+7\0+7^\0-7\0-7^\0-8\0" /* Octave 6 */ "+9\0+9^\0-9\0-9^\0+10\0-10\0-10^\0+11\0+11^\0-11\0-11^\0-12\0+12\0+12^", }; struct instr diatonic = {harp_reset, harp_sym, harp_note, &d_harp}; struct instr chromatic = {harp_reset, harp_sym, harp_note, &c_harp}; /* ---------------------- Jianpu ------------------------- */ struct jianpu { int hasln[3]; }; static void jianpu_reset(void *ctx) { int i; struct jianpu *jianpu = (struct jianpu *)ctx; for (i = 0; i < 3; i++) { jianpu->hasln[i] = 0; ln[i][0] = 0; } } static void jianpu_sym(void *ctx, int c) { int i; struct jianpu *jianpu = (struct jianpu *)ctx; switch (c) { case '\n': for (i = 0; i < 3; i++) { if (jianpu->hasln[i]) printf("%s%s\n", INDENT, ln[i]); } jianpu_reset(ctx); break; case ' ': for (i = 0; i < 3; i++) strcatf(ln[i], " "); break; case '|': strcatf(ln[0], " "); strcatf(ln[1], "%s| %s", DIM, RST); strcatf(ln[2], " "); break; } } static void jianpu_note(void *ctx, int c) { struct jianpu *jianpu = (struct jianpu *)ctx; int n = c % 12; int o = c / 12; char *hoct = " .:>>>>"; char *loct = "<<<<* "; char *acc = " # # # # # "; char *note = "112234455667"; int isacc = acc[n] == '#'; jianpu->hasln[1] = 1; if (hoct[o] != ' ') jianpu->hasln[0] = 1; if (loct[o] != ' ') jianpu->hasln[2] = 1; strcatf(ln[0], "%s%s%c%s ", ACC, isacc ? " " : "", hoct[o], RST); strcatf(ln[1], "%s%s%c%s ", ACC, isacc ? SHARP : "", note[n], RST); strcatf(ln[2], "%s%s%c%s ", ACC, isacc ? " " : "", loct[o], RST); } struct jianpu jnpu = {0}; struct instr jianpu = {jianpu_reset, jianpu_sym, jianpu_note, &jnpu}; /* ----------------------- Klavarscribo -------------------------- */ struct klavar { int n; int root; }; static int isacc[] = {0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0}; static void klavar_reset(void *ctx) { (void)ctx; } static void klavar_sym(void *ctx, int c) { struct klavar *klavar = (struct klavar *)ctx; int i; char *fill = " "; if (c == ' ') fill = " "; if (c == '|') fill = HLINE; if (c == '\n') return; printf("%s", INDENT); for (i = 0; i < klavar->n; i++) { printf("%s%s%s", (i % 12 == 0 ? ACC : DIM), (isacc[i % 12] ? VLINE : i % 12 == 0 ? DLINE : fill), RST); } printf("\n"); } static void klavar_note(void *ctx, int c) { int i; struct klavar *klavar = (struct klavar *)ctx; printf("%s", INDENT); for (i = 0; i < klavar->n; i++) { char *fill = " "; char *color = i % 12 == 0 ? ACC : DIM; if (c == i + klavar->root) { fill = isacc[i % 12] ? FE : FF; color = ACC; } else { fill = isacc[i % 12] ? VLINE : i % 12 == 0 ? DLINE : " "; } printf("%s%s%s", color, fill, RST); } printf("\n"); } struct klavar pianofull = {48, C4 - 12}; struct klavar pianotoy = {25, C4}; struct instr piano = {klavar_reset, klavar_sym, klavar_note, &pianofull}; struct instr toy = {klavar_reset, klavar_sym, klavar_note, &pianotoy}; /* ---------------- Kalimba -------------------- */ struct kalimba { int n; int left; int intervals[32]; int marks[32]; }; static void kalimba_reset(void *ctx) { (void)ctx; } static void kalimba_sym(void *ctx, int c) { int i; struct kalimba *kalimba = (struct kalimba *)ctx; char *fill = DLINE; if (c == '\n') return; if (c == '|') fill = HLINE; printf("%s", INDENT); for (i = 0; i < kalimba->n; i++) { printf("%s%s%s", DIM, kalimba->marks[i] ? VLINE : fill, RST); } printf("\n"); } static void kalimba_note(void *ctx, int c) { int i; struct kalimba *kalimba = (struct kalimba *)ctx; int tin = kalimba->left; printf("%s", INDENT); for (i = 0; i < kalimba->n; i++) { char *fill = kalimba->marks[i] ? VLINE : DLINE; char *color = DIM; if (c == tin) { fill = FF; color = ACC; } else if (isacc[c % 12] && (c == tin - 1 || c == tin + 1)) { fill = FE; color = DIM; } printf("%s%s%s", color, fill, RST); tin = tin + kalimba->intervals[i]; } printf("\n"); } struct kalimba klmb17 = { 17, C4 + 26, /* d' b g e c A F D C E G B d f a c' e' */ {-3, -4, -3, -4, -3, -4, -3, -2, 4, 3, 4, 3, 3, 4, 3, 4, 0}, {0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0}, }; struct kalimba klmb21 = { 21, C4 + 26, /* d' b g e c A F D B G F A C E G B d f a c' e' */ {-3, -4, -3, -4, -3, -4, -3, -3, -4, -2, 4, 3, 4, 3, 4, 3, 3, 4, 3, 4, 0}, {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0}, }; struct instr kalimba17 = {kalimba_reset, kalimba_sym, kalimba_note, &klmb17}; struct instr kalimba21 = {kalimba_reset, kalimba_sym, kalimba_note, &klmb21}; /* ---------------- TODO: Piano tabs like guiar -------------------- */ static int note(char c) { const int N[] = {9, 11, 0, 2, 4, 5, 7}; if ((c >= 'A' && c <= 'G') || (c >= 'a' && c <= 'g')) { return C4 + N[tolower(c) - 'a'] + (12 * (c >= 'a')); } return 0; } static void tabs_abc(FILE *f, struct instr *instr, int transpose) { char line[LINESZ]; while (fgets(line, sizeof(line), f)) { char *p; int acc = 0; int isabc = 1, q = 0; /* Tell text/meta/lyrics from music notation lines */ for (p = line; *p; p++) { if (*p == '"') { q = !q; } else if (!q && !isspace(*p) && !ispunct(*p) && !note(*p) && !isdigit(*p) && *p != 'z') { isabc = 0; break; } } if (!isabc) { printf("%s%s%s%s", INDENT, TXT, line, RST); continue; } if (isempty(line)) { printf("\n"); continue; } /* Render a note */ q = 0; instr->reset(instr->ctx); for (p = line; *p; p++) { int n; char c = *p; if (c == '"') { q = !q; /* TODO: maybe support chords output, too? Mind transposing! */ } else if (c == '\n') instr->sym(instr->ctx, '\n'); else if (isspace(c)) instr->sym(instr->ctx, ' '); else if (c == '|') instr->sym(instr->ctx, '|'); else if (c == '_') acc--; else if (c == '^') acc++; n = note(c); if (!q && n) { while (*p) { int nc = *++p; switch (nc) { case '#': acc = acc + 1; break; case '\'': acc = acc + 12; break; case ',': acc = acc - 12; break; default: p--; goto out; } } out: instr->note(instr->ctx, n + transpose + acc); acc = 0; } } } /* Final row may be without a newline, flush it */ instr->sym(instr->ctx, '\n'); } static struct { const char *name; const char *descr; struct instr *instr; } INST[] = { /* String */ {"guitar", "6-string Guitar Tabs", &guitar}, {"uke", "Ukulele Tabs", &uke}, {"mandolin", "Mandolin Tabs", &mandolin}, {"cbg", "Cigar Box Guitar (GDg tuning)", &cbg}, {"diddley", "Diddley Bow (Unitar)", &diddley}, {"2gd", "Two-string Diddley Bow (G+D)", &gd}, {"2gc", "Two-string Diddley Bow (G+C)", &gc}, {"violin", "Violin Tabs", &violin}, /* Woodwind+Brass */ {"recorder", "Recorder (German System)", &german}, {"german", "Recorder (German System)", &german}, {"baroque", "Recorder (Baroque/English System)", &baroque}, {"english", "Recorder (Baroque/English System)", &baroque}, {"whistle", "Irish Tin Whistle in D", &tinwhistle}, {"xaphoon", "Xaphoon (Pocket Sax)", &xaphoon}, {"pendant", "Pendant Ocarina (4-hole)", &pendant}, {"naf", "Native American Flute in A (6-hole)", &naf}, {"naf6", "Native American Flute in A (6-hole)", &naf}, {"naf5", "Native American Flute in A (5-hole)", &naf5}, {"naf4", "Native American Flute in A (minor pentatonic, 4-hole)", &naf4}, {"trumpet", "Trumbet", &trumpet}, {"sax", "Alto Saxophone (Eb)", &sax}, /* Harmonicas */ {"harp", "Diatonic Harmonica", &diatonic}, {"diatonic", "Diatonic Harmonica", &diatonic}, {"chromatic", "Chromatic Harmonica", &chromatic}, /* Keys */ {"piano", "Klavarscribo for 48-key piano", &piano}, {"toy", "Toy 25-key piano", &toy}, {"kalimba", "Kalimba (17 keys)", &kalimba17}, {"kalimba21", "Kalimba (21 keys)", &kalimba21}, /* Other */ {"jianpu", "Chinese Numeric Notation", &jianpu}, {"123", "Chinese Numeric Notation", &jianpu}, }; static void usage(const char *argv0) { unsigned int i; fprintf(stderr, "USAGE: %s [-i inst] [-t steps] [file ...]\n", argv0); fprintf(stderr, "\nOptions:\n\n"); fprintf(stderr, " -i NAME\tSpecify the instrument for rendering tabs (see below)\n"); fprintf(stderr, " -t NUM\tTranspose the music by NUM semitones\n"); fprintf(stderr, " -c \tForce colored output\n"); fprintf(stderr, " -C \tDisable colored output\n"); fprintf(stderr, " -a \tDisable unicode (use ASCII)\n"); fprintf(stderr, " -h \tShow this help\n"); fprintf(stderr, "\nInstruments:\n\n"); for (i = 0; i < sizeof(INST) / sizeof(INST[0]); i++) { fprintf(stderr, " * %-10s\t%s\n", INST[i].name, INST[i].descr); } fprintf(stderr, "\n"); } int main(int argc, char *argv[]) { int c; int found = 0; int colorize = 0; int transpose = 0; int padding = 2; unsigned int t; char *endp; struct instr *instr = &guitar; while ((c = getopt(argc, argv, "hCcai:p:t:")) != -1) { switch (c) { case 'c': colorize = 1; break; case 'C': decolorize(); break; case 'a': asciify(); break; case 'i': for (t = 0; t < sizeof(INST) / sizeof(INST[0]); t++) { if (strcmp(INST[t].name, optarg) == 0) { instr = INST[t].instr; found = 1; break; } } if (!found) { fprintf(stderr, "Unknown instrument: %s\n", optarg); return 1; } break; case 't': transpose = strtol(optarg, &endp, 0); if (endp == optarg || *endp != '\0') { fprintf(stderr, "%s: -t requires a number, got %s\n", argv[0], optarg); return 1; } if (transpose < -24 || transpose > 24) { fprintf(stderr, "%s: invalid transpose, should be -24..+24\n", argv[0]); return 1; } break; case 'p': padding = strtol(optarg, &endp, 0); if (endp == optarg || *endp != '\0') { fprintf(stderr, "%s: -I requires a number, got %s\n", argv[0], optarg); return 1; } if (padding < 0 || padding > 99) { fprintf(stderr, "%s: invalid padding, should be 0..99\n", argv[0]); return 1; } break; default: usage(argv[0]); return 1; } } if ((!isatty(STDOUT_FILENO) || (getenv("NO_COLOR") != NULL && strcmp(getenv("NO_COLOR"), "0"))) && !colorize) { decolorize(); } memset(VINDENT, '\n', padding / 2); /* terminal fonts usually have 2:1 proportions */ memset(INDENT, ' ', padding); if (optind == argc) { printf("%s", VINDENT); tabs_abc(stdin, instr, transpose); } else { int i; for (i = optind; i < argc; i++) { FILE *f = fopen(argv[i], "r"); if (f == NULL) { perror("fopen"); return 1; } printf("%s", VINDENT); tabs_abc(f, instr, transpose); fclose(f); } } return 0; }
zserge/tab
41
🎼 A tiny CLI tool to render tabs for music instruments (🎹🎷🎺🎸🪕🪈 and many others!)
C
zserge
Serge Zaitsev
apl.py
Python
#!/usr/bin/env python3 # # This is an implementation of k/simple language (https://github.com/kparc/ksimple/) in Python # K/simple is a subset of K langauge, which belongs to the APL family, together with J and Q. # This program illustrates how array languages work. # import sys, re, functools, itertools G = {} # global vars def a(x): return type(x) == int # is atom? def err(msg="nyi"): raise f"error: {msg}" # well, error def sub(x): return -x if a(x) else list(map(lambda xi: -xi, x)) # negate atom or every element in list def iota(x): return list(range(0, x)) if a(x) else err("rank/iota") # iota 1..x or rank error for lists def rank(x): return err("rank/rank") if a(x) else len(x) # length of list, or rank error def cat(x): return [x] if a(x) else x # atom to list, or return list unchanged def rev(x): return err("rank/rev") if a(x) else list(reversed(x)) # reverse list, or rank error # dyad is a helper for high-level verbs. # if x and y are both atoms: return "x OP y" # if x is atom and y is a vector: flip them (operators are assumed to be commutative) # if x is a vector and y is an atom: apply "x OP y" for every element of x # if both are vectors (of the same length!) - apply OP pairwise def dyad(x, y, op): if a(x): return op(x, y) if a(y) else dyad(y, x, op) elif a(y): return list(map(lambda n: op(n, y), x)) elif len(x) != len(y): err("rank/opx") else: return list(map(lambda n: op(n[0], n[1]), zip(x, y))) def Add(x, y): return dyad(x, y, lambda x, y: x + y) def And(x, y): return dyad(x, y, lambda x, y: x & y) def Or(x, y): return dyad(x, y, lambda x, y: x | y) def Not(x, y): return dyad(x, y, lambda x, y: int(x != y)) def Eq(x, y): return dyad(x, y, lambda x, y: int(x == y)) def Prod(x, y): return dyad(x, y, lambda x, y: x * y) def Sub(x, y): return Add(x, sub(y)) def Mod(x, y): return err("rank") if not a(x) else y % x if a(y) else list(map(lambda y: y % x, y)) def Take(x, y): return err("rank") if not a(x) else [y]*x if a(y) else y[:x] def Cat(x, y): return cat(x) + cat(y) def At(x, y): return x[y] if a(y) else list(map(lambda y: x[y], y)) def at(x): return At(x, 0) def Over(op, x): return functools.reduce(lambda a, b: op(a, b), x) def Scan(op, x): return list(itertools.accumulate(x, lambda a, b: op(a, b))) V = {"+": (err, Add), "-": (sub, Sub), "!": (iota, Mod), "#": (rank, Take), ",": (cat, Cat), "@": (at, At), "=": (err, Eq), "~": (err, Not), "&": (err, And), "|": (rev, Or), "*": (err, Prod)} def e(s): m = re.match(r"(?P<id>[a-zA-Z]+)|(?P<num>[0-9]+)|(?P<op>[-+!#,@=~&|*])", s) if not m: err(f"syntax: {s}") elif m.lastgroup == "id" or m.lastgroup == "num": x = int(s[: m.end()]) if m.lastgroup == "num" else G.get(s[: m.end()], 0) # a noun if m.end() == len(s): return x # if last in the string: return it if s[m.end()] == ":": # if assignment: recursively evaluate the rest and assign a global x = e(s[m.end() + 1 :]) G[s[: m.end()]] = x return x return V[s[m.end()]][1](x, e(s[m.end() + 1 :])) # otherwise: apply dyadic function else: # If adverb (scan/over): evaluate the rest and apply verb to the resulting noun if len(s) > 1 and s[1] in "/\\": return (Over if s[1] == "/" else Scan)(V[s[0]][1], e(s[2:])) # Otherwise: apply a monadic verb to the rest of the expression return V[s[0]][0](e(s[1:])) [print(e(line.split(";", 1)[0].strip().replace(" ", ""))) for line in sys.stdin if line.strip()]
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
asm.py
Python
#!/usr/bin/env python3 import types,dis,sys # A minimal two-pass assembler for CPythin VM bytecode. It can handle assembly # instructions (simple and extended BINARY_OPs), constants, variables and # labels. Assembly source file is read from stdin until EOF. Resulting # function is compiled and executed immediately after. # Some CPython VM opcodes, feel free to extend these OPS = {'LOAD_CONST':100,'LOAD_FAST':124,'STORE_FAST':125,'RETURN_VALUE':83,'JUMP_FORWARD':110,'JUMP_BACKWARD':140,'POP_JUMP_IF_FALSE':114,'POP_JUMP_IF_TRUE':115,'BINARY_OP':122} # BINARY_OP parameters for arithmetic operations BINOPS = {'ADD':0,'SUBTRACT':10,'MULTIPLY':5,'DIVIDE':3} # Two-pass assembler def assemble(code): bytecode, consts, vars, labels = [], [], [], {} pos = 0 # First pass: handle constants, variables and label addresses for line in code.split('\n'): parts = line.strip().split() if not parts: continue instr = parts[0] if instr.endswith(':'): labels[instr[:-1]] = pos elif instr == 'CONST': consts.append(int(parts[1])) elif instr == 'VAR': vars.append(parts[1]) else: pos += 2 if instr not in BINOPS else 4 # Second pass: translate instructions to bytecode 1:1 and fill in labels for line in code.split('\n'): parts = line.strip().split() if not parts: continue instr = parts[0] if instr.endswith(':') or instr == 'CONST' or instr == 'VAR': continue arg = parts[1] if len(parts) > 1 else 0 # Replace labels with addresses if isinstance(arg, str) and arg in labels: if labels[arg] < len(bytecode): arg = (len(bytecode)-labels[arg])/2+1 else: arg = (labels[arg]-len(bytecode))/2-1 if instr in BINOPS: # BINARY_OP is a 4-byte command with a 2-byte parameter bytecode.append(OPS['BINARY_OP']) bytecode.append(BINOPS[instr]&255) bytecode.append(BINOPS[instr]>>8&255) bytecode.append(0) else: bytecode.append(OPS[instr]) bytecode.append(int(arg)) return tuple(consts), tuple(vars), bytes(bytecode) code = ''.join([line for line in sys.stdin]) consts, v, bytecode = assemble(code) code_obj = types.CodeType(0,0,0,len(v),128,64,bytecode,consts,(),v,'asm','mod','',1,b'',b'') # Optionally, disassemble the bytecode for debugging # dis.dis(ff) print(types.FunctionType(code_obj, {})())
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
basic.py
Python
#!/usr/bin/env python3 import sys code, vars = {}, {"#": 0} def num(s): n = 0 while s and s[0].isdigit(): n, s = n * 10 + int(s[0]), s[1:] return n, s.strip() def expr(s): res, s = term(s); op = "" while s and s[0] in "+-": op = s[0]; n, s = term(s[1:]) res += n if op == "+" else -n return res, s def term(s): res, s = factor(s) while s and s[0] in "*/": op = s[0]; n, s = factor(s[1:]) res *= n if op == "*" else 1 / n if n != 0 else 0 return res, s def factor(s): if s and s[0] == "(": res, s = expr(s[1:]); return res, s[1:] elif s and s[0].isdigit(): return num(s) else: i = 0 while i < len(s) and s[i].isalnum(): i += 1 return vars.get(s[:i], 0), s[i:] def stmt(s): def do_if(s): n, ln = expr(s) if n: stmt(ln) while s != None: cmd = s.split(None, 1) vars["#"] += 1 if vars["#"] else 0 ops = { "rem": lambda args: None, "bye": lambda args: sys.exit(0), "list": lambda args: print("\n".join([f"{n:3} {ln}" for (n, ln) in sorted(code.items()) if ln])), "print": lambda args: print(args[1:-1] if args and args[0] == '"' else expr(args)[0]), "input": lambda args: vars.update({args[0]: int(input("] "))}), "goto": lambda args: vars.update({"#": expr(args)[0]}), "if": lambda args: do_if(args), "run": lambda args: vars.update({"#": 1}), } if cmd and cmd[0].lower() in ops: ops[cmd[0].lower()](cmd[1] if len(cmd) > 1 else "") elif s: assign = s.split("=", 1); vars[assign[0]], _ = expr(assign[1]) if vars["#"] <= 0: break vars["#"], s = next(((n, ln) for (n, ln) in sorted(code.items()) if n >= vars["#"]), (0, None)) for line in sys.stdin: lineno, line = num(line) code[lineno] = line.strip() if lineno else stmt(line)
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
factorial/fac.asm
Assembly
CONST 1 CONST 10 VAR n VAR result LOAD_CONST 0 # result = 1 STORE_FAST 0 # store in result LOAD_CONST 1 # n = CONST[1] (change this to calculate factorial of different numbers) STORE_FAST 1 # store in n loop: LOAD_FAST 1 # load n POP_JUMP_IF_FALSE end # if n == 0, jump to end LOAD_FAST 0 # load result LOAD_FAST 1 # load n MULTIPLY 0 # result *= n STORE_FAST 0 # store result LOAD_FAST 1 # load n LOAD_CONST 0 # load 1 SUBTRACT 0 # n -= 1 STORE_FAST 1 # store n JUMP_BACKWARD loop # jump to start of loop end: LOAD_FAST 0 # load result RETURN_VALUE 0 # return result
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
factorial/fac.lsp
Common Lisp
(label fac (lambda (x) (cond ((eq x 0) 1) (1 (* x (fac (- x 1))))))) (fac 1) (fac 2) (fac 3) (fac 4) (fac 5) (fac 6) (fac 7) (fac 8) (fac 9) (fac 10)
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
factorial/fac.pas
Pascal
var n, f; begin n := 10; f := 1; while n > 0 do begin f := f * n; n := n - 1; end; ! f end.
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
lisp.py
Python
#!/usr/bin/env python3 import sys # Very simple lexer, split by parens and whitespace def lex(code): return code.replace("(", " ( ").replace(")", " ) ").split() # A simple parser: build nested lists from nested parenthesis def parse(tokens): t = tokens.pop(0) if t == "(": sexp = [] while tokens[0] != ")": sexp.append(parse(tokens)) tokens.pop(0) return sexp try: return int(t) except: return t # # Add (x, y) pair to list L: # # pairlis([3], [4], []) -> [[3, 4]] # pairlis([1, 2, 3], [4, 5, 6], [[7, 8]]) -> [[1, 4], [2, 5], [3, 6], [7, 8]] # def pairlis(x, y, L): return L if not x else [[x[0], y[0]]] + pairlis(x[1:], y[1:], L) # # Find value in associated list L by key x: # # L = [["foo", 12], ["bar", 42], ["baz", 123]] # assoc("bar", L) -> 42 # def assoc(x, L): return [] if not L else L[0][1] if L[0][0] == x else assoc(x, L[1:]) # # Atom is not a list, or an empty list (nil) # atom([]) -> t # atom(42) -> t # atom([42, 'a']) -> [] # def atom(x): return "t" if type(x) != type([]) or len(x) == 0 else [] # # apply[fn;x;a] = # [atom[fn] → [eq[fn;CAR] → caar[x]; # eq[fn;CDR] → cdar[x]; # eq[fn;CONS] → cons[car[x];cadr[x]]; # eq[fn;ATOM] → atom[car[x]]; # eq[fn;EQ] → eq[car[x];cadr[x]]; # T → apply[eval[fn;a];x;a]]; # eq[car[fn];LAMBDA] → eval[caddr[fn]; pairlis[cadr[fn];x;a]]]; # def apply(f, args, L): if f == "atom": return atom(args[0]) elif f == "car": return args[0][0] elif f == "cdr": return args[0][1:] elif f == "cons": return [args[0]] + args[1] elif f == "eq": return "t" if atom(args[0]) and args[0] == args[1] else [] elif f == "+": return args[0] + args[1] elif f == "-": return args[0] - args[1] elif f == "*": return args[0] * args[1] elif f == "/": return args[0] / args[1] elif f[0] == "lambda": return eval(f[2], pairlis(f[1], args, L)) else: return apply(eval(f, L), args, L) # Evaluate "cond" def evcon(x, L): return [] if len(x) == 0 else eval(x[0][1], L) if eval(x[0][0], L) else evcon(x[1:], L) # Evaluate list of lambda arguments def evlis(x, L): return [eval(x[0], L)] + evlis(x[1:], L) if x else [] # # McCarthy's eval from the paper: # # eval[e;a] = # [atom[e] → cdr[assoc[e;a]]; # atom[car[e]] → # [eq[car[e],QUOTE] → cadr[e]; # eq[car[e];COND] → evcon[cdr[e];a]; # T → apply[car[e];evlis[cdr[e];a];a]]; # T → apply[car[e];evlis[cdr[e];a];a]] # # ...with a few additions: nil, t, symbols and label # def eval(x, L): if x == "nil": return [] elif x == "t" or type(x) == int: return x elif type(x) == str: return assoc(x, L) elif x[0] == "quote": return x[1] elif x[0] == "cond": return evcon(x[1:], L) elif x[0] == "label": L.insert(0, [x[1], x[2]]); return x[1] else: return apply(x[0], evlis(x[1:], L), L) G = [] [print(eval(parse(lex(line.split(";", 1)[0])), G)) for line in sys.stdin if line.strip()]
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
mouse.py
Python
#!/usr/bin/env python3 import sys # Returns a position in string "s" of the unmatched delimiter "r" (skipping nested l+r pairs) # # skip("2+(3+(4+5)))+6", "(", ")") -> 12 ("+6") # skip("a [ b [] [] c]] d []", "[", "]") -> 16 (" d []") # def skip(s, l, r): return next(i + 1 for i, c in enumerate(s) if (c == r and (s[:i].count(l) - s[:i].count(r)) == 0)) def mouse(s): # We need to store macro definitons (they don't shadow variables), # data stack, return stack and memory for variables. # "i" is a code pointer, offset if the start of the first local variable # "A" in current environment (environments can be nested, so inner # function's "A" becomes 26, the other inner starts with 52 etc. defs, ds, rs, data, i, offset = {}, [], [], [0] * 200, 0, 0 # First we loop over code and store starting addresses of all macros for n, c in enumerate(s): if c == "$": defs[s[n + 1]] = n + 2 while i < len(s) and s[i] != "$": # Skip whitespace if s[i] in " \t\r\n]$": pass # Skip comments till the end of line elif s[i] == "'": i += s[i + 1 :].find("\n") # Parse numbers into integers elif s[i].isdigit(): n = 0 while s[i].isdigit(): n = n * 10 + ord(s[i]) - ord("0"); i = i + 1 i = i - 1; ds.append(n) # Put variable address on data stack elif s[i] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": ds.append(ord(s[i]) - ord("A") + offset) # Read user input as a number elif s[i] == "?": ds.append(num(input("> "))) # Print value from data stack as a number elif s[i] == "!": print(ds.pop(), end="") # Print a literal string, "!" is newline elif s[i] == '"': j = skip(s[i + 1 :], '"', '"'); print(s[i + 1 : i + j].replace("!", "\n"), end=""); i = i + j # Common arithmetics and comparison (note the lack of == and != operators elif s[i] == "+": ds.append(ds.pop() + ds.pop()) elif s[i] == "-": ds.append(-ds.pop() + ds.pop()) elif s[i] == "*": ds.append(ds.pop() * ds.pop()) elif s[i] == "/": ds.append(int(1 / (ds.pop() / ds.pop()))) elif s[i] == ">": ds.append(int(ds.pop() < ds.pop())) elif s[i] == "<": ds.append(int(ds.pop() > ds.pop())) # Fetch/dereference variable elif s[i] == ".": ds.append(data[ds.pop()]) # Store value into a variable elif s[i] == "=": x = ds.pop(); data[ds.pop()] = x # If data stack has non-positive value: execute the block, otherwise skip it elif s[i] == "[": i += skip(s[i + 1 :], "[", "]") if ds.pop() <= 0 else 0 # Start of the loop: store it in return stack elif s[i] == "(": rs.append(("LOOP", i, offset)) # Loop condition: if condition is non-positive - continue, otherwise skip until pairing ")" elif s[i] == "^": if ds.pop() <= 0: _, i, _ = rs.pop(); i += skip(s[i + 1 :], "(", ")") # End of loop: return to its start (which is stored on return stack) elif s[i] == ")": _, i, offset = rs[-1] # Call a macro: save current code pointer and variable offset, jump to the start of the macro elif s[i] == "#": if s[i + 1] in defs: rs.append(("MACRO", i, offset)); i = defs[s[i + 1]]; offset = offset + 26 else: i += skip(s[i + 1 :], "#", ";") # End of macro: return to the macro call address and ignore until the last parameter (";") elif s[i] == "@": _, i, offset = rs.pop(); i += skip(s[i + 1 :], "#", ";") # Macro parameter delimiter: return back to the macro and continue execution from there elif s[i] == "," or s[i] == ";": _, i, offset = rs.pop() # Macro parameter inside macro: jump to the matching value from the macro call elif s[i] == "%": pn = ord(s[i + 1])-ord("A")+1; rs.append(("PARAM", i + 1, offset)); pb, tmp = 1, len(rs) - 1 while pb: tmp = tmp - 1; tag, nn, off = rs[tmp] if tag == "MACRO": pb = pb - 1 elif tag == "PARAM": pb = pb + 1 _, i, offset = rs[tmp] while i < len(s) and pn and s[i] != ";": i = i + 1 if s[i] == "#": i += skip(s[i:], "#", ";") if s[i] == ",": pn = pn - 1 if s[i] == ";": _, i, offset = rs.pop() i = i + 1 mouse("\n".join([line for line in sys.stdin]))
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
pl0.py
Python
#!/usr/bin/env python3 import re, sys, operator def parse(code): tok = ""; kind = ""; code = code + ";" # force terminate code to trick look-ahead lexer # A simple regex-based lexer for PL/0, cuts one token from the string def lex(expected=None, when=None): nonlocal code, tok, kind if when and tok != when: return False if expected and kind != expected: raise SyntaxError(f"Expected {expected} but got {kind}") m = re.match(r"(?P<num>[0-9]+)|(?P<op>[-+*/()<>=])|(?P<ws>\s+)|(?P<kw>begin|end\.|end|if|then|while|do|var|!|\?|call|procedure)|(?P<id>[a-zA-Z]+)|(?P<semi>;)|(?P<asgn>:=)|(?P<comma>,)", code) if not m: raise SyntaxError("unexpected character") tok = code[:m.end()]; kind = m.lastgroup; code = code[m.end():]; return kind != "ws" or lex() def block(): var, proc = [], [] # var <name> , ... ; while lex("kw", "var"): while not lex("semi", ";"): var.append(tok); lex("id"); lex("comma", ",") # procedure <name> ; begin ... end; while lex('kw', 'procedure'): n=tok; lex('id'); lex('semi'); proc.append((n, block())); lex('semi') # begin ... end (statement) return 'block',var,proc,stmt() def stmt(): # <id> := <expr> if kind == "id": n = tok; lex("id"); lex("asgn"); return "asgn", n, expr() # call <id> elif tok == "call": lex("kw"); n = tok; lex("id"); return "call", n # ? <id> elif tok == "?": lex("kw"); n = tok; lex("id"); return "read", n # ! <expr> elif tok == "!": lex("kw"); return "write", expr() # begin <stmt...> end elif tok == "begin": lex("kw"); body = [] while tok != "end" and tok != "end.": body.append(stmt()); lex("semi", ";") lex("kw"); return "begin", body # if <cond> then <stmt> # while <cond> do <stmt> elif tok == "if" or tok == "while": cond = tok; lex("kw"); e = expr(); op = tok; lex("op"); c = ("op", op, e, expr()); lex("kw"); return (cond, c, stmt()) def expr(tokens="+-", term=lambda: expr("*/", factor)): e = term() while tok in tokens: op = tok; lex("op"); e = ("op", op, e, term()) return e def factor(): if kind == "id": n = tok; lex("id"); return ("id", n) elif kind == "num": num = tok; lex("num"); return int(num) elif tok == "(": lex("op"); e = expr(); lex("op"); return e lex(); return block() def eval(node, scope=(None, {}, {})): def find(x, i=1, frame=scope): return frame[i] if x in frame[i] else find(x, i, frame[0]) if type(node) is int: return node elif node[0] == "id": return find(node[1], 1)[node[1]] elif node[0] == "asgn": env = find(node[1], 1); env[node[1]] = eval(node[2], scope) elif node[0] == "begin": any(eval(n, scope) and False for n in node[1]) elif node[0] == "read": env = find(node[1], 1); env[node[1]] = int(input("> ")) elif node[0] == "op": return {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.floordiv, "<": operator.lt, ">": operator.gt, "=": operator.eq}[node[1]](eval(node[2], scope), eval(node[3], scope)) elif node[0] == "if": _ = eval(node[1], scope) and eval(node[2], scope) elif node[0] == "while": any(eval(node[2], scope) and False for _ in iter(lambda: bool(eval(node[1], scope)), False)) elif node[0] == "write": print(eval(node[1], scope)) elif node[0] == "block": eval(node[3], (scope, {v: 0 for v in node[1]}, {p[0]: p[1] for p in node[2]})) elif node[0] == "call": eval(find(node[1], 2)[node[1]], scope) return 0 eval(parse("\n".join([line for line in sys.stdin])))
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
tcl.py
Python
#!/usr/bin/env python3 import sys, re, operator G = {} def tcl_m(op): return lambda a: str(int(op(int(a[0]), int(a[1])))) def tcl_puts(a): s = " ".join(a); print(s); return s def tcl_set(a): G.update({a[0]: a[1]}) if len(a) > 1 else ""; return G.get(a[0], "") def tcl_while(a): while int(tcl_eval(a[0])): tcl_eval(a[1]) FN = { "#": lambda a: "", "puts": tcl_puts, "+": tcl_m(operator.add), "*": tcl_m(operator.mul), "<=": tcl_m(operator.le), "set": tcl_set, "while": tcl_while, } def tcl_tok(code): if code[0] == "$": return "$" + tcl_tok(code[1:]) elif code[0] in ";\n": return ";" elif code[0] == " ": return re.match(r"\s*", code).group(0) elif code[0] in "{[": level, i = 1, 1 while level > 0 and i < len(code): if code[i] in "}]": level = level - 1 elif code[i] in "{[": level = level + 1 i = i + 1 return code[:i] else: return re.match(r"[^;${}\[\]\n ]*", code).group(0) def tcl_subst(s): if s and s[0] == "{": return s[1:-1] elif s and s[0] == "$": return tcl_eval("set " + s[1:] + ";") elif s and s[0] == "[": return tcl_eval(s[1:-1] + ";") return s def tcl_eval(code): args, r = [""], "" while code: tok = tcl_tok(code) code = code[len(tok) :] if tok[0] == " ": args = (args + [""]) if args[0] else args elif tok != ";": args[-1] += tcl_subst(tok) if (tok == ";" or code == "") and len(args) > 0: r = FN[args[0]](args[1:]) if args[0] in FN else "" args = [""] return r tcl_eval("\n".join([line for line in sys.stdin]))
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
test/test.lsp
Common Lisp
nil ; [] 42 ; 42 (quote 42) ; 42 (quote (a b)) ; ['a', 'b'] (quote ()) ; [] (+ 2 3) ; 5 (+ 2 (* 5 7)) ; 37 (atom 42) ; t (atom (quote t)) ; t (atom (quote foo)) ; t (atom (quote (foo bar))); [] (atom (quote ())) ; t (atom (quote (atom (quote a)))) ; [] (eq (quote a) (quote a)) ; t (eq (quote (a b)) (quote (a b))) ; [] (eq (quote ()) (quote ())) ; t (eq (quote a) (quote b)) ; [] (eq (+ 2 4) (* 2 3)) ; t (car (quote (a b c))) ; a (cdr (quote (a b c))) ; ['b', 'c'] (car (cdr (quote (a b c)))) ; b (car (cdr (cdr (quote (a b c))))) ; c (cons (quote a) (quote (b c))) ; ['a', ['b', 'c']] (cons (quote a) (cons (quote b) (cons (quote c) nil))) ; ['a', 'b', 'c'] (cond ((eq (quote a) (quote b)) (quote first)) ((atom (quote a)) (quote second))) ; second (cond ((eq (quote a) (quote a)) (quote first)) ((atom (quote a)) (quote second))) ; first ((lambda (a b) (+ a b)) 2 3) ; 5 ((lambda (x) (cons x (quote (b)))) (quote a)) ; ['a', 'b'] (label five 5) ; five five ; 5 (label add (lambda (a b) (+ a b))) ; add (add 3 five) ; 8
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
test/test.pas
Pascal
var max, arg, ret; var foo; procedure isprime; var i; begin ret := 1; i := 2; while i < arg do begin if arg / i * i = arg then begin ret := 0; i := arg; end; i := i + 1; end; end; procedure primes; begin arg := 2; while arg < max do begin call isprime; if ret = 1 then ! arg; arg := arg + 1; end; end; begin max := 100; call primes; end.
zserge/tinylangs
350
Real programming languages in 50 lines of code
Python
zserge
Serge Zaitsev
c/tinysh.c
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> /* Display prompt */ static void prompt() { write(2, "$ ", 2); } /* Display error message, optionally - exit */ static void err(int retval, int fatal) { if (retval < 0) { write(2, "?\n", 2); if (fatal) { exit(1); } } } /* Helper functions to detect token class */ static int is_delim(int c) { return c == 0 || c == '|'; } static int is_redir(int c) { return c == '>' || c == '<'; } static int is_blank(int c) { return c == ' ' || c == '\t' || c == '\n'; } static int is_special(int c) { return is_delim(c) || is_redir(c) || is_blank(c); } /* Recursively run right-most part of the command line printing output to the * `t` file descriptor */ static void run(char *c, int t) { char *redir_stdin = NULL; char *redir_stdout = NULL; int pipefds[2] = {0, 0}; int outfd = 0; char *v[99] = {0}; char **u; u = &v[98]; /* end of words */ for (;;) { c--; if (is_delim(*c)) { /* if NIL (start of string) or pipe: break */ break; } if (!is_special(*c)) { /* Copy word of regular chars into previous u */ c++; *c = 0; /* null-terminate */ for (; !is_special(*--c);) { } *--u = ++c; } /* If < or > */ if (is_redir(*c)) { if (*c == '<') { redir_stdin = *u; } else { redir_stdout = *u; } if (u - v != 98) { u++; } } } if (u - v == 98) { /* empty input */ return; } if (strcmp(*u, "cd") == 0) { err(chdir(u[1]), 0); return; /* actually, should run() again */ } if (*c) { pipe(pipefds); outfd = pipefds[1]; /* write end of the pipe */ } int pid = fork(); if (pid) { /* Parent or error */ err(pid, 1); if (outfd) { run(c, outfd); /* parse the rest of the cmdline */ close(outfd); /* close output fd */ close(pipefds[0]); /* close read end of the pipe */ } wait(0); return; } if (outfd) { dup2(pipefds[0], 0); /* dup read fd to stdin */ close(pipefds[0]); /* close read fd */ close(outfd); /* close output */ } if (redir_stdin) { close(0); /* replace stdin with redir_stdin */ err(open(redir_stdin, 0), 1); } if (t) { dup2(t, 1); /* replace stdout with t */ close(t); } if (redir_stdout) { close(1); err(creat(redir_stdout, 438), 1); /* replace stdout with redir_stdout */ } err(execvp(*u, u), 1); } int main() { for (;;) { prompt(); char q[512] = {0}; /* input buffer */ char *c = q; if (fgets(c + 1, sizeof(q) - 1, stdin) == NULL) { exit(0); } /* skip to end of line */ for (; *++c;) { } run(c, 0); } }
zserge/tinysh
98
Tiny UNIX shell, de-obfuscated, modernized, and "rewritten in Rust".
C
zserge
Serge Zaitsev
orig/tbr.c
C
#define D ,close( char *c,q [512 ],m[ 256 ],*v[ 99], **u, *i[3];int f[2],p;main (){for (m[m [60]= m[62 ]=32 ]=m[* m=124 [m]= 9]=6; e(-8) ,gets (1+( c=q) )|| exit (0); r(0,0) )for( ;*++ c;); }r(t, o){ *i=i [2]= 0;for (u=v +98 ;m[*--c] ^9;m [*c] &32 ?i[*c &2]= *u,u- v^98 &&++u: 3 )if(!m[*c]){for(*++c=0;!m[*--c];); * --u= ++c;}u-v^98?strcmp(*u,"cd")?*c?pipe(f),o=f[ 1 ]: 4 ,(p=fork())?e(p),o?r(o,0)D o)D*f): 1 ,wait(0):(o?dup2(*f,0)D*f)D o):*i? 5 D 0),e(open(*i,0)): 9 ,t?dup2(t,1)D t):i[ 2 ]? 6 D 1),e(creat(i[2],438)): 5 ,e(execvp(*u,u))):e(chdir(u[1])*2): 3 ;}e(x){x<0?write(2,"?\n$ "-x/4,2),x+1||exit(1): 5 ;}
zserge/tinysh
98
Tiny UNIX shell, de-obfuscated, modernized, and "rewritten in Rust".
C
zserge
Serge Zaitsev
src/main.rs
Rust
use std::fs::File; use std::io::Write; use std::io::{Error, ErrorKind}; use std::process::{Command, Stdio}; use std::{env, io}; #[derive(Debug, Clone)] enum Token { Blank, Redir(i32), Delim(bool), Normal(char), } fn token(x: Option<&char>) -> Token { match x { Some(&c) => match c { '|' => Token::Delim(true), '<' => Token::Redir(0), '>' => Token::Redir(1), ' ' | '\t' | '\n' | '\r' => Token::Blank, _ => Token::Normal(c), }, None => Token::Delim(false), } } fn run<I>(mut it: std::iter::Peekable<I>, output: Stdio) -> Result<(), Error> where I: Iterator<Item = char>, { let mut is_pipe = false; let mut args = Vec::<String>::new(); let mut io_in = Stdio::inherit(); let mut io_out = output; while let Some(tok) = it.next() { match token(Some(&tok)) { Token::Delim(p) => { is_pipe = p; break; } Token::Normal(c) => { let mut word = String::new(); word.push(c); while let Token::Normal(c) = token(it.peek()) { it.next(); word.push(c); } args.push(word.chars().rev().collect::<String>()); } Token::Redir(fd) => match args.pop() { Some(path) => match fd { 0 => io_in = Stdio::from(File::open(path)?), 1 => io_out = Stdio::from(File::create(path)?), _ => return Err(Error::new(ErrorKind::Other, "bad redirection fd")), }, None => { return Err(Error::new( ErrorKind::Other, "redirection filename expected", )); } }, Token::Blank => {} } } if args.is_empty() { return Ok(()); } args.reverse(); if args[0] == "cd" { let path = args .into_iter() .nth(1) .unwrap_or(env::var("HOME").unwrap_or("/".to_string())); env::set_current_dir(path)?; return Ok(()); } if is_pipe { io_in = Stdio::piped() } let mut args_iter = args.iter(); let pathname = args_iter.next().unwrap(); let mut child = Command::new(pathname) .args(args_iter) .stdin(io_in) .stdout(io_out) .spawn()?; if is_pipe { run(it, Stdio::from(child.stdin.take().unwrap()))?; } child.wait()?; Ok(()) } fn main() { loop { print!("$ "); let _ = io::stdout().flush(); // continue even if flush fails let mut input = String::new(); match io::stdin().read_line(&mut input) { Ok(0) => return, Ok(_) => { if let Err(e) = run(input.chars().rev().peekable(), Stdio::inherit()) { println!("error: {}", e); } } Err(e) => { println!("io error: {}", e); return; } } } }
zserge/tinysh
98
Tiny UNIX shell, de-obfuscated, modernized, and "rewritten in Rust".
C
zserge
Serge Zaitsev
example.html
HTML
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="zine.css" rel="stylesheet"> </head> <body> <main class="zine"> <article> <h1>Header</h1> </article> <article> <p>First page</p> </article> <article> <p>Second page</p> </article> <article> <p>Third page</p> </article> <article> <p>Fourth page</p> </article> <article> <p>Fifth page</p> </article> <article> <p>Sixth page</p> </article> <article> <h1>The end</h1> </article> </main> </body> </html>
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
hollow-men/index.html
HTML
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../zine.css" rel="stylesheet"> <style> @import url('https://fonts.googleapis.com/css2?family=Comforter+Brush&display=swap'); @font-face { font-family: poem-font; src: url(TTWPGOTT.ttf); } h1, span { font-family: "Comforter Brush", cursive; } p, pre { font-family: poem-font, monospace; font-size: 4mm; } </style> <title>Zine: Порожні люди</title> </head> <body> <main class="zine"> <article style="background: url(hollow-men-ua-front.jpg) center center/cover no-repeat; filter: grayscale(0.9) brightness(1.5); "> <h1 style="grid-area: 3/3/7/14; display: flex; justify-content: center; align-items: center; background-color: #222; color: #eee;">Порожні люди</h1> </article> <article> <pre style="grid-area: 1/1/15/21;"> I ми лиш пусті тіла ми всі опудала гнемо додолу спини у головах -- трина сухих голосів в'язка перешіптуємось боязко беззмістовно і напівживо як вітер в засохлих нивах чи лапки щурів на битому склі з порожніх льохів з-під землі вигляд без форми, тіні безбарвні скована воля, жести невправні ті, хто з рішучістю на чолі впав, у царство сну або мрій іду́чи пам'ятайте нас -- якщо й взагалі -- не як втрачені, збурені душі -- як пусті тіла чи опудала </pre> </article> <article> <pre style="grid-area: 1/1/15/21;"> II очей боюся уві сні та мертве королівство мрій мені їх не покаже, ні ті очі -- відблиск на руїнах міста гілок гойдання, вітру кличне гасло ще більш віддалене і урочисте ніж зірка, що вночі погасла дай не наблизитись мені до того королівства мрій дай ми постати у вбранні з хутра круків і пацюків -- і стій собі на костурах у полі віддай мене вітрам на волю, дай ми ** це не остання зустріч в царстві тьми </pre> </article> <article> <pre style="grid-area: 1/1/15/21;"> III тут -- мертва земля. терниста земля. тут кам'яні ідоли сяють від дотику благання слабкої руки тут, де згасають зірки чи правда, що в іншому царстві встають самі, не як ми, тремтіло з губами, що створені для поцілунків, та моляться кам'яним брилам </pre> </article> <article> <pre style="grid-area: 1/1/15/21;"> IV нема тут очей. очей тут немає. лиш впалих зірок хвіст у нашій долині, у мертвій долині розбитих щелеп і втрачених королівств останнє місце зустрічі навпомацки і уникаючи слів разом, біля річки, набряклої після злив. незрячі, хіба знову з'являться очі чи зірка вказівна нам шлях прокладе й троянда столиста, у мрій королівство - єдину надію порожніх людей </pre> </article> <article> <pre style="grid-area: 1/1/15/21;"> V ой терне ж мій, терне, терне зелененький, де ж ти, терне, зиму зимував, що й не розвивався? між думкою й втіленням рухом і вчинком лягає велика Тінь. -- бо Твоє є Царство -- між зачаттям та створенням чуттям і відмовою лягає велика Тінь. -- життя ж бо задовге -- </pre> </article> <article> <pre style="grid-area: 1/1/15/21;"> між бажанням і спазмом правом і існуванням сутністю і занепадом лягає велика Тінь -- бо Твоє є Царство бо Твоє є життя ж бо бо Твоє є... *** ось так згине світ. ось так згине світ. ось так згине світ. не з вибухом. З плачем. -- T. S. Eliot </pre> </article> <article style="background: url(hollow-men-ua-thorn.jpg) center center/cover no-repeat; filter: grayscale(0.9) brightness(1.5);"> </article> </main> </body> </html>
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
mandolin/frets.py
Python
FRETS = [ ["G", "G#", "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G"], ["D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B", "C", "C#", "D"], ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A"], ["E", "F", "F#", "G", "G#", "A", "A#", "B", "C", "C#", "D", "D#", "E"], ] print("""<svg width="80" height="262" viewBox="0 0 80 262" style="font-family: sans-serif; font-size: 7px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <line x1="10" y1="20" x2="10" y2="260" stroke="black" stroke-width="1" /> <line x1="30" y1="20" x2="30" y2="260" stroke="black" stroke-width="1" /> <line x1="50" y1="20" x2="50" y2="260" stroke="black" stroke-width="1" /> <line x1="70" y1="20" x2="70" y2="260" stroke="black" stroke-width="1" /> <rect x="9" y="18" width="62" height="3" fill="black" /> """) for i in range(13): y = (i+1) * 20 print(f"""<line x1="10" y1="{y}" x2="70" y2="{y}" stroke="black" stroke-width="1" />""") for (i, f) in enumerate(FRETS): for (j, n) in enumerate(f): x = 10 + 20 * i y = 10 + 20 * j c = "black" if len(n) == 2 else "#888" print(f"""<g> <circle cx="{x}" cy="{y}" r="7" fill="{c}"></circle> <text x="{x}" y="{y}" text-anchor="middle" alignment-baseline="middle" fill="white" dy="0.3">{n}</text> </g>""") print("""</svg>""")
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
mandolin/index.html
HTML
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../zine.css" rel="stylesheet"> <style> @import url('https://fonts.googleapis.com/css2?family=Zeyada&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Paytone+One&display=swap'); img { width: 100%; height: 100%; object-fit: contain; } h1, h2 { font-family: "Zeyada", cursive; } h1 { font-size: 8mm; } h2 { font-size: 5mm; } p { font-family: "Paytone One", sans-serif; } article > * { align-self: center; justify-self: center; } </style> </head> <body> <main class="zine"> <article style="background: url(mandolin-front.jpg) center center/cover no-repeat; filter: brightness(1.5); "> <h1 style="text-stroke: black; color: black; grid-area:2/6/5/11">Mandolin</h1> </article> <article> <h1 style="grid-area:2/4/4/13; ">Major chords</h1> <h2 style="grid-area:4/2/6/5; ">C</h2> <h2 style="grid-area:4/5/6/8; ">D</h2> <h2 style="grid-area:4/8/6/11; ">E</h2> <h2 style="grid-area:4/11/6/14; ">F</h2> <img src="chords/c.svg" style="grid-area:5/2/9/5" /> <img src="chords/d.svg" style="grid-area:5/5/9/8" /> <img src="chords/e.svg" style="grid-area:5/8/9/11" /> <img src="chords/f.svg" style="grid-area:5/11/9/14" /> <h2 style="grid-area:10/2/12/5; ">G</h2> <h2 style="grid-area:10/5/12/8; ">A</h2> <h2 style="grid-area:10/8/12/11; ">B</h2> <h2 style="grid-area:10/11/12/14; ">C#</h2> <img src="chords/g.svg" style="grid-area:11/2/15/5" /> <img src="chords/a.svg" style="grid-area:11/5/15/8" /> <img src="chords/b.svg" style="grid-area:11/8/15/11" /> <img src="chords/cs.svg" style="grid-area:11/11/15/14" /> <h2 style="grid-area:16/2/18/5; ">D#</h2> <h2 style="grid-area:16/5/18/8; ">F#</h2> <h2 style="grid-area:16/8/18/11; ">G#</h2> <h2 style="grid-area:16/11/18/14; ">A#</h2> <img src="chords/ds.svg" style="grid-area:17/2/21/5" /> <img src="chords/fs.svg" style="grid-area:17/5/21/8" /> <img src="chords/gs.svg" style="grid-area:17/8/21/11" /> <img src="chords/as.svg" style="grid-area:17/11/21/14" /> </article> <article> <h1 style="grid-area:2/4/4/13; ">Minor chords</h1> <h2 style="grid-area:4/2/6/5; ">Cm</h2> <h2 style="grid-area:4/5/6/8; ">Dm</h2> <h2 style="grid-area:4/8/6/11; ">Em</h2> <h2 style="grid-area:4/11/6/14; ">Fm</h2> <img src="chords/cm.svg" style="grid-area:5/2/9/5" /> <img src="chords/dm.svg" style="grid-area:5/5/9/8" /> <img src="chords/em.svg" style="grid-area:5/8/9/11" /> <img src="chords/fm.svg" style="grid-area:5/11/9/14" /> <h2 style="grid-area:10/2/12/5; ">Gm</h2> <h2 style="grid-area:10/5/12/8; ">Am</h2> <h2 style="grid-area:10/8/12/11; ">Bm</h2> <h2 style="grid-area:10/11/12/14; ">C#m</h2> <img src="chords/gm.svg" style="grid-area:11/2/15/5" /> <img src="chords/am.svg" style="grid-area:11/5/15/8" /> <img src="chords/bm.svg" style="grid-area:11/8/15/11" /> <img src="chords/csm.svg" style="grid-area:11/11/15/14" /> <h2 style="grid-area:16/2/18/5; ">D#m</h2> <h2 style="grid-area:16/5/18/8; ">F#m</h2> <h2 style="grid-area:16/8/18/11; ">G#m</h2> <h2 style="grid-area:16/11/18/14; ">A#m</h2> <img src="chords/dsm.svg" style="grid-area:17/2/21/5" /> <img src="chords/fsm.svg" style="grid-area:17/5/21/8" /> <img src="chords/gsm.svg" style="grid-area:17/8/21/11" /> <img src="chords/asm.svg" style="grid-area:17/11/21/14" /> </article> <article> <h1 style="grid-area:2/4/4/13; ">Movable chords</h1> <h2 style="grid-area:4/2/6/5; ">maj</h2> <h2 style="grid-area:4/5/6/8; ">maj</h2> <h2 style="grid-area:4/8/6/11; ">min</h2> <h2 style="grid-area:4/11/6/14; ">min</h2> <img src="chords/xmaj-1.svg" style="grid-area:5/2/9/5" /> <img src="chords/xmaj-2.svg" style="grid-area:5/5/9/8" /> <img src="chords/xmin-1.svg" style="grid-area:5/8/9/11" /> <img src="chords/xmin-2.svg" style="grid-area:5/11/9/14" /> <h2 style="grid-area:10/2/12/5; ">7<sup>th</sup></h2> <h2 style="grid-area:10/5/12/8; ">7<sup>th</sup></h2> <h2 style="grid-area:10/8/12/11; ">m7</h2> <h2 style="grid-area:10/11/12/14; ">m7</h2> <img src="chords/x7-1.svg" style="grid-area:11/2/15/5" /> <img src="chords/x7-2.svg" style="grid-area:11/5/15/8" /> <img src="chords/xm7-1.svg" style="grid-area:11/8/15/11" /> <img src="chords/xm7-2.svg" style="grid-area:11/11/15/14" /> <h2 style="grid-area:16/2/18/5; ">maj7</h2> <h2 style="grid-area:16/5/18/8; ">6<sup>th</sup></h2> <h2 style="grid-area:16/8/18/11; ">dim</h2> <h2 style="grid-area:16/11/18/14; ">aug</h2> <img src="chords/xmaj7.svg" style="grid-area:17/2/21/5" /> <img src="chords/x6.svg" style="grid-area:17/5/21/8" /> <img src="chords/xdim.svg" style="grid-area:17/8/21/11" /> <img src="chords/xaug.svg" style="grid-area:17/11/21/14" /> </article> <article> <h1 style="grid-area:2/4/4/13; ">Scales</h1> <h2 style="grid-area:6/2/8/5; ">Major</h2> <h2 style="grid-area:6/5/8/8; ">Minor</h2> <h2 style="grid-area:6/8/8/11; ">Pent.</h2> <h2 style="grid-area:6/11/8/14; ">Blues</h2> <img src="chords/scale-major.svg" style="grid-area:6/2/16/5" /> <img src="chords/scale-minor.svg" style="grid-area:6/5/16/8" /> <img src="chords/scale-penta.svg" style="grid-area:6/8/16/11" /> <img src="chords/scale-blues.svg" style="grid-area:6/11/16/14" /> </article> <article> <h1 style="grid-area:10/4/12/13">Progressions</h1> <img src="circle-of-fifths.jpg" style="grid-area:2/3/10/14" /> <p style="grid-area:12/2/14/8">C G Am F</p> <p style="grid-area:14/2/16/8">Em D C B</p> <p style="grid-area:16/2/18/8">Am C G D</p> <p style="grid-area:18/2/20/8">F Dm Bb C</p> <p style="grid-area:12/8/14/15">A D7 A E7 D7 A</p> <p style="grid-area:14/8/16/15">C E7 F Fm</p> <p style="grid-area:16/8/18/15">Gm Cm D7</p> <p style="grid-area:18/8/20/15">Em G D C</p> </article> <article> <h1 style="grid-area:2/4/4/13; ">Fretboard</h1> <img src="frets.svg" style="grid-area:4/2/21/15" /> </article> <article style="background: url(mandolin-back.jpg) center center/cover no-repeat;"> </article> </main> </body> </html>
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
mandolin/uchord.py
Python
# The MIT License (MIT) # # Copyright (c) 2017 G. Völkl # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class Chord: """ """ def __init__(self, name, frets, starting_fret=-1, fingers="", subtexts=""): self.name = name self.frets = frets self.fingers = fingers self.subtexts = subtexts self.starting_fret = self._calculate_starting_fret(starting_fret, self.frets) def _calculate_starting_fret(self,starting_fret,frets): if starting_fret != -1: return starting_fret max_fret = -1 num_visible_frets = 5 for i in range(4): max_fret = max(max_fret,int(frets[i])) if max_fret <= num_visible_frets: return 1 else: return max_fret - num_visible_frets + 1 def to_svg(self): """ :rtype: str """ return """ <svg width="84" height="124" viewBox="0 0 84 144" style="font-family: sans-serif; font-size: 11px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> """ + self._to_svg() + "</svg>" def _to_svg(self): closed_string_visible = [] open_string_visible = [] fret_y = [] finger = [] subtext = [] for i in range(4): if int(self.frets[i]) > 0: closed_string_visible.append("visible") open_string_visible.append("hidden") else: closed_string_visible.append("hidden") open_string_visible.append("visible") fret = int(self.frets[i]) if self.starting_fret != 1: fret = fret - self.starting_fret + 1 fret_y.append((fret - 1) * 20) if self.fingers != "": if self.fingers[i] != "_": finger.append(self.fingers[i]) else: finger.append("") else: finger.append("") if self.subtexts != "": if self.subtexts[i] != "_": subtext.append(self.subtexts[i]) else: subtext.append("") else: subtext.append("") if self.starting_fret != 1: starting_fret_visible = "visible" else: starting_fret_visible = "hidden" #<text id="chordName" x="42" y="12" text-anchor="middle" style="font-size: 16px;">{name}</text> svg = """ <text id="startingFret" x="0" y="40" style="visibility: {starting_fret_visible};">{starting_fret}</text> <g id="svgChord" transform="translate(9,24)"> <g id="strings" transform="translate(0,2)"> <rect height="100" width="2" x="0" fill="black"></rect> <rect height="100" width="2" x="20" fill="black"></rect> <rect height="100" width="2" x="40" fill="black"></rect> <rect height="100" width="2" x="60" fill="black"></rect> </g> <g id="frets" transform="translate(0,2)"> <rect height="2" width="62" y="0" fill="black"></rect> <rect height="2" width="62" y="20" fill="black"></rect> <rect height="2" width="62" y="40" fill="black"></rect> <rect height="2" width="62" y="60" fill="black"></rect> <rect height="2" width="62" y="80" fill="black"></rect> <rect height="2" width="62" y="100" fill="black"></rect> </g> <g id="closedStrings" transform="translate(1,12)"> <g id="closedString0" transform="translate(0,{fret_y[0]})" style="visibility: {closed_string_visible[0]};"> <circle r="6"></circle> <text fill="white" id="finger0" y="4" text-anchor="middle" >{finger[0]}</text> </g> <g id="closedString1" transform="translate(20,{fret_y[1]})" style="visibility: {closed_string_visible[1]};"> <circle r="6"></circle> <text fill="white" id="finger1" y="4" text-anchor="middle">{finger[1]}</text> </g> <g id="closedString2" transform="translate(40,{fret_y[2]})" style="visibility: {closed_string_visible[2]};"> <circle r="6"></circle> <text fill="white" id="finger2" y="4" text-anchor="middle">{finger[2]}</text> </g> <g id="closedString3" transform="translate(60,{fret_y[3]})" style="visibility: {closed_string_visible[3]};"> <circle r="6"></circle> <text fill="white" id="finger3" y="4" text-anchor="middle">{finger[3]}</text> </g> </g> <g id="openStrings" transform="translate(1,-5)"> <circle id="openString0" cx="0" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[0]};"></circle> <circle id="openString1" cx="20" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[1]};"></circle> <circle id="openString2" cx="40" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[2]};"></circle> <circle id="openString3" cx="60" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[3]};"></circle> </g> <g id="subText" transform="translate(1,98)"> <text id="subText0" x="0" text-anchor="middle">{subtext[0]}</text> <text id="subText1" x="20" text-anchor="middle">{subtext[1]}</text> <text id="subText2" x="40" text-anchor="middle">{subtext[2]}</text> <text id="subText3" x="60" text-anchor="middle">{subtext[3]}</text> </g> </g> """.format(name=self.name, open_string_visible=open_string_visible, starting_fret_visible=starting_fret_visible, starting_fret=self.starting_fret, closed_string_visible=closed_string_visible, fret_y=fret_y, finger=finger, subtext=subtext) return svg class Chords: def __init__(self, chordlist): self._chordlist = chordlist def to_svg(self): result = f"""<svg width="{len(self._chordlist)*84}" height="132" style="font-family: sans-serif; font-size: 11px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> """ for i in range(len(self._chordlist)): result += f'<g transform="translate({i * 100},24)">' result += self._chordlist[i]._to_svg() result += '</g>' result += "</svg>" return result def write_chord(filename, name, frets, starting_fret=-1, fingers="", subtexts=""): """ Convenient way to write an svg file :param filename: name of svg file :param name: chord name :param frets: fret positions :param starting_fret: number of starting fret :param fingers: position of fingers :param subtexts: text under the chord :return: """ with open(filename, 'w') as f: f.write(Chord(name, frets, starting_fret, fingers, subtexts).to_svg()) write_chord('chords/c.svg','','0230',fingers=' ') write_chord('chords/d.svg','','2002',fingers=' ') write_chord('chords/e.svg','','1224',fingers=' O') write_chord('chords/f.svg','','5301',fingers=' ') write_chord('chords/g.svg','','0023',fingers=' ') write_chord('chords/a.svg','','2240',fingers=' O ') write_chord('chords/b.svg','','4122',fingers=' ') write_chord('chords/cs.svg','','6344',fingers=' ') write_chord('chords/ds.svg','','0113',fingers=' ') write_chord('chords/fs.svg','','3446',fingers=' ') write_chord('chords/gs.svg','','1134',fingers=' ') write_chord('chords/as.svg','','3011',fingers=' ') write_chord('chords/cm.svg','','0134',fingers=' ') write_chord('chords/dm.svg','','2001',fingers=' ') write_chord('chords/em.svg','','0220',fingers=' ') write_chord('chords/fm.svg','','1334',fingers=' ') write_chord('chords/gm.svg','','0013',fingers=' ') write_chord('chords/am.svg','','2230',fingers=' ') write_chord('chords/bm.svg','','4022',fingers=' ') write_chord('chords/csm.svg','','1240',fingers=' ') write_chord('chords/dsm.svg','','3112',fingers=' ') write_chord('chords/fsm.svg','','2445',fingers=' ') write_chord('chords/gsm.svg','','1124',fingers=' ') write_chord('chords/asm.svg','','3341',fingers=' ') write_chord('chords/xmaj-1.svg','','1134',fingers='R R') write_chord('chords/xmaj-2.svg','','3113',fingers=' R ') write_chord('chords/xmin-1.svg','','1124',fingers='R R') write_chord('chords/xmin-2.svg','','3112',fingers=' R ') write_chord('chords/x7-1.svg','','1132',fingers='R ') write_chord('chords/x7-2.svg','','3142',fingers=' R ') write_chord('chords/xm7-1.svg','','1122',fingers='R ') write_chord('chords/xm7-2.svg','','3153',fingers=' R ') write_chord('chords/xmaj7.svg','','1133',fingers='R ') write_chord('chords/x6.svg','','1131',fingers='R ') write_chord('chords/xdim.svg','','2135',fingers='R ') write_chord('chords/xaug.svg','','1234',fingers='R R')
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
tinwhistle/index.html
HTML
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../zine.css" rel="stylesheet"> <style> @import url('https://fonts.googleapis.com/css2?family=Eagle+Lake&family=Amiri&display=swap'); img { width: 100%; height: 100%; object-fit: contain; } h1, h2 { font-family: "Eagle Lake", cursive; } h1 { font-size: 7mm; } h2 { font-size: 4mm; line-height: 2rem; } p + h2 { margin-top: 1rem; } p { font-family: "Amiri", sans-serif; font-size: 5mm; line-height: 1.25;} i { display: inline-block; font-size: 0.6em; width: 1em; line-height: 0.7; text-align: center; font-style: normal; } u > i { border-bottom: 1px solid black; } i::before { content: attr(data-n); display: block; } i::after { content: attr(data-m); display: block; } </style> </head> <body> <main class="zine"> <article style="background: url(tinwhistle-front.jpg) center center/cover no-repeat; filter: brightness(1.5); "> <h1 style="grid-area:4/3/7/14">Irish Whistle</h1> </article> <article> <div style="grid-area:2/2/21/15"> <h2>Danny Boy</h2> <div> <p>4321 21<u>5</u><i data-n="0" data-m="5"></i>1235</p> <p>431<i data-n="0" data-m="5"></i> <u>5</u><i data-n="0" data-m="5"></i>1312</p> <p>4321 21<u>5</u><i data-n="0" data-m="5"></i>1235</p> <p>4321 <i data-n="0" data-m="2"></i>12323</p> <p><i data-n="0" data-m="5"></i><u>5</u><u>4</u><u>3</u> <u>4</u><u>4</u><u>5</u><i data-n="0" data-m="5"></i><u>5</u><i data-n="0" data-m="5"></i>13</p> <p><i data-n="0" data-m="5"></i><u>5</u><u>4</u><u>3</u> <u>4</u><u>4</u><u>5</u><i data-n="0" data-m="5"></i>12</p> <p><i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><u>1</u> <u>2</u><u>2</u><u>3</u><u>5</u><u>3</u><i data-n="0" data-m="5"></i>13</p> <p>4321 <i data-n="0" data-m="2"></i>12323</p> </div> <h2>Whiskey In The Jar</h2> <div> <p>𝄆4222124 211014</p> <p>21110<i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i>01 22<i data-n="0" data-m="5"></i>012𝄇</p> <p>25555555 445432</p> <p>11210<i data-n="0" data-m="5"></i>124546</p> </div> </div> </article> <article> <div style="grid-area:2/2/21/15"> <h2>Foggy Dew</h2> <p>𝄆 1<i data-n="0" data-m="5"></i><u>5</u> <i data-n="0" data-m="5"></i>1<u>5</u> <i data-n="0" data-m="5"></i>12 15</p> <p>543123565 𝄇</p> <p>6531<i data-n="0" data-m="5"></i> <i data-n="0" data-m="2"></i>1221 321<u>3</u><u>4</u><u>5</u><i data-n="0" data-m="5"></i>1<u>5</u></p> <p>1<i data-n="0" data-m="5"></i><u>5</u> <i data-n="0" data-m="5"></i>1<u>5</u> <i data-n="0" data-m="5"></i>12 15 543123565</p> <h2>&nbsp;</h2> <h2>Wellerman (Sea Shanty)</h2> <p>15553111 1<i data-n="0" data-m="2"></i>221<i data-n="0" data-m="2"></i><u>5</u>11 15553111 212345</p> <p><u>5</u><u>5</u><i data-n="0" data-m="2"></i><i data-n="0" data-m="5"></i>11 1<i data-n="0" data-m="2"></i>221<i data-n="0" data-m="2"></i><i data-n="0" data-m="5"></i>11</p> <p><u>5</u><u>5</u><i data-n="0" data-m="2"></i><i data-n="0" data-m="5"></i>11 112345</p> </div> </article> <article> <div style="grid-area:2/2/21/15"> <h2>Wild Rover</h2> <div> <p>𝄆3323561121<i data-n="0" data-m="2"></i></p> <p><i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i>1<i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>246123𝄇</p> <p>432 2 46 11121<i data-n="0" data-m="2"></i></p> <p>1<i data-n="0" data-m="2"></i><i data-n="0" data-m="5"></i> 1345 561 23</p> </div> <h2>The Irish Rover</h2> <div> <p>𝄆246432 <i data-n="0" data-m="5"></i><u>5</u><u>4</u><u>5</u>0<i data-n="0" data-m="5"></i></p> <p>012 124 345 𝄇<sup>1</sup></p> <p>012 0<i data-n="0" data-m="5"></i><u>5</u> 02<i data-n="0" data-m="5"></i> 𝄇<sup>2</sup></p> <p>22<i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><u>5</u><u>4</u> <u>5</u><i data-n="0" data-m="5"></i><u>5</u><u>5</u>02</p> <p>2<i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><u>5</u><u>4</u> <i data-n="0" data-m="5"></i><u>5</u>02</p> <p>246432 <i data-n="0" data-m="5"></i><u>5</u><u>4</u><u>5</u>0<i data-n="0" data-m="5"></i></p> <p>012 0<i data-n="0" data-m="5"></i><u>5</u> 02<u>5</u> <i data-n="0" data-m="5"></i></p> </div> </div> </article> <article> <div style="grid-area:2/2/21/15"> <h2>Scarborough Fair</h2> <div> <p>5 51 14345 1<i data-n="0" data-m="5"></i><u>5</u> <i data-n="0" data-m="5"></i>1021</p> <p><u>5</u><u>5</u> <u>5</u><i data-n="0" data-m="5"></i> 112346 5 12 34565</p> </div> <h2>Molly Malone</h2> <div> <p>633331 32222<i data-n="0" data-m="2"></i></p> <p>2123<i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i> 11232</p> <p>633331 32222<i data-n="0" data-m="2"></i></p> <p>121<i data-n="0" data-m="5"></i> <i data-n="0" data-m="2"></i>1<i data-n="0" data-m="5"></i> <i data-n="0" data-m="2"></i>1323</p> </div> <h2>Ievan Polka</h2> <div> <p>52222 1<i data-n="0" data-m="2"></i>22 <i data-n="0" data-m="2"></i>1333 1<i data-n="0" data-m="2"></i>22</p> <p>5222 1<i data-n="0" data-m="2"></i>22 211<u>5</u><i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>1 1<i data-n="0" data-m="2"></i>22</p> <p>22<u>5</u><u>5</u><u>5</u><i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>133 1<i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>1<i data-n="0" data-m="2"></i>22</p> <p>1<u>5</u><u>5</u><u>5</u><u>5</u><i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>133 1<i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>1<i data-n="0" data-m="2"></i>22</p> </div> </div> </article> <article> <div style="grid-area:2/2/21/15"> <h2>Bella Ciao</h2> <div> <p>410<i data-n="0" data-m="5"></i>1 410<i data-n="0" data-m="5"></i>1</p> <p>410<i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i>0 1<i data-n="0" data-m="5"></i><i data-n="0" data-m="5"></i>01<u>4</u><u>4</u><u>4</u></p> <p><u>4</u><u>5</u><u>4</u><u>3</u><u>3</u> <u>3</u><u>4</u><u>5</u><u>3</u><u>4</u> <u>4</u><u>5</u><i data-n="0" data-m="5"></i>0<u>4</u><i data-n="0" data-m="5"></i>01</p> </div> <h2>&nbsp;</h2> <h2>Irish Washerwoman</h2> <div> <p>𝄆 133633 131<i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>1 <i data-n="0" data-m="2"></i>22522</p> <p><i data-n="0" data-m="2"></i>2<i data-n="0" data-m="2"></i><u>5</u><i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i> 133633 131<i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i>1</p> <p><i data-n="0" data-m="2"></i>1<i data-n="0" data-m="2"></i>2<i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i> 133 3 𝄇</p> <p>𝄆 <u>3</u> <u>3</u><i data-n="0" data-m="5"></i><u>3</u><u>3</u><i data-n="0" data-m="5"></i><u>3</u> <u>3</u><i data-n="0" data-m="5"></i><u>3</u><u>1</u><u>2</u><u>3</u> <u>4</u><i data-n="0" data-m="5"></i><u>4</u><u>4</u><i data-n="0" data-m="5"></i><u>4</u></p> <p><u>4</u><i data-n="0" data-m="5"></i><u>4</u>234 <u>5</u><u>3</u><u>3</u><i data-n="0" data-m="5"></i><u>3</u><u>3</u> <i data-n="0" data-m="2"></i><u>3</u><u>3</u>1<u>3</u><u>3</u> </p> <p><i data-n="0" data-m="2"></i>1<i data-n="0" data-m="2"></i>2<i data-n="0" data-m="5"></i><i data-n="0" data-m="2"></i> 133 3 𝄇</p> </div> </div> </article> <article> <img src="tinwhistle-fingering.jpg" style="grid-area:2/2/21/15" /> </article> <article style="background: url(tinwhistle-back.jpg) center center/cover no-repeat;"> </article> </main> </body> </html>
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
tokipona/index.html
HTML
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../zine.css" rel="stylesheet"> <style> /*@import url('https://fonts.googleapis.com/css2?family=Comforter+Brush&display=swap');*/ @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300..700;1,300..700&display=swap'); h1, span, p { font-family: "Cormorant Garamond", serif; } h1 { margin: 3mm 0; } </style> <title>Zine: Toki Pona</title> </head> <body> <main class="zine"> <article style="filter: grayscale(1);"> <img style="grid-area:3/6/8/11; width: 100%; height: auto;" src="toki.png" /> <h1 style="grid-area: 7/3/14/14; display: flex; justify-content: center; align-items: center;">Toki Pona</h1> <p style="grid-area: 14/3/18/14"><em>Toki Pona</em> is a constructed language with a vocabulary of just over 120 words using only 14 phonemes:</p> <p style="grid-area: 19/3/19/14">a e i j k l m n o p s t u w</p> </article> <article style="display:block; padding: 3mm; height: 105mm; width: 75mm; "> <h1>Basics</h1> <p>Words have multiple meanings, as nouns, verbs, adjectives or adverbs:</p> <p><b>telo</b> – <em>water / wet / to wash.</em></p> <p>Adjectives follow nouns, modify them:</p> <p><b>soweli suli</b> – <em>big animal = elephant.</em></p> <p><b>jan lili</b> – <em>small person = child.</em></p> <h1>Sentences</h1> <p><u>[subject]</u> <b>li</b> <u>[verb]</u> {<b>e</b> <u>[object]}</u></p> <p><b>soweli li moku</b> – <em>a cat is eating / the dog eats / pets are drinking.</em></p> <p><b>mi</b> <em>(me)</em> and <b>sina</b> <em>(you)</em> don't need <b>li</b>: <b>mi moku; sina toki</b> – <em>I eat; you speak.</em></p> <p>Use <b>e</b> before the object: <b>mi moku e kili</b> – <em>I eat fruit.</em></p> </article> <article style="display:block; padding: 3mm; height: 105mm; width: 75mm; "> <h1>Particles</h1> <p>Use <b>la</b> to set context: <b>mi toki la sina moku</b> – <em>when I speak, you eat.</em></p> <p>Use <b>pi</b> for grouping: <b>toki pi jan pona</b> – <em>language of good men</em>; but <b>toki jan pona</b> – <em>good man speaks.</em></p> <p>Use <b>o</b> for commands: <b>o moku!</b> – <em>Eat!</em></p> <p>Use <b>en</b> for "and": <b>mi en sina</b> – <em>me and you.</em></p> <p>Use <b>anu</b> for "or": <b>mi moku anu toki</b> – <em>I eat or speak.</em></p> <h1>Prepositions</h1> <p><b>kepeken, lon, sama, tan, tawa</b> are also verbs: <b>mi lon tomo</b> – <em>I am at home.</em></p> <p><b>wile, kama, sona, lukin, ken, awen</b> act as preverbs: <b>mi wile moku</b> – <em>I want to eat.</em></p> </article> <article style="display:block; padding: 3mm; height: 105mm; width: 75mm; "> <h1>Questions</h1> <p>Use <b>ala</b> for negation: <b>mi moku ala</b> – <em>I am not eating.</em></p> <p>Use <b>ala</b> for yes-no questions: <b>sina moku ala moku?</b> – <em>are you eating?</em></p> <p>To say <em>"yes"</em> repeat the verb: <b>moku</b>, to say <em>"no"</em> use <b>ala</b>: <b>moku ala.</b></p> <p>Use <b>seme</b> for open questions: <b>sina moku seme?</b> – <em>what are you eating?</em></p> <p>Use <b>anu seme</b> for tag questions: <b>sina moku anu seme?</b> – <em>you are eating, aren't you?</em></p> </p> <h1>Numbers</h1> <p><b>wan</b>=1, <b>tu</b>=2, <b>luka</b>=5, <b>mute</b>=20, <b>ale</b>=100. <b>luka tu wan</b>=7.</p> </article> <article style="display:block; padding: 3mm; height: 105mm; width: 75mm; "> <h1>Phrases</h1> <p><b>toki!</b> – <em>Hello!</em></p> <p><b>sina pilin seme?</b> – <em>How are you?</em></p> <p><b>nimi mi li...</b> – <em>My name is...</em></p> <p><b>sina sona ala sona?</b> – <em>Do you understand?</em></p> <p><b>o toki kepeken tenpo mute</b> - <em>Say slowly.</em></p> <p><b>o toki sin e ni</b> - <em>Please say again.</em></p> <p><b>mi pakala</b> – <em>Sorry.</em></p> <p><b>mi wile</b> – <em>Please.</em></p> <p><b>pona</b> – <em>Thank you.</em></p> <p><b>mi olin e sina</b> – <em>I love you.</em></p> <p><b>tomo telo li lon seme?</b> – <em>Where is the bathroom?</em></p> <p><b>tomo tawa supa mi pi lon sewi li jo e kala linja mute mute</b> – <em>My hovercraft is full of eels.</em></p> </article> <article style="display:block; padding: 3mm; height: 105mm; width: 75mm; "> <h1>Vocabulary</h1> <p> <b>a</b>&nbsp;<em>[a!]</em> • <b>akesi</b>&nbsp;<em>reptile</em> • <b>ala</b>&nbsp;<em>no</em> • <b>alasa</b>&nbsp;<em>hunt</em> • <b>ale</b>&nbsp;<em>all</em> • <b>anpa</b>&nbsp;<em>low</em> • <b>ante</b>&nbsp;<em>other</em> • <b>anu</b>&nbsp;<em>[or]</em> • <b>awen</b>&nbsp;<em>keep</em> • <b>e</b>&nbsp;<em>[obj]</em> • <b>en</b>&nbsp;<em>[and]</em> • <b>esun</b>&nbsp;<em>shop</em> • <b>ijo</b>&nbsp;<em>thing</em> • <b>ike</b>&nbsp;<em>bad</em> • <b>ilo</b>&nbsp;<em>tool</em> • <b>insa</b>&nbsp;<em>centre</em> • <b>jaki</b>&nbsp;<em>gross</em> • <b>jan</b>&nbsp;<em>man</em> • <b>jelo</b>&nbsp;<em>yellow</em> • <b>jo</b>&nbsp;<em>have</em> • <b>kala</b>&nbsp;<em>fish</em> • <b>kalama</b>&nbsp;<em>sound</em> • <b>kama</b>&nbsp;<em>come</em> • <b>kasi</b>&nbsp;<em>plant</em> • <b>ken</b>&nbsp;<em>can</em> • <b>kepeken</b>&nbsp;<em>use</em> • <b>kili</b>&nbsp;<em>fruit</em> • <b>kiwen</b>&nbsp;<em>hard</em> • <b>ko</b>&nbsp;<em>clay</em> • <b>kon</b>&nbsp;<em>air</em> • <b>kule</b>&nbsp;<em>colour</em> • <b>kulupu</b>&nbsp;<em>group</em> • <b>kute</b>&nbsp;<em>hear</em> • <b>la</b>&nbsp;<em>[ctx]</em> • <b>lape</b>&nbsp;<em>sleep</em> • <b>laso</b>&nbsp;<em>blue</em> • <b>lawa</b>&nbsp;<em>head</em> • <b>len</b>&nbsp;<em>cloth</em> • <b>lete</b>&nbsp;<em>cold</em> • <b>li</b>&nbsp;<em>[pred]</em> • <b>lili</b>&nbsp;<em>small</em> • <b>linja</b>&nbsp;<em>rope</em> • <b>lipu</b>&nbsp;<em>page</em> • <b>loje</b>&nbsp;<em>red</em> • <b>lon</b>&nbsp;<em>at</em> • <b>luka</b>&nbsp;<em>hand</em> • <b>lukin</b>&nbsp;<em>see</em> • <b>lupa</b>&nbsp;<em>hole</em> • <b>ma</b>&nbsp;<em>land</em> • <b>mama</b>&nbsp;<em>parent</em> • <b>mani</b>&nbsp;<em>money</em> • <b>meli</b>&nbsp;<em>woman</em> • <b>mi</b>&nbsp;<em>me</em> • <b>mije</b>&nbsp;<em>male</em> • <b>moku</b>&nbsp;<em>eat</em> • <b>moli</b>&nbsp;<em>dead</em> • <b>monsi</b>&nbsp;<em>back</em> • <b>mu</b>&nbsp;<em>[moo!]</em> • <b>mun</b>&nbsp;<em>moon</em> • </p> </article> <article style="display:block; padding: 3mm; height: 105mm; width: 75mm; "> <p> <b>musi</b>&nbsp;<em>fun</em> • <b>mute</b>&nbsp;<em>many</em> • <b>nanpa</b>&nbsp;<em>number</em> • <b>nasa</b>&nbsp;<em>crazy</em> • <b>nasin</b>&nbsp;<em>way</em> • <b>nena</b>&nbsp;<em>bump</em> • <b>ni</b>&nbsp;<em>this</em> • <b>nimi</b>&nbsp;<em>name</em> • <b>noka</b>&nbsp;<em>leg</em> • <b>o</b>&nbsp;<em>[o!]</em> • <b>olin</b>&nbsp;<em>love</em> • <b>ona</b>&nbsp;<em>they</em> • <b>open</b>&nbsp;<em>open</em> • <b>pakala</b>&nbsp;<em>break</em> • <b>pali</b>&nbsp;<em>do</em> • <b>palisa</b>&nbsp;<em>stick</em> • <b>pan</b>&nbsp;<em>bread</em> • <b>pana</b>&nbsp;<em>give</em> • <b>pi</b>&nbsp;<em>[of]</em> • <b>pilin</b>&nbsp;<em>heart</em> • <b>pimeja</b>&nbsp;<em>dark</em> • <b>pini</b>&nbsp;<em>end</em> • <b>pipi</b>&nbsp;<em>bug</em> • <b>poka</b>&nbsp;<em>side</em> • <b>poki</b>&nbsp;<em>bag</em> • <b>pona</b>&nbsp;<em>good</em> • <b>sama</b>&nbsp;<em>same</em> • <b>seli</b>&nbsp;<em>hot</em> • <b>selo</b>&nbsp;<em>layer</em> • <b>seme</b>&nbsp;<em>what</em> • <b>sewi</b>&nbsp;<em>top</em> • <b>sijelo</b>&nbsp;<em>body</em> • <b>sike</b>&nbsp;<em>round</em> • <b>sin</b>&nbsp;<em>new</em> • <b>sina</b>&nbsp;<em>you</em> • <b>sinpin</b>&nbsp;<em>face</em> • <b>sitelen</b>&nbsp;<em>image</em> • <b>sona</b>&nbsp;<em>know</em> • <b>soweli</b>&nbsp;<em>animal</em> • <b>suli</b>&nbsp;<em>big</em> • <b>suno</b>&nbsp;<em>sun</em> • <b>supa</b>&nbsp;<em>surface</em> • <b>suwi</b>&nbsp;<em>sweet</em> • <b>tan</b>&nbsp;<em>from</em> • <b>taso</b>&nbsp;<em>but</em> • <b>tawa</b>&nbsp;<em>go</em> • <b>telo</b>&nbsp;<em>water</em> • <b>tenpo</b>&nbsp;<em>time</em> • <b>toki</b>&nbsp;<em>say</em> • <b>tomo</b>&nbsp;<em>home</em> • <b>tu</b>&nbsp;<em>2</em> • <b>unpa</b>&nbsp;<em>sex</em> • <b>uta</b>&nbsp;<em>mouth</em> • <b>utala</b>&nbsp;<em>fight</em> • <b>walo</b>&nbsp;<em>white</em> • <b>wan</b>&nbsp;<em>1</em> • <b>waso</b>&nbsp;<em>bird</em> • <b>wawa</b>&nbsp;<em>strong</em> • <b>weka</b>&nbsp;<em>away</em> • <b>wile</b>&nbsp;<em>want</em> </div> </article> <article style="filter: grayscale(1)"> <p style="grid-area: 3/5/5/12">...and one last word:</p> <p style="grid-area: 5/5/7/12"><b>kijetesantakalu</b></p> <img src="racoon.png" style="grid-area: 7/5/9/12; width: 100%; height: auto;"/> <p style="grid-area: 14/3/17/14;"><em>any animal from the Procyonidae family, such as raccoons, coatis, kinkajous, olingos, ringtails and cacomistles.</em></p> </article> </main> </body> </html>
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
ukulele/index.html
HTML
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../zine.css" rel="stylesheet"> <style> @import url('https://fonts.googleapis.com/css2?family=Zeyada&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Paytone+One&display=swap'); img { width: 100%; height: 100%; object-fit: contain; } h1, h2 { font-family: "Zeyada", cursive; } h1 { font-size: 8mm; } h2 { font-size: 5mm; } p { font-family: "Paytone One", sans-serif; } article > * { align-self: center; justify-self: center; } </style> </head> <body> <main class="zine"> <article style="background: url(ukulele-front.jpg) center center/cover no-repeat; filter: brightness(1.5); "> <h1 style="text-stroke: black; color: white; grid-area:2/6/5/11">UKULELE</h1> </article> <article> <h1 style="grid-area:2/4/4/13; ">Major chords</h1> <h2 style="grid-area:4/2/6/5; ">C</h2> <h2 style="grid-area:4/5/6/8; ">D</h2> <h2 style="grid-area:4/8/6/11; ">E</h2> <h2 style="grid-area:4/11/6/14; ">F</h2> <img src="chords/c.svg" style="grid-area:5/2/9/5" /> <img src="chords/d.svg" style="grid-area:5/5/9/8" /> <img src="chords/e.svg" style="grid-area:5/8/9/11" /> <img src="chords/f.svg" style="grid-area:5/11/9/14" /> <h2 style="grid-area:10/2/12/5; ">G</h2> <h2 style="grid-area:10/5/12/8; ">A</h2> <h2 style="grid-area:10/8/12/11; ">B</h2> <h2 style="grid-area:10/11/12/14; ">C#</h2> <img src="chords/g.svg" style="grid-area:11/2/15/5" /> <img src="chords/a.svg" style="grid-area:11/5/15/8" /> <img src="chords/b.svg" style="grid-area:11/8/15/11" /> <img src="chords/cs.svg" style="grid-area:11/11/15/14" /> <h2 style="grid-area:16/2/18/5; ">D#</h2> <h2 style="grid-area:16/5/18/8; ">F#</h2> <h2 style="grid-area:16/8/18/11; ">G#</h2> <h2 style="grid-area:16/11/18/14; ">A#</h2> <img src="chords/ds.svg" style="grid-area:17/2/21/5" /> <img src="chords/fs.svg" style="grid-area:17/5/21/8" /> <img src="chords/gs.svg" style="grid-area:17/8/21/11" /> <img src="chords/as.svg" style="grid-area:17/11/21/14" /> </article> <article> <h1 style="grid-area:2/4/4/13; ">Minor chords</h1> <h2 style="grid-area:4/2/6/5; ">Cm</h2> <h2 style="grid-area:4/5/6/8; ">Dm</h2> <h2 style="grid-area:4/8/6/11; ">Em</h2> <h2 style="grid-area:4/11/6/14; ">Fm</h2> <img src="chords/cm.svg" style="grid-area:5/2/9/5" /> <img src="chords/dm.svg" style="grid-area:5/5/9/8" /> <img src="chords/em.svg" style="grid-area:5/8/9/11" /> <img src="chords/fm.svg" style="grid-area:5/11/9/14" /> <h2 style="grid-area:10/2/12/5; ">Gm</h2> <h2 style="grid-area:10/5/12/8; ">Am</h2> <h2 style="grid-area:10/8/12/11; ">Bm</h2> <h2 style="grid-area:10/11/12/14; ">C#m</h2> <img src="chords/gm.svg" style="grid-area:11/2/15/5" /> <img src="chords/am.svg" style="grid-area:11/5/15/8" /> <img src="chords/bm.svg" style="grid-area:11/8/15/11" /> <img src="chords/csm.svg" style="grid-area:11/11/15/14" /> <h2 style="grid-area:16/2/18/5; ">D#m</h2> <h2 style="grid-area:16/5/18/8; ">F#m</h2> <h2 style="grid-area:16/8/18/11; ">G#m</h2> <h2 style="grid-area:16/11/18/14; ">A#m</h2> <img src="chords/dsm.svg" style="grid-area:17/2/21/5" /> <img src="chords/fsm.svg" style="grid-area:17/5/21/8" /> <img src="chords/gsm.svg" style="grid-area:17/8/21/11" /> <img src="chords/asm.svg" style="grid-area:17/11/21/14" /> </article> <article> <h1 style="grid-area:2/4/4/13; ">7<sup>th</sup> chords</h1> <h2 style="grid-area:4/2/6/5; ">C7</h2> <h2 style="grid-area:4/5/6/8; ">D7</h2> <h2 style="grid-area:4/8/6/11; ">E7</h2> <h2 style="grid-area:4/11/6/14; ">F7</h2> <img src="chords/c7.svg" style="grid-area:5/2/9/5" /> <img src="chords/d7.svg" style="grid-area:5/5/9/8" /> <img src="chords/e7.svg" style="grid-area:5/8/9/11" /> <img src="chords/f7.svg" style="grid-area:5/11/9/14" /> <h2 style="grid-area:10/2/12/5; ">G7</h2> <h2 style="grid-area:10/5/12/8; ">A7</h2> <h2 style="grid-area:10/8/12/11; ">B7</h2> <h2 style="grid-area:10/11/12/14; ">C#7</h2> <img src="chords/g7.svg" style="grid-area:11/2/15/5" /> <img src="chords/a7.svg" style="grid-area:11/5/15/8" /> <img src="chords/b7.svg" style="grid-area:11/8/15/11" /> <img src="chords/cs7.svg" style="grid-area:11/11/15/14" /> <h2 style="grid-area:16/2/18/5; ">D#7</h2> <h2 style="grid-area:16/5/18/8; ">F#7</h2> <h2 style="grid-area:16/8/18/11; ">G#7</h2> <h2 style="grid-area:16/11/18/14; ">A#7</h2> <img src="chords/ds7.svg" style="grid-area:17/2/21/5" /> <img src="chords/fs7.svg" style="grid-area:17/5/21/8" /> <img src="chords/gs7.svg" style="grid-area:17/8/21/11" /> <img src="chords/as7.svg" style="grid-area:17/11/21/14" /> </article> <article> <h1 style="grid-area:2/4/4/13; ">Minor 7<sup>th</sup> chords</h1> <h2 style="grid-area:4/2/6/5; ">Cm7</h2> <h2 style="grid-area:4/5/6/8; ">Dm7</h2> <h2 style="grid-area:4/8/6/11; ">Em7</h2> <h2 style="grid-area:4/11/6/14; ">Fm7</h2> <img src="chords/cm7.svg" style="grid-area:5/2/9/5" /> <img src="chords/dm7.svg" style="grid-area:5/5/9/8" /> <img src="chords/em7.svg" style="grid-area:5/8/9/11" /> <img src="chords/fm7.svg" style="grid-area:5/11/9/14" /> <h2 style="grid-area:10/2/12/5; ">Gm7</h2> <h2 style="grid-area:10/5/12/8; ">Am7</h2> <h2 style="grid-area:10/8/12/11; ">Bm7</h2> <h2 style="grid-area:10/11/12/14; ">C#m7</h2> <img src="chords/gm7.svg" style="grid-area:11/2/15/5" /> <img src="chords/am7.svg" style="grid-area:11/5/15/8" /> <img src="chords/bm7.svg" style="grid-area:11/8/15/11" /> <img src="chords/csm7.svg" style="grid-area:11/11/15/14" /> <h2 style="grid-area:16/2/18/5; ">D#m7</h2> <h2 style="grid-area:16/5/18/8; ">F#m7</h2> <h2 style="grid-area:16/8/18/11; ">G#m7</h2> <h2 style="grid-area:16/11/18/14; ">A#m7</h2> <img src="chords/dsm7.svg" style="grid-area:17/2/21/5" /> <img src="chords/fsm7.svg" style="grid-area:17/5/21/8" /> <img src="chords/gsm7.svg" style="grid-area:17/8/21/11" /> <img src="chords/asm7.svg" style="grid-area:17/11/21/14" /> </article> <article> <h1 style="grid-area:2/4/4/13; ">Movable chords</h1> <h2 style="grid-area:4/2/6/5; ">dim</h2> <h2 style="grid-area:4/5/6/8; ">aug</h2> <h2 style="grid-area:4/8/6/11; ">6<sup>th</sup></h2> <h2 style="grid-area:4/11/6/14; ">maj7</h2> <img src="chords/xdim.svg" style="grid-area:5/2/9/5" /> <img src="chords/xaug.svg" style="grid-area:5/5/9/8" /> <img src="chords/x6.svg" style="grid-area:5/8/9/11" /> <img src="chords/xmaj7.svg" style="grid-area:5/11/9/14" /> <h1 style="grid-area:10/4/12/13">Progressions</h1> <p style="grid-area:12/2/14/8">C G Am F</p> <p style="grid-area:14/2/16/8">Em D C B</p> <p style="grid-area:16/2/18/8">Am C G D</p> <p style="grid-area:18/2/20/8">F Dm Bb C</p> <p style="grid-area:12/8/14/15">A D7 A E7 D7 A</p> <p style="grid-area:14/8/16/15">C E7 F Fm</p> <p style="grid-area:16/8/18/15">Gm Cm D7</p> <p style="grid-area:18/8/20/15">Em G D C</p> </article> <article> <h1 style="grid-area:2/4/4/13; ">Frets</h1> <img src="frets.png" style="grid-area:4/2/21/15" /> </article> <article style="background: url(ukulele-back.jpg) center center/cover no-repeat;"> </article> </main> </body> </html>
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
ukulele/uchord.py
Python
# The MIT License (MIT) # # Copyright (c) 2017 G. Völkl # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class Chord: """ """ def __init__(self, name, frets, starting_fret=-1, fingers="", subtexts=""): self.name = name self.frets = frets self.fingers = fingers self.subtexts = subtexts self.starting_fret = self._calculate_starting_fret(starting_fret, self.frets) def _calculate_starting_fret(self,starting_fret,frets): if starting_fret != -1: return starting_fret max_fret = -1 num_visible_frets = 4 for i in range(4): max_fret = max(max_fret,int(frets[i])) if max_fret <= num_visible_frets: return 1 else: return max_fret - num_visible_frets + 1 def to_svg(self): """ :rtype: str """ return """ <svg width="84" height="124" viewBox="0 0 84 124" style="font-family: sans-serif; font-size: 11px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> """ + self._to_svg() + "</svg>" def _to_svg(self): closed_string_visible = [] open_string_visible = [] fret_y = [] finger = [] subtext = [] for i in range(4): if int(self.frets[i]) > 0: closed_string_visible.append("visible") open_string_visible.append("hidden") else: closed_string_visible.append("hidden") open_string_visible.append("visible") fret = int(self.frets[i]) if self.starting_fret != 1: fret = fret - self.starting_fret + 1 fret_y.append((fret - 1) * 20) if self.fingers != "": if self.fingers[i] != "_": finger.append(self.fingers[i]) else: finger.append("") else: finger.append("") if self.subtexts != "": if self.subtexts[i] != "_": subtext.append(self.subtexts[i]) else: subtext.append("") else: subtext.append("") if self.starting_fret != 1: starting_fret_visible = "visible" else: starting_fret_visible = "hidden" #<text id="chordName" x="42" y="12" text-anchor="middle" style="font-size: 16px;">{name}</text> svg = """ <text id="startingFret" x="0" y="40" style="visibility: {starting_fret_visible};">{starting_fret}</text> <g id="svgChord" transform="translate(9,24)"> <g id="strings" transform="translate(0,2)"> <rect height="80" width="2" x="0" fill="black"></rect> <rect height="80" width="2" x="20" fill="black"></rect> <rect height="80" width="2" x="40" fill="black"></rect> <rect height="80" width="2" x="60" fill="black"></rect> </g> <g id="frets" transform="translate(0,2)"> <rect height="2" width="62" y="0" fill="black"></rect> <rect height="2" width="62" y="20" fill="black"></rect> <rect height="2" width="62" y="40" fill="black"></rect> <rect height="2" width="62" y="60" fill="black"></rect> <rect height="2" width="62" y="80" fill="black"></rect> </g> <g id="closedStrings" transform="translate(1,12)"> <g id="closedString0" transform="translate(0,{fret_y[0]})" style="visibility: {closed_string_visible[0]};"> <circle r="6"></circle> <text fill="white" id="finger0" y="4" text-anchor="middle" >{finger[0]}</text> </g> <g id="closedString1" transform="translate(20,{fret_y[1]})" style="visibility: {closed_string_visible[1]};"> <circle r="6"></circle> <text fill="white" id="finger1" y="4" text-anchor="middle">{finger[1]}</text> </g> <g id="closedString2" transform="translate(40,{fret_y[2]})" style="visibility: {closed_string_visible[2]};"> <circle r="6"></circle> <text fill="white" id="finger2" y="4" text-anchor="middle">{finger[2]}</text> </g> <g id="closedString3" transform="translate(60,{fret_y[3]})" style="visibility: {closed_string_visible[3]};"> <circle r="6"></circle> <text fill="white" id="finger3" y="4" text-anchor="middle">{finger[3]}</text> </g> </g> <g id="openStrings" transform="translate(1,-5)"> <circle id="openString0" cx="0" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[0]};"></circle> <circle id="openString1" cx="20" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[1]};"></circle> <circle id="openString2" cx="40" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[2]};"></circle> <circle id="openString3" cx="60" r="4" fill="none" stroke="black" stroke-width="1" style="visibility: {open_string_visible[3]};"></circle> </g> <g id="subText" transform="translate(1,98)"> <text id="subText0" x="0" text-anchor="middle">{subtext[0]}</text> <text id="subText1" x="20" text-anchor="middle">{subtext[1]}</text> <text id="subText2" x="40" text-anchor="middle">{subtext[2]}</text> <text id="subText3" x="60" text-anchor="middle">{subtext[3]}</text> </g> </g> """.format(name=self.name, open_string_visible=open_string_visible, starting_fret_visible=starting_fret_visible, starting_fret=self.starting_fret, closed_string_visible=closed_string_visible, fret_y=fret_y, finger=finger, subtext=subtext) return svg class Chords: def __init__(self, chordlist): self._chordlist = chordlist def to_svg(self): result = f"""<svg width="{len(self._chordlist)*84}" height="132" style="font-family: sans-serif; font-size: 11px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> """ for i in range(len(self._chordlist)): result += f'<g transform="translate({i * 80},24)">' result += self._chordlist[i]._to_svg() result += '</g>' result += "</svg>" return result def write_chord(filename, name, frets, starting_fret=-1, fingers="", subtexts=""): """ Convenient way to write an svg file :param filename: name of svg file :param name: chord name :param frets: fret positions :param starting_fret: number of starting fret :param fingers: position of fingers :param subtexts: text under the chord :return: """ with open(filename, 'w') as f: f.write(Chord(name, frets, starting_fret, fingers, subtexts).to_svg()) write_chord('chords/c.svg','','0003',fingers='0003') write_chord('chords/d.svg','','2220',fingers='1230') write_chord('chords/e.svg','','4442',fingers='2341') write_chord('chords/f.svg','','2010',fingers='2010') write_chord('chords/g.svg','','0232',fingers='0132') write_chord('chords/a.svg','','2100',fingers='2100') write_chord('chords/b.svg','','4322',fingers='3211') write_chord('chords/cs.svg','','1114',fingers='1114') write_chord('chords/ds.svg','','0331',fingers='0341') write_chord('chords/fs.svg','','3121',fingers='3121') write_chord('chords/gs.svg','','5343',fingers='3121') write_chord('chords/as.svg','','3211',fingers='3211') write_chord('chords/cm.svg','','0333',fingers='0111') write_chord('chords/dm.svg','','2210',fingers='2310') write_chord('chords/em.svg','','0432',fingers='0321') write_chord('chords/fm.svg','','1013',fingers='1024') write_chord('chords/gm.svg','','0231',fingers='0231') write_chord('chords/am.svg','','2000',fingers='2000') write_chord('chords/bm.svg','','4222',fingers='3111') write_chord('chords/csm.svg','','1104',fingers='1204') write_chord('chords/dsm.svg','','3321',fingers='3421') write_chord('chords/fsm.svg','','2124',fingers='2134') write_chord('chords/gsm.svg','','1342',fingers='1342') write_chord('chords/asm.svg','','3111',fingers='3111') write_chord('chords/c7.svg','','0001',fingers='0001') write_chord('chords/d7.svg','','2223',fingers='1112') write_chord('chords/e7.svg','','1202',fingers='1203') write_chord('chords/f7.svg','','2313',fingers='2413') write_chord('chords/g7.svg','','0212',fingers='0213') write_chord('chords/a7.svg','','0100',fingers='0200') write_chord('chords/b7.svg','','2322',fingers='1211') write_chord('chords/cs7.svg','','1112',fingers='1112') write_chord('chords/ds7.svg','','3334',fingers='1112') write_chord('chords/fs7.svg','','3424',fingers='2413') write_chord('chords/gs7.svg','','1323',fingers='1324') write_chord('chords/as7.svg','','1211',fingers='1211') write_chord('chords/cm7.svg','','3333',fingers='1111') write_chord('chords/dm7.svg','','2213',fingers='3214') write_chord('chords/em7.svg','','0202',fingers='0102') write_chord('chords/fm7.svg','','1313',fingers='1324') write_chord('chords/gm7.svg','','0211',fingers='0211') write_chord('chords/am7.svg','','2433',fingers='1322') write_chord('chords/bm7.svg','','2222',fingers='1111') write_chord('chords/csm7.svg','','1102',fingers='1203') write_chord('chords/dsm7.svg','','3324',fingers='2314') write_chord('chords/fsm7.svg','','2424',fingers='1324') write_chord('chords/gsm7.svg','','1322',fingers='1322') write_chord('chords/asm7.svg','','1111',fingers='1111') write_chord('chords/xdim.svg','','1212',fingers=' R') write_chord('chords/xaug.svg','','4332',fingers='R R') write_chord('chords/x6.svg','','4646',fingers='R ') write_chord('chords/xmaj7.svg','','4666',fingers='R ')
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
zine.css
CSS
/* Minimal CSS reset */ * { margin: 0; padding: 0; box-sizing: border-box; } /* Common styles: zine is a grid with some gap between pages */ .zine { display: grid; padding: 1mm; gap: 2mm; } /* Pages are also 21x15 grids to roughly fit A4/Letter aspect ratio */ .zine > * { display: grid; grid-template-columns: repeat(15, 5mm); grid-template-rows: repeat(21, 5mm); background-color: white; } @media (prefers-color-scheme: dark) { body { background-color: #424242; } } @media screen { /* On screen all pages go vertically in the middle of the screen */ .zine { grid-template-areas: "p1" "p2" "p3" "p4" "p5" "p6" "p7" "p8"; justify-items: center; gap: 2rem; margin: 2rem; } .zine::before { font-family: system-ui, sans-serif; content: "This is a micro-zine 🗞️. You can read it online, or 🖨️ print, ✂️ cut and 📃 fold it!"; /*position: fixed;*/ /*display: block;*/ /*right: 1rem;*/ /*top: 1rem;*/ /*width: 10rem;*/ padding: 1rem 2rem; line-height: 2rem; color: #828282; } /* Pages drop shadow to appear natural */ .zine > * { border-radius: 2px; box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23); } } @media print { /* 8-page zine should be printed in landscape mode with no additional margins */ @page { size: landscape; margin: 0; bleed: 0; } /* Zine has strange page ordering to make folding possible */ .zine { width: 100vw; height: 100vh; grid-template-areas: "p5 p4 p3 p2" "p6 p7 p8 p1"; } /* Some pages have to be flipped 180 degrees */ .zine > :nth-child(5), .zine > :nth-child(4), .zine > :nth-child(3), .zine > :nth-child(2) { transform: rotate(180deg); } .zine :nth-child(1) { grid-area: p1; } .zine :nth-child(2) { grid-area: p2; } .zine :nth-child(3) { grid-area: p3; } .zine :nth-child(4) { grid-area: p4; } .zine :nth-child(5) { grid-area: p5; } .zine :nth-child(6) { grid-area: p6; } .zine :nth-child(7) { grid-area: p7; } .zine :nth-child(8) { grid-area: p8; } }
zserge/zine
79
Tiny CSS template to produce micro-zines (folded 8-page magazines)
HTML
zserge
Serge Zaitsev
eslint.config.js
JavaScript
const tsParser = require('@typescript-eslint/parser'); const tsPlugin = require('@typescript-eslint/eslint-plugin'); module.exports = [ { files: ['**/*.ts'], languageOptions: { parser: tsParser, }, plugins: { '@typescript-eslint': tsPlugin, }, rules: { '@typescript-eslint/no-unused-vars': ['error', { args: 'all', argsIgnorePattern: '^_' }], }, }, ];
zsviczian/KPlex
11
A knowledge graph project inspired by TheBrain and ExcaliBrain aiming to create an Obsidian.md plugin that will serve as a graph based user interface to link and navigate notes
TypeScript
zsviczian
rollup.config.js
JavaScript
import babel from "@rollup/plugin-babel"; import commonjs from "@rollup/plugin-commonjs"; import replace from "@rollup/plugin-replace"; import resolve from "@rollup/plugin-node-resolve"; import { terser } from "rollup-plugin-terser"; import typescript from "@rollup/plugin-typescript"; import copy from "rollup-plugin-copy"; import { env } from "process"; const DIST_FOLDER = 'dist'; const isProd = (process.env.NODE_ENV === "production"); console.log(`Building for ${isProd ? "production" : "development"}`); export default { input: "src/index.ts", output: { file: `${DIST_FOLDER}/main.js`, format: "cjs", exports: "default", SourceMap: !isProd, }, external: ["obsidian", "fs", "os", "path"], plugins: [ typescript({ sourceMap: !isProd, }), resolve({ browser: true, }), replace({ preventAssignment: true, "process.env.NODE_ENV": JSON.stringify(env.NODE_ENV), }), babel({ babelHelpers: 'bundled', exclude: 'node_modules/**', presets: ["@babel/preset-react", "@babel/preset-typescript"], }), commonjs(), ...(isProd ? [ terser({ toplevel: false, compress: { passes: 2 }, format: { comments: false, // Remove all comments }, })] : [] ), copy({ targets: [ { src: 'manifest.json', dest: DIST_FOLDER }, { src: 'styles.css', dest: DIST_FOLDER } ], verbose: true, }), ], };
zsviczian/KPlex
11
A knowledge graph project inspired by TheBrain and ExcaliBrain aiming to create an Obsidian.md plugin that will serve as a graph based user interface to link and navigate notes
TypeScript
zsviczian