code
stringlengths 0
56.1M
| repo_name
stringclasses 515
values | path
stringlengths 2
147
| language
stringclasses 447
values | license
stringclasses 7
values | size
int64 0
56.8M
|
---|---|---|---|---|---|
import { chapterHref, pageHref } from '../data/hrefs';
import { h } from '../hs';
import { isCandidate } from '../pages/wtcupVote';
import { Content } from './contentControl';
// const voteDate = 1607007600000; // new Date('2020-12-03T23:00:00.000+08:00').getTime()
const endDate = 1609426800000; // new Date('2020-12-31T23:00:00.000+08:00').getTime()
export function isWtcupStillOn() {
return Date.now() < endDate;
}
export function loadWtcupInfoPre(content: Content, relativePath: string) {
if (!isWtcupStillOn()) {
return;
}
if (isCandidate(relativePath)) {
content.addBlock({
initElement: h('div',
h('h3', `本文正在参与第一届西塔杯年度最佳已完结文章评选!`),
h('p',
'评选结果由投票决定,欢迎',
h('a.regular', {
href: pageHref('wtcup-vote'),
}, '点此参与投票'),
'。'
),
),
});
}
}
export function loadWtcupInfo(content: Content) {
content.addBlock({
initElement: h('div',
h('h3', `第一届西塔杯年度最佳已完结文章评选已经结束!`),
h('p',
'西塔杯选出了年度十佳作品以及三位获奖作者,',
h('a.regular', {
href: chapterHref('META/第一届西塔杯评选.html'),
}, '点此查看评选结果'),
'。'
),
),
});
}
|
kink/kat
|
src/web/control/wtcupInfoControl.ts
|
TypeScript
|
unknown
| 1,382 |
import { DebugLogger } from '../DebugLogger';
export class AutoCache<TKey, TValue> {
private map = new Map<TKey, Promise<TValue>>();
public constructor(
private loader: (key: TKey) => Promise<TValue>,
private logger: DebugLogger,
) {}
public delete(key: TKey) {
this.map.delete(key);
}
public get(key: TKey): Promise<TValue> {
let value = this.map.get(key);
if (value === undefined) {
this.logger.log(`Start loading for key=${key}.`);
value = this.loader(key);
this.map.set(key, value);
value.catch(error => {
this.map.delete(key);
this.logger.warn(
`Loader failed for key=${key}. Cache removed.`, error,
);
});
} else {
this.logger.log(`Cached value used for key=${key}.`);
}
return value;
}
}
export class AutoSingleCache<TValue> extends AutoCache<null, TValue> {
public constructor(
loader: () => Promise<TValue>,
logger: DebugLogger,
) {
super(loader, logger);
}
public delete() {
super.delete(null);
}
public get(): Promise<TValue> {
return super.get(null);
}
}
|
kink/kat
|
src/web/data/AutoCache.ts
|
TypeScript
|
unknown
| 1,120 |
import { Chapter, Data, Folder, AuthorInfo } from '../../Data';
import { DebugLogger } from '../DebugLogger';
export const data = (window as any).DATA as Data;
export interface ChapterContext {
folder: Folder;
inFolderIndex: number;
chapter: Chapter;
}
const debugLogger = new DebugLogger('Data');
export const tagCountMap: Map<string, number> = new Map();
function incrementCount(tag: string) {
tagCountMap.set(tag, (tagCountMap.get(tag) ?? 0) + 1);
}
export const relativePathLookUpMap: Map<string, ChapterContext> = new Map();
function iterateFolder(folder: Folder) {
folder.children.forEach((child, index) => {
if (child.type === 'folder') {
iterateFolder(child);
} else {
relativePathLookUpMap.set(child.htmlRelativePath, {
folder,
chapter: child,
inFolderIndex: index,
});
child.tags?.forEach(tag => {
incrementCount(tag);
if (tag.includes('(')) {
incrementCount(tag.substr(0, tag.indexOf('(')));
}
});
}
});
}
const startTime = Date.now();
iterateFolder(data.chapterTree);
debugLogger.log(`Iterating folders took ${Date.now() - startTime}ms.`);
export const authorInfoMap: Map<string, AuthorInfo> = new Map();
for (const authorInfo of data.authorsInfo) {
authorInfoMap.set(authorInfo.name, authorInfo);
}
export const tagAliasMap = new Map(data.tagAliases);
|
kink/kat
|
src/web/data/data.ts
|
TypeScript
|
unknown
| 1,388 |
import { DebugLogger } from '../DebugLogger';
let db: null | Promise<IDBDatabase> = null;
const debugLogger = new DebugLogger('IndexedDB');
const migrations = new Map<number, (db: IDBDatabase) => void>([
[0, db => {
const readingProgress = db.createObjectStore('readingProgress', { keyPath: 'relativePath' });
readingProgress.createIndex('lastRead', 'lastRead');
}],
[1, db => {
db.createObjectStore('simpleKV');
}]
]);
/**
* Turn an event target into a promise.
* ! NOTE: This does not handle onerror, as errors are expected to bubble up.
*/
export function untilSuccess<TResult>(target: IDBRequest<TResult>) {
return new Promise<TResult>(resolve => {
target.onsuccess = function() {
resolve(this.result);
};
});
}
type DbKVKey<TValue> = { key: string };
export function dbKVKey<TValue>(key: string): DbKVKey<TValue> {
return { key };
}
export async function dbKVSet<TValue>(key: DbKVKey<TValue>, value: TValue) {
const db = await getDb();
const store = db.transaction('simpleKV', 'readwrite').objectStore('simpleKV');
await untilSuccess(store.put(value, key.key));
}
export async function dbKVGet<TValue>(key: DbKVKey<TValue>): Promise<TValue | null> {
const db = await getDb();
const store = db.transaction('simpleKV', 'readwrite').objectStore('simpleKV');
return await untilSuccess(store.get(key.key)) ?? null;
}
export function getDb() {
if (db === null) {
db = new Promise((resolve, reject) => {
debugLogger.log('Open database');
const request = window.indexedDB.open('main', 2);
request.onsuccess = () => {
debugLogger.log('Database successfully opened.');
resolve(request.result);
};
request.onerror = () => {
debugLogger.error('Database failed to open: ', request.error);
reject(request.error);
};
request.onupgradeneeded = event => {
debugLogger.log(`Migrating from ${event.oldVersion} to ${event.newVersion!}`);
const db = request.result;
for (let version = event.oldVersion; version < event.newVersion!; version++) {
const migration = migrations.get(version);
if (migration === undefined) {
throw new Error(`Missing migration for version=${version}.`);
}
debugLogger.log(`Running migration ${version} -> ${version + 1}`);
migration(db);
}
debugLogger.log('Migration completed');
};
});
}
return db;
}
|
kink/kat
|
src/web/data/db.ts
|
TypeScript
|
unknown
| 2,474 |
export function chapterHref(htmlRelativePath: string) {
return `#/chapter/${htmlRelativePath}`;
}
export function pageHref(pageName: string) {
return `#/page/${pageName}`;
}
export function mirrorLandingHref(origin: string, token: string | null, scroll?: number) {
let href = `${origin}/#/mirror-landing`;
if (token !== null) {
href += `~token=${token}`;
}
if (scroll !== undefined) {
href += `~scroll=${scroll}`;
}
return href;
}
export function tagSearchHref(tag: string) {
return `#/page/tag-search/${tag}`;
}
|
kink/kat
|
src/web/data/hrefs.ts
|
TypeScript
|
unknown
| 542 |
// Tracking reading progress
import { getDb, untilSuccess } from './db';
interface Entry {
relativePath: string;
lastRead: Date;
/** 0 - 1 */
progress: number;
}
async function getReadonlyStore() {
const db = await getDb();
return db.transaction('readingProgress').objectStore('readingProgress');
}
async function getStore() {
const db = await getDb();
return db.transaction('readingProgress', 'readwrite').objectStore('readingProgress');
}
export async function updateChapterProgress(relativePath: string, progress: number) {
const store = await getStore();
const result = (await untilSuccess(store.get(relativePath))) as (undefined | Entry);
await untilSuccess(store.put({
relativePath,
lastRead: new Date(),
progress: Math.max(progress, result?.progress ?? 0),
}));
}
export async function getHistory(entries = 20) {
const store = await getReadonlyStore();
const lastReadIndex = store.index('lastRead');
return new Promise<Array<Entry>>(resolve => {
const results: Array<Entry> = [];
lastReadIndex.openCursor(null, 'prev').onsuccess = function() {
const cursor = this.result;
if (cursor !== null) {
results.push(cursor.value);
if (results.length >= entries) {
resolve(results);
} else {
cursor.continue();
}
} else {
resolve(results);
}
};
});
}
|
kink/kat
|
src/web/data/readingProgress.ts
|
TypeScript
|
unknown
| 1,395 |
import { Event } from '../Event';
const noop = () => { /* noop */ };
export class BooleanSetting {
private value: boolean;
public readonly event: Event<boolean> = new Event();
public constructor(
private key: string,
defaultValue: boolean
) {
if (defaultValue) {
this.value = window.localStorage.getItem(key) !== 'false';
} else {
this.value = window.localStorage.getItem(key) === 'true';
}
this.updateLocalStorage();
setImmediate(() => this.event.emit(this.value));
}
private updateLocalStorage() {
window.localStorage.setItem(this.key, String(this.value));
}
public getValue() {
return this.value;
}
public setValue(newValue: boolean) {
if (newValue !== this.value) {
this.event.emit(newValue);
}
this.value = newValue;
this.updateLocalStorage();
}
public toggle() {
this.setValue(!this.value);
}
}
export class EnumSetting {
private value: number;
public constructor(
private key: string,
public options: Array<string>,
private defaultValue: number,
private onUpdate: (newValue: number, newValueName: string) => void = noop,
) {
if (!this.isCorrectValue(defaultValue)) {
throw new Error(`Default value ${defaultValue} is not correct.`);
}
this.value = +(window.localStorage.getItem(key) || defaultValue);
this.correctValue();
this.onUpdate(this.value, this.options[this.value]);
}
private isCorrectValue(value: number): boolean {
return !(Number.isNaN(value) || value % 1 !== 0 || value < 0 || value >= this.options.length);
}
private correctValue() {
if (!this.isCorrectValue(this.value)) {
this.value = this.defaultValue;
}
}
private updateLocalStorage() {
window.localStorage.setItem(this.key, String(this.value));
}
public getValue() {
return this.value;
}
public getValueName() {
return this.options[this.value];
}
public setValue(newValue: number) {
if (newValue !== this.value) {
this.onUpdate(newValue, this.options[newValue]);
}
this.value = newValue;
this.updateLocalStorage();
}
}
export const animation = new BooleanSetting('animation', true);
animation.event.on(value => {
setTimeout(() => {
document.body.classList.toggle('animation-enabled', value);
}, 1);
});
export const warning = new BooleanSetting('warning', false);
export const earlyAccess = new BooleanSetting('earlyAccess', false);
export const useComments = new BooleanSetting('useComments', true);
export const gestureSwitchChapter = new BooleanSetting('gestureSwitchChapter', true);
// https://github.com/zenozeng/fonts.css
const fontFamilyCssValues = [
'-apple-system, "Noto Sans", "Helvetica Neue", Helvetica, "Nimbus Sans L", Arial, "Liberation Sans", "PingFang SC", "Hiragino Sans GB", "Noto Sans CJK SC", "Source Han Sans SC", "Source Han Sans CN", "Microsoft YaHei", "Wenquanyi Micro Hei", "WenQuanYi Zen Hei", "ST Heiti", SimHei, "WenQuanYi Zen Hei Sharp", sans-serif',
'Baskerville, Georgia, "Liberation Serif", "Kaiti SC", STKaiti, "AR PL UKai CN", "AR PL UKai HK", "AR PL UKai TW", "AR PL UKai TW MBE", "AR PL KaitiM GB", KaiTi, KaiTi_GB2312, DFKai-SB, "TW\-Kai", serif',
'Georgia, "Nimbus Roman No9 L", "Songti SC", "Noto Serif CJK SC", "Source Han Serif SC", "Source Han Serif CN", STSong, "AR PL New Sung", "AR PL SungtiL GB", NSimSun, SimSun, "TW\-Sung", "WenQuanYi Bitmap Song", "AR PL UMing CN", "AR PL UMing HK", "AR PL UMing TW", "AR PL UMing TW MBE", PMingLiU, MingLiU, serif',
'Baskerville, "Times New Roman", "Liberation Serif", STFangsong, FangSong, FangSong_GB2312, "CWTEX\-F", serif',
];
export const fontFamily = new EnumSetting('fontFamily', ['黑体', '楷体', '宋体', '仿宋'], 0, (fontFamilyIndex: number) => {
document.documentElement.style.setProperty('--font-family', fontFamilyCssValues[fontFamilyIndex]);
document.documentElement.style.setProperty('--font-family-mono', '"Fira Code", ' + fontFamilyCssValues[fontFamilyIndex]);
});
export const developerMode = new BooleanSetting('developerMode', false);
export const charCount = new BooleanSetting('charCount', true);
export const wtcdGameQuickLoadConfirm = new BooleanSetting('wtcdGameQuickLoadConfirm', true);
export const contactInfo = new BooleanSetting('contactInfo', true);
export const showAbandonedChapters = new BooleanSetting('showAbandonedChapters', false);
export const enablePushHelper = new BooleanSetting('enablePushHelper', false);
export const chapterRecommendationCount = new EnumSetting('chapterRecommendationCount', ['禁用', '5 条', '10 条', '15 条', '20 条', '25 条', '30 条', '35 条', '40 条', '45 条', '50 条'], 2);
|
kink/kat
|
src/web/data/settings.ts
|
TypeScript
|
unknown
| 4,668 |
// import { ChapterContext } from './data';
// export type Selection = [number, number, number, number];
// interface State {
// currentChapter: ChapterContext | null;
// chapterSelection: Selection | null;
// chapterTextNodes: Array<Text> | null;
// }
// export const state: State = {
// currentChapter: null,
// chapterSelection: null,
// chapterTextNodes: null,
// };
|
kink/kat
|
src/web/data/state.ts
|
TypeScript
|
unknown
| 384 |
import * as hs from 'hyperscript';
export const h = hs;
|
kink/kat
|
src/web/hs.ts
|
TypeScript
|
unknown
| 57 |
import { BUILD_FAILED_DESC, BUILD_FAILED_OK, BUILD_FAILED_TITLE } from './constant/messages';
import './control/analyticsControl';
import { followQuery, initPathHandlers } from './control/followQuery';
import { initLoseContactPrevention } from './control/loseContactPreventionControl';
import { notify } from './control/modalControl';
import './control/navbarControl';
import { init, tokenItem } from './control/userControl';
import { data } from './data/data';
import { animation } from './data/settings';
import { id } from './util/DOM';
const $warning = id('warning');
if ($warning !== null) {
$warning.addEventListener('click', () => {
$warning.style.opacity = '0';
if (animation.getValue()) {
$warning.addEventListener('transitionend', () => {
$warning.remove();
});
} else {
$warning.remove();
}
});
}
const $buildNumber = id('build-number');
$buildNumber.innerText = `Build ${data.buildNumber}`;
if (tokenItem.exists()) {
init(tokenItem.getValue()!);
}
if (data.buildError) {
notify(BUILD_FAILED_TITLE, BUILD_FAILED_DESC, BUILD_FAILED_OK);
}
initPathHandlers();
window.addEventListener('popstate', () => {
followQuery();
});
followQuery();
initLoseContactPrevention();
|
kink/kat
|
src/web/index.ts
|
TypeScript
|
unknown
| 1,283 |
import { DebugLogger } from '../DebugLogger';
import { Event } from '../Event';
import { isAnyParent } from '../util/DOM';
export enum SwipeDirection {
TO_TOP,
TO_RIGHT,
TO_BOTTOM,
TO_LEFT,
}
const gestureMinWidth = 900;
export const swipeEvent: Event<SwipeDirection> = new Event();
const horizontalMinXProportion = 0.17;
const horizontalMaxYProportion = 0.1;
const verticalMinYProportion = 0.1;
const verticalMaxProportion = 0.1;
const swipeTimeThreshold = 500;
let startX = 0;
let startY = 0;
let startTime = 0;
let startTarget: EventTarget | null = null;
window.addEventListener('touchstart', event => {
// Only listen for first touch starts
if (event.touches.length !== 1) {
return;
}
startTarget = event.target;
startX = event.touches[0].clientX;
startY = event.touches[0].clientY;
startTime = Date.now();
});
window.addEventListener('touchend', event => {
// Only listen for last touch ends
if (event.touches.length !== 0) {
return;
}
// Ignore touches that lasted too long
if (Date.now() - startTime > swipeTimeThreshold) {
return;
}
if (window.innerWidth > gestureMinWidth) {
return;
}
const deltaX = event.changedTouches[0].clientX - startX;
const deltaY = event.changedTouches[0].clientY - startY;
const xProportion = Math.abs(deltaX / window.innerWidth);
const yProportion = Math.abs(deltaY / window.innerHeight);
if (xProportion > horizontalMinXProportion && yProportion < horizontalMaxYProportion) {
// Horizontal swipe detected
// Check for scrollable element
if (isAnyParent(startTarget as HTMLElement, $element => (
(window.getComputedStyle($element).getPropertyValue('overflow-x') !== 'hidden') &&
($element.scrollWidth > $element.clientWidth)
))) {
return;
}
if (deltaX > 0) {
swipeEvent.emit(SwipeDirection.TO_RIGHT);
} else {
swipeEvent.emit(SwipeDirection.TO_LEFT);
}
} else if (yProportion > verticalMinYProportion && xProportion < verticalMaxProportion) {
// Vertical swipe detected
// Check for scrollable element
if (isAnyParent(startTarget as HTMLElement, $element => (
(window.getComputedStyle($element).getPropertyValue('overflow-y') !== 'hidden') &&
($element.scrollHeight > $element.clientHeight)
))) {
return;
}
if (deltaY > 0) {
swipeEvent.emit(SwipeDirection.TO_BOTTOM);
} else {
swipeEvent.emit(SwipeDirection.TO_TOP);
}
}
});
const swipeEventDebugLogger = new DebugLogger('Swipe Event');
swipeEvent.on(direction => {
swipeEventDebugLogger.log(SwipeDirection[direction]);
});
|
kink/kat
|
src/web/input/gestures.ts
|
TypeScript
|
unknown
| 2,607 |
import { DebugLogger } from '../DebugLogger';
import { Event } from '../Event';
export enum ArrowKey {
LEFT,
UP,
RIGHT,
DOWN,
}
export const arrowKeyPressEvent = new Event<ArrowKey>();
export const escapeKeyPressEvent = new Event();
document.addEventListener('keydown', event => {
if (event.repeat) {
return;
}
switch (event.keyCode) {
case 27:
escapeKeyPressEvent.emit();
break;
case 37:
arrowKeyPressEvent.emit(ArrowKey.LEFT);
break;
case 38:
arrowKeyPressEvent.emit(ArrowKey.UP);
break;
case 39:
arrowKeyPressEvent.emit(ArrowKey.RIGHT);
break;
case 40:
arrowKeyPressEvent.emit(ArrowKey.DOWN);
break;
}
});
const arrowEventDebugLogger = new DebugLogger('Arrow Key Event');
arrowKeyPressEvent.on(arrowKey => {
arrowEventDebugLogger.log(ArrowKey[arrowKey]);
});
|
kink/kat
|
src/web/input/keyboard.ts
|
TypeScript
|
unknown
| 867 |
import { ItemDecoration, Menu } from '../Menu';
import { relativePathLookUpMap } from '../data/data';
import { pageHref } from '../data/hrefs';
import { shortNumber } from '../util/shortNumber';
export class AuthorsMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
// Cannot use data from authors.json because we need to list every single author
const authors = new Map<string, number>();
Array.from(relativePathLookUpMap.values()).forEach(chapterCtx => {
const chars = chapterCtx.chapter.charsCount ?? 1;
chapterCtx.chapter.authors.forEach(({ name }) => {
if (authors.has(name)) {
authors.set(name, authors.get(name)! + chars);
} else {
authors.set(name, chars);
}
});
});
Array.from(authors)
.sort((a, b) => b[1] - a[1])
.forEach(([name, chars]) => {
const handle = this.addItem(name, {
button: true,
decoration: ItemDecoration.ICON_PERSON,
link: pageHref(`author/${name}`),
});
handle.append(`[${shortNumber(chars)}]`);
});
}
}
|
kink/kat
|
src/web/menu/AuthorsMenu.ts
|
TypeScript
|
unknown
| 1,118 |
import { Folder } from '../../Data';
import { canChapterShown } from '../control/chapterControl';
import { data } from '../data/data';
import { chapterHref } from '../data/hrefs';
import { charCount, earlyAccess, showAbandonedChapters } from '../data/settings';
import { ItemDecoration, Menu } from '../Menu';
import { shortNumber } from '../util/shortNumber';
import { getDecorationForChapterType } from './ChaptersMenu';
export function isEmptyFolder(folder: Folder): boolean {
return folder.children.every(child =>
(child.type === 'folder')
? isEmptyFolder(child)
: !canChapterShown(child));
}
export function isAbandonedFolder(folder: Folder): boolean {
return folder.children.every(child =>
(child.type === 'folder')
? isAbandonedFolder(child)
: child.abandoned);
}
export class ChapterListingMenu extends Menu {
public constructor(urlBase: string, folder?: Folder) {
super(urlBase);
if (folder === undefined) {
folder = data.chapterTree;
}
for (const child of folder.children) {
if (child.type === 'folder') {
const handle = this.buildSubMenu(child.displayName, ChapterListingMenu, child)
.setUrlSegment(child.displayName.replace(/ /g, '-'))
.setDecoration(ItemDecoration.ICON_FOLDER)
.setHidden(isEmptyFolder(child))
.build();
if (isAbandonedFolder(child)) {
handle.prepend('[DED]');
}
if (child.charsCount !== null && charCount.getValue()) {
handle.append(`[${shortNumber(child.charsCount)}]`);
}
} else {
if (child.hidden) {
continue;
}
if (child.abandoned && !showAbandonedChapters.getValue()) {
continue;
}
if (child.isEarlyAccess && !earlyAccess.getValue()) {
continue;
}
const handle = this.addItem(child.displayName, {
button: true,
link: chapterHref(child.htmlRelativePath),
decoration: getDecorationForChapterType(child.type),
});
if (child.abandoned) {
handle.prepend('[DED]');
}
if (folder.showIndex === true) {
handle.prepend(`${child.displayIndex.join('.')}. `);
}
if (child.isEarlyAccess) {
handle.prepend('[WIP]');
}
if (child.charsCount !== null && charCount.getValue()) {
handle.append(`[${shortNumber(child.charsCount)}]`);
}
}
}
}
}
|
kink/kat
|
src/web/menu/ChapterListingMenu.ts
|
TypeScript
|
unknown
| 2,474 |
import { NodeType } from '../../Data';
import { pageHref } from '../data/hrefs';
import { ItemDecoration, Menu } from '../Menu';
import { AuthorsMenu } from './AuthorsMenu';
import { ChapterListingMenu } from './ChapterListingMenu';
import { HistoryChaptersMenu } from './HistoryChaptersMenu';
import { LatestChaptersMenu } from './LatestChapterMenu';
export function getDecorationForChapterType(chapterType: NodeType) {
switch (chapterType) {
case 'Markdown': return ItemDecoration.ICON_FILE;
case 'WTCD': return ItemDecoration.ICON_GAME;
}
}
export class ChaptersMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
this.buildSubMenu('All Chapters', ChapterListingMenu)
.setDecoration(ItemDecoration.ICON_LIST).build();
this.buildSubMenu('Latest Chapters', LatestChaptersMenu)
.setDecoration(ItemDecoration.ICON_CALENDER).build();
this.buildSubMenu('Chapter History', HistoryChaptersMenu)
.setDecoration(ItemDecoration.ICON_HISTORY).build();
this.addItem('Tag Search', {
button: true,
link: pageHref('tag-search'),
decoration: ItemDecoration.ICON_TAG,
});
this.buildSubMenu('Author Search', AuthorsMenu)
.setDecoration(ItemDecoration.ICON_PERSON).build();
}
}
|
kink/kat
|
src/web/menu/ChaptersMenu.ts
|
TypeScript
|
unknown
| 1,271 |
import { ItemDecoration, Menu } from '../Menu';
export class ContactMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
this.addItem('Telegram Updates Channel', {
button: true,
link: 'https://t.me/joinchat/AAAAAEpkRVwZ-3s5V3YHjA',
decoration: ItemDecoration.ICON_LINK,
});
this.addItem('Telegram Discussion Group', {
button: true,
link: 'https://t.me/joinchat/Dt8_WlJnmEwYNbjzlnLyNA',
decoration: ItemDecoration.ICON_LINK,
});
this.addItem('GitLab Repo', {
button: true,
link: 'https://gitgud.io/RinTepis/wearable-technology',
decoration: ItemDecoration.ICON_LINK,
});
this.addItem('GitHub Repository Site (Blocked)', {
button: true,
link: 'https://github.com/SCLeoX/Wearable-Technology',
decoration: ItemDecoration.ICON_LINK,
});
this.addItem('GitLab.com Repository Site (Blocked)', {
button: true,
link: 'https://gitlab.com/SCLeo/wearable-technology',
decoration: ItemDecoration.ICON_LINK,
});
this.addItem('Original Google Docs', {
button: true,
link: 'https://docs.google.com/document/d/1Pp5CtO8c77DnWGqbXg-3e7w9Q3t88P35FOl6iIJvMfo/edit?usp=sharing',
decoration: ItemDecoration.ICON_LINK,
});
}
}
|
kink/kat
|
src/web/menu/ContactMenu.ts
|
TypeScript
|
unknown
| 1,288 |
import { relativePathLookUpMap } from '../data/data';
import { chapterHref } from '../data/hrefs';
import { getHistory } from '../data/readingProgress';
import { Menu } from '../Menu';
import { getDecorationForChapterType } from './ChaptersMenu';
export class HistoryChaptersMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
// This is very fast. There is no need to display any loading text.
getHistory().then(entries => {
let hasAny = false;
entries.forEach(({ relativePath, progress }) => {
const chapterCtx = relativePathLookUpMap.get(relativePath);
if (chapterCtx === undefined) {
return;
}
hasAny = true;
const handle = this.addItem(chapterCtx.folder.displayName + ' > ' + chapterCtx.chapter.displayName, {
button: true,
decoration: getDecorationForChapterType(chapterCtx.chapter.type),
link: chapterHref(chapterCtx.chapter.htmlRelativePath),
});
handle.prepend(`[${progress === 1 ? 'Complete' : `${Math.round(progress * 100)}%` }]`);
});
if (!hasAny) {
this.addItem('Reading history is empty');
}
}, () => {
this.addItem('Reading history requires your browser to support IndexedDB. Your browser does not support IndexedDB. Please update your browser and try again.');
});
}
}
|
kink/kat
|
src/web/menu/HistoryChaptersMenu.ts
|
TypeScript
|
unknown
| 1,372 |
import { relativePathLookUpMap } from '../data/data';
import { chapterHref } from '../data/hrefs';
import { ItemDecoration, Menu } from '../Menu';
import { formatTimeRelativeLong } from '../util/formatTime';
import { getDecorationForChapterType } from './ChaptersMenu';
export class LatestChaptersMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
let chapterCtxs = Array.from(relativePathLookUpMap.values());
chapterCtxs = chapterCtxs.filter(chapterCtx => !chapterCtx.chapter.htmlRelativePath.includes('META'));
chapterCtxs.sort((a, b) => b.chapter.creationTime - a.chapter.creationTime);
chapterCtxs = chapterCtxs.slice(0, 20);
chapterCtxs.forEach(chapterCtx => {
const handle = this.addItem(chapterCtx.folder.displayName + ' > ' + chapterCtx.chapter.displayName, {
button: true,
decoration: getDecorationForChapterType(chapterCtx.chapter.type),
link: chapterHref(chapterCtx.chapter.htmlRelativePath),
});
handle.prepend(`[${formatTimeRelativeLong(new Date(chapterCtx.chapter.creationTime * 1000))}]`);
});
this.addItem('View All Chapters', {
button: true,
decoration: ItemDecoration.ICON_LIST,
link: '#/menu/章节选择/所有章节',
});
}
}
|
kink/kat
|
src/web/menu/LatestChapterMenu.ts
|
TypeScript
|
unknown
| 1,271 |
const links: Array<{
text: string,
link: string,
}> = [
{ text: '艾利浩斯学院 图书馆', link: 'http://alhs.live' },
{ text: 'acted 咕咕喵的小说和小游戏', link: 'https://acted.gitlab.io/h3/' },
{ text: '琥珀的可穿戴科技番外', link: 'https://www.pixiv.net/novel/show.php?id=14995202' },
{ text: '千早快传', link: 'https://chihaya.cloud' },
];
import { ItemDecoration, Menu } from '../Menu';
export class LinkExchangeMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
links.sort(() => Math.random() - 0.5);
links.forEach(({ text, link }) => this.addItem(text, {
button: true,
link,
decoration: ItemDecoration.ICON_LINK,
}));
}
}
|
kink/kat
|
src/web/menu/LinkExchangeMenu.ts
|
TypeScript
|
unknown
| 732 |
import { pageHref } from '../data/hrefs';
import { Menu } from '../Menu';
import { ChaptersMenu } from './ChaptersMenu';
import { ContactMenu } from './ContactMenu';
import { LinkExchangeMenu } from './LinkExchangeMenu';
import { SettingsMenu } from './SettingsMenu';
import { StatsMenu } from './StatsMenu';
import { StyleMenu } from './StyleMenu';
import { ThanksMenu } from './ThanksMenu';
export class MainMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
this.container.classList.add('main');
this.buildSubMenu('Select Chapter', ChaptersMenu).build();
this.buildSubMenu('Credits', ThanksMenu).build();
this.buildSubMenu('Reader Style', StyleMenu).build();
this.buildSubMenu('Contact', ContactMenu).setUrlSegment('订阅及讨论组').build();
this.addItem('Latest Comments', { button: true, link: pageHref('recent-comments') });
this.buildSubMenu('Links', LinkExchangeMenu).build();
this.addItem('Source Code', { button: true, link: 'https://gitgud.io/RinTepis/wearable-technology' });
this.buildSubMenu('Settings', SettingsMenu).build();
this.buildSubMenu('Statistics', StatsMenu).build();
}
}
|
kink/kat
|
src/web/menu/MainMenu.ts
|
TypeScript
|
unknown
| 1,173 |
import { stylePreviewArticle } from '../constant/stylePreviewArticle';
import { newContent, Side } from '../control/contentControl';
import { Layout } from '../control/layoutControl';
import { showMirrorSitesModal } from '../control/mirrorControl';
import { animation, BooleanSetting, chapterRecommendationCount, charCount, contactInfo, developerMode, earlyAccess, enablePushHelper, EnumSetting, fontFamily, gestureSwitchChapter, showAbandonedChapters, useComments, warning, wtcdGameQuickLoadConfirm } from '../data/settings';
import { ItemDecoration, ItemHandle, Menu } from '../Menu';
import { UserMenu } from './UserMenu';
export class EnumSettingMenu extends Menu {
public constructor(urlBase: string, setting: EnumSetting, usePreview: boolean, callback: () => void) {
super(urlBase, usePreview ? Layout.SIDE : Layout.OFF);
let currentHandle: ItemHandle;
if (usePreview) {
const block = newContent(Side.RIGHT).addBlock();
block.element.innerHTML = stylePreviewArticle;
}
setting.options.forEach((valueName, value) => {
const handle = this.addItem(valueName, { button: true, decoration: ItemDecoration.SELECTABLE })
.onClick(() => {
currentHandle.setSelected(false);
handle.setSelected(true);
setting.setValue(value);
currentHandle = handle;
callback();
});
if (value === setting.getValue()) {
currentHandle = handle;
handle.setSelected(true);
}
});
}
}
export class SettingsMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
this.buildSubMenu('User Settings Menu', UserMenu).build();
this.addItem('Mirror Selection', { button: true }).onClick(() => {
showMirrorSitesModal();
});
this.addBooleanSetting('NSFW Warning', warning);
this.addBooleanSetting('Animations', animation);
this.addBooleanSetting('WIP Warning', earlyAccess);
this.addBooleanSetting('Show Comments', useComments);
this.addBooleanSetting('Chapter Gestures (iPhone)', gestureSwitchChapter);
this.addEnumSetting('Font', fontFamily, true);
this.addBooleanSetting('Display wordcount', charCount);
this.addBooleanSetting('WTCD Confirm before a save is loaded', wtcdGameQuickLoadConfirm);
this.addBooleanSetting('Developer Mode', developerMode);
this.addBooleanSetting('Show contact information at the end of articles', contactInfo);
this.addBooleanSetting('启用推送助手', enablePushHelper);
this.addBooleanSetting('Show abandoned chapters', showAbandonedChapters);
this.addEnumSetting('Recommended chapter count', chapterRecommendationCount);
}
public addBooleanSetting(label: string, setting: BooleanSetting) {
const getText = (value: boolean) => `${label}:${value ? 'On' : 'Off'}`;
const handle = this.addItem(getText(setting.getValue()), { button: true })
.onClick(() => {
setting.toggle();
});
setting.event.on(newValue => {
handle.setInnerText(getText(newValue));
});
}
public addEnumSetting(label: string, setting: EnumSetting, usePreview?: true) {
const getText = () => `${label}:${setting.getValueName()}`;
const handle = this.buildSubMenu(label, EnumSettingMenu, setting, usePreview === true, () => {
handle.setInnerText(getText());
}).setDisplayName(getText()).build();
}
}
|
kink/kat
|
src/web/menu/SettingsMenu.ts
|
TypeScript
|
unknown
| 3,373 |
import { data } from '../data/data';
import { ItemDecoration, Menu } from '../Menu';
import { shortNumber } from '../util/shortNumber';
export class StatsKeywordsCountMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
this.addItem('Add More Keywords', {
button: true,
link: 'https://gitgud.io/RinTepis/wearable-technology/-/blob/master/src/builder/keywords.ts',
decoration: ItemDecoration.ICON_LINK,
});
data.keywordsCount.forEach(([keyword, count]) => {
this.addItem(`${keyword}:${shortNumber(count, 2)}`);
});
}
}
|
kink/kat
|
src/web/menu/StatsKeywordsCountMenu.ts
|
TypeScript
|
unknown
| 590 |
import { data } from '../data/data';
import { pageHref } from '../data/hrefs';
import { ItemDecoration, Menu } from '../Menu';
import { shortNumber } from '../util/shortNumber';
import { StatsKeywordsCountMenu } from './StatsKeywordsCountMenu';
export class StatsMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
this.addItem('View Website Statistics', { button: true, link: pageHref('visit-count'), decoration: ItemDecoration.ICON_EQUALIZER });
this.buildSubMenu('Keyword Statistics', StatsKeywordsCountMenu)
.setDecoration(ItemDecoration.ICON_EQUALIZER)
.build();
this.addItem(`Total # of words:${data.charsCount === null ? 'unavailable' : shortNumber(data.charsCount, 2)}`);
this.addItem(`Total section: ${shortNumber(data.paragraphsCount, 2)}`);
}
}
|
kink/kat
|
src/web/menu/StatsMenu.ts
|
TypeScript
|
unknown
| 817 |
import { stylePreviewArticle } from '../constant/stylePreviewArticle';
import { newContent, Side } from '../control/contentControl';
import { Layout } from '../control/layoutControl';
import { DebugLogger } from '../DebugLogger';
import { h } from '../hs';
import { ItemDecoration, Menu } from '../Menu';
interface StyleDef {
readonly rectBgColor: string;
readonly paperBgColor: string;
readonly keyColor: [number, number, number];
readonly linkColor: string;
readonly linkHoverColor: string;
readonly linkActiveColor: string;
readonly commentColor: string;
readonly keyIsDark: boolean;
readonly contentBlockWarningColor: string;
}
class Style {
public static currentlyEnabled: Style | null = null;
private static themeColorMetaTag: HTMLMetaElement | null = null;
private styleSheet: StyleSheet | null = null;
private debugLogger: DebugLogger;
public constructor(
public readonly name: string,
public readonly def: StyleDef,
) {
this.debugLogger = new DebugLogger(`Style (${name})`);
}
private injectStyleSheet() {
const $style = document.createElement('style');
document.head.appendChild($style);
const sheet = $style.sheet as CSSStyleSheet;
sheet.disabled = true;
const attemptInsertRule = (rule: string) => {
try {
sheet.insertRule(rule);
} catch (error) {
this.debugLogger.error(`Failed to inject rule "${rule}".`, error);
}
};
const key = `rgb(${this.def.keyColor.join(',')})`;
const keyAlpha = (alpha: number) => `rgba(${this.def.keyColor.join(',')},${alpha})`;
// attemptInsertRule(`.container { color: ${key}; }`);
// attemptInsertRule(`.menu { color: ${key}; }`);
attemptInsertRule(`.menu .button:active::after { background-color: ${key}; }`);
attemptInsertRule(`.button::after { background-color: ${key}; }`);
attemptInsertRule(`body { background-color: ${this.def.paperBgColor}; }`);
// attemptInsertRule(`.rect { background-color: ${this.def.rectBgColor}; }`);
// attemptInsertRule(`.rect.reading>div { background-color: ${this.def.paperBgColor}; }`);
// attemptInsertRule(`.rect.reading>div { color: ${key}; }`);
// attemptInsertRule(`.rect.reading>.content a { color: ${this.def.linkColor}; }`);
// attemptInsertRule(`.rect.reading>.content a:hover { color: ${this.def.linkHoverColor}; }`);
// attemptInsertRule(`.rect.reading>.content a:active { color: ${this.def.linkActiveColor}; }`);
// attemptInsertRule(`.rect.reading .early-access.content-block { background-color: ${this.def.contentBlockEarlyAccessColor}; }`);
// attemptInsertRule(`.rect>.comments>div { background-color: ${this.def.commentColor}; }`);
// attemptInsertRule(`@media (min-width: 901px) { ::-webkit-scrollbar-thumb { background-color: ${this.def.paperBgColor}; } }`);
// attemptInsertRule(`.rect>.comments>.create-comment::before { background-color: ${key}; }`);
attemptInsertRule(`:root { --comment-color:${this.def.commentColor}; }`);
attemptInsertRule(`:root { --content-block-warning-color:${this.def.contentBlockWarningColor}; }`);
attemptInsertRule(`:root { --rect-bg-color: ${this.def.rectBgColor}; }`);
attemptInsertRule(`:root { --paper-bg-color: ${this.def.paperBgColor}; }`);
attemptInsertRule(`:root { --link-color: ${this.def.linkColor}; }`);
attemptInsertRule(`:root { --link-hover-color: ${this.def.linkHoverColor}; }`);
attemptInsertRule(`:root { --link-active-color: ${this.def.linkActiveColor}; }`);
attemptInsertRule(`:root { --key: ${key}; }`);
attemptInsertRule(`:root { --key-opacity-01: ${keyAlpha(0.1)}; }`);
attemptInsertRule(`:root { --key-opacity-014: ${keyAlpha(0.14)}; }`);
attemptInsertRule(`:root { --key-opacity-015: ${keyAlpha(0.15)}; }`);
attemptInsertRule(`:root { --key-opacity-023: ${keyAlpha(0.23)}; }`);
attemptInsertRule(`:root { --key-opacity-05: ${keyAlpha(0.5)}; }`);
attemptInsertRule(`:root { --key-opacity-07: ${keyAlpha(0.7)}; }`);
attemptInsertRule(`:root { --key-opacity-007: ${keyAlpha(0.07)}; }`);
attemptInsertRule(`:root { --key-opacity-004: ${keyAlpha(0.04)}; }`);
attemptInsertRule(`:root { --button-color: ${this.def.commentColor}; }`);
this.styleSheet = sheet;
}
public activate() {
if (Style.currentlyEnabled !== null) {
const currentlyEnabled = Style.currentlyEnabled;
if (currentlyEnabled.styleSheet !== null) {
currentlyEnabled.styleSheet.disabled = true;
}
}
if (this.styleSheet === null) {
this.injectStyleSheet();
}
this.styleSheet!.disabled = false;
window.localStorage.setItem('style', this.name);
if (Style.themeColorMetaTag === null) {
Style.themeColorMetaTag = h('meta', {
name: 'theme-color',
content: this.def.paperBgColor,
});
document.head.appendChild(Style.themeColorMetaTag!);
} else {
Style.themeColorMetaTag.content = this.def.paperBgColor;
}
Style.currentlyEnabled = this;
}
}
const darkKeyLinkColors = {
linkColor: '#00E',
linkHoverColor: '#F00',
linkActiveColor: '#00E',
};
const lightKeyLinkColors = {
linkColor: '#7AB2E2',
linkHoverColor: '#5A92C2',
linkActiveColor: '#5A92C2',
};
const styles = [
new Style('Wearable Technology (Default)', {
rectBgColor: '#444',
paperBgColor: '#333',
keyColor: [221, 221, 221],
...lightKeyLinkColors,
contentBlockWarningColor: '#E65100',
commentColor: '#444',
keyIsDark: false,
}),
new Style('White Paper', {
rectBgColor: '#EFEFED',
paperBgColor: '#FFF',
keyColor: [0, 0, 0],
...darkKeyLinkColors,
contentBlockWarningColor: '#FFE082',
commentColor: '#F5F5F5',
keyIsDark: true,
}),
new Style('Night', {
rectBgColor: '#272B36',
paperBgColor: '#38404D',
keyColor: [221, 221, 221],
...lightKeyLinkColors,
contentBlockWarningColor: '#E65100',
commentColor: '#272B36',
keyIsDark: false,
}),
new Style('Parchment', {
rectBgColor: '#D8D4C9',
paperBgColor: '#F8F4E9',
keyColor: [85, 40, 48],
...darkKeyLinkColors,
contentBlockWarningColor: '#FFE082',
commentColor: '#F9EFD7',
keyIsDark: true,
}),
new Style('Chocolate', {
rectBgColor: '#2E1C11',
paperBgColor: '#3A2519',
keyColor: [221, 175, 153],
...lightKeyLinkColors,
contentBlockWarningColor: '#E65100',
commentColor: '#2C1C11',
keyIsDark: false,
}),
];
export class StyleMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase, Layout.SIDE);
const handles = styles.map(style => {
const handle = this.addItem(style.name, { button: true, decoration: ItemDecoration.SELECTABLE })
.onClick(() => {
style.activate();
handles.forEach(handle => handle.setSelected(false));
handle.setSelected(true);
});
if (window.localStorage.getItem('style') === style.name) {
handle.setSelected(true);
}
return handle;
});
const content = newContent(Side.RIGHT);
const $div = content.addBlock().element;
$div.innerHTML = stylePreviewArticle;
}
}
const usedStyle = window.localStorage.getItem('style');
let flag = false;
for (const style of styles) {
if (usedStyle === style.name) {
style.activate();
flag = true;
break;
}
}
if (!flag) {
styles[0].activate();
}
|
kink/kat
|
src/web/menu/StyleMenu.ts
|
TypeScript
|
unknown
| 7,390 |
import { thanks } from '../constant/thanks';
import { ItemDecoration, Menu } from '../Menu';
export class ThanksMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
for (const person of thanks) {
this.addItem(person.name, person.link === undefined
? {}
: { button: true, link: person.link, decoration: ItemDecoration.ICON_LINK },
);
}
}
}
|
kink/kat
|
src/web/menu/ThanksMenu.ts
|
TypeScript
|
unknown
| 405 |
import { showLoginModal, showUpdateProfileModal } from '../control/userControl';
import { Menu } from '../Menu';
export class UserMenu extends Menu {
public constructor(urlBase: string) {
super(urlBase);
this.addItem('Identity Token', { button: true }).onClick(() => {
showLoginModal();
});
this.addItem('Edit User Info', { button: true }).onClick(() => {
showUpdateProfileModal();
});
}
}
|
kink/kat
|
src/web/menu/UserMenu.ts
|
TypeScript
|
unknown
| 427 |
import { AUTHOR_PAGE_AS, AUTHOR_PAGE_LINK, AUTHOR_PAGE_WORKS, AUTHOR_PAGE_WORKS_DESC, GO_TO_MENU } from '../constant/messages';
import { getRolePriority } from '../constant/rolePriorities';
import { setNavbarPath } from '../control/navbarControl';
import { Page } from '../control/pageControl';
import { authorInfoMap, relativePathLookUpMap } from '../data/data';
import { chapterHref } from '../data/hrefs';
import { h } from '../hs';
import { formatRelativePath } from '../util/formatRelativePath';
import { padName } from '../util/padName';
export const author: Page = {
name: 'author',
handler: (content, pagePath) => {
const authorName = pagePath.get();
setNavbarPath([
{ display: 'Artist List', hash: '#/menu/章节选择/按作者检索' },
{ display: authorName, hash: null },
]);
const author = authorInfoMap.get(authorName);
const block = content.addBlock();
block.element.appendChild(h('h1', authorName));
if (author?.description !== undefined) {
block.element.appendChild(h('p', author.description));
}
const roleChaptersMap = new Map<string, Array<string>>();
for (const [relativePath, { chapter: { authors } }] of relativePathLookUpMap.entries()) {
for (const { name, role } of authors) {
if (name !== authorName) {
continue;
}
if (!roleChaptersMap.has(role)) {
roleChaptersMap.set(role, [relativePath]);
} else {
roleChaptersMap.get(role)!.push(relativePath);
}
}
}
block.element.appendChild(h('h2', AUTHOR_PAGE_WORKS));
block.element.appendChild(h('p', AUTHOR_PAGE_WORKS_DESC.replace('$', padName(authorName))));
const roleChaptersArray = Array.from(roleChaptersMap);
roleChaptersArray.sort(([roleA, _], [roleB, __]) => getRolePriority(roleB) - getRolePriority(roleA));
for (const [role, relativePaths] of roleChaptersArray) {
block.element.appendChild(h('h4', AUTHOR_PAGE_AS + role));
const $list = h('ul');
for (const relativePath of relativePaths) {
$list.appendChild(h('li',
formatRelativePath(relativePath),
'(',
h('a.regular', {
href: chapterHref(relativePath),
}, AUTHOR_PAGE_LINK),
')',
));
}
block.element.appendChild($list);
}
block.element.appendChild(h('div.page-switcher', [
h('a.to-menu', {
href: window.location.pathname,
onclick: (event: MouseEvent) => {
event.preventDefault();
history.back();
},
}, GO_TO_MENU),
]));
return true;
},
};
|
kink/kat
|
src/web/pages/author.ts
|
TypeScript
|
unknown
| 2,629 |
import { COMMENTS_RECENT_SECTION } from '../constant/messages';
import { loadRecentComments } from '../control/commentsControl';
import { setNavbarPath } from '../control/navbarControl';
import { Page } from '../control/pageControl';
export const recentComments: Page = {
name: 'recent-comments',
handler: content => {
setNavbarPath([{ display: COMMENTS_RECENT_SECTION, hash: null }]);
loadRecentComments(content);
return true;
},
};
|
kink/kat
|
src/web/pages/recentComments.ts
|
TypeScript
|
unknown
| 453 |
import { COMMENTS_MENTION_NO_TOKEN_DESC, COMMENTS_MENTION_NO_TOKEN_TITLE, COMMENTS_MENTION_SECTION } from '../constant/messages';
import { loadRecentMentions } from '../control/commentsControl';
import { setNavbarPath } from '../control/navbarControl';
import { Page } from '../control/pageControl';
import { removeNewMentionLink } from '../control/userControl';
import { h } from '../hs';
export const recentMentions: Page = {
name: 'recent-mentions',
handler: content => {
setNavbarPath([{ display: COMMENTS_MENTION_SECTION, hash: null }]);
// ! In the name of spaghetti
setTimeout(() => {
removeNewMentionLink();
}, 500);
localStorage.setItem('lastCheckedMention', String(Date.now()));
if (localStorage.getItem('token') === null) {
content.addBlock({
initElement: h('div',
h('h1', COMMENTS_MENTION_NO_TOKEN_TITLE),
h('p', COMMENTS_MENTION_NO_TOKEN_DESC),
)
});
} else {
loadRecentMentions(content, localStorage.getItem('token')!);
}
return true;
},
};
|
kink/kat
|
src/web/pages/recentMentions.ts
|
TypeScript
|
unknown
| 1,059 |
import { $e } from '../$e';
import { ContentBlock, ContentBlockSide, ContentBlockStyle } from '../control/contentControl';
import { Modal } from '../control/modalControl';
import { setNavbarPath } from '../control/navbarControl';
import { Page } from '../control/pageControl';
import { search, SearchInput } from '../control/searchControl';
import { data, tagAliasMap } from '../data/data';
import { chapterHref } from '../data/hrefs';
import { autoExpandTextArea } from '../util/DOM';
import { formatRelativePath } from '../util/formatRelativePath';
import { tagSpan } from '../util/tag';
function resolveAlias(maybeAliased: string) {
let modifier: string = '';
if ('+-'.includes(maybeAliased[0])) {
modifier = maybeAliased[0];
maybeAliased = maybeAliased.substr(1);
}
const split = maybeAliased.split('(');
if (tagAliasMap.has(split[0].toLowerCase())) {
split[0] = tagAliasMap.get(split[0].toLowerCase())!;
}
return modifier + split.join('(');
}
export const tagSearch: Page = {
name: 'tag-search',
handler: (content, pagePath) => {
setNavbarPath([{ display: '标签搜索', hash: null }]);
content.addBlock({
initElement: (
<div>
<h1>Most articles don't have tags!</h1>
<p>Note that this system can only search through articles based on the tags the article has. As this system was only implemented recently, the majority of articles don't have any tags. Articles without tags will not be searched.</p>
<p>If you are willing to help add tags <a className='regular' href={ chapterHref('META/协助打标签.html') }>visit here</a>.</p>
</div>
),
style: ContentBlockStyle.WARNING,
});
content.appendLeftSideContainer();
const $textarea = (<textarea className='general small'/>) as HTMLTextAreaElement;
$textarea.value = pagePath.get().split('/').join('\n');
const updateTextAreaSize = autoExpandTextArea($textarea, 40);
function openTagsList() {
const modal = new Modal(
<div style={{ width: '1000px' }}>
<h1>Tag List</h1>
<p>Not every tag has an article</p>
<p>
{ data.tags.map(([tag]) => {
let selected = $textarea.value.trim().split(/\s+/).includes(tag);
const $tag = tagSpan(tag, selected);
$tag.addEventListener('click', () => {
if (selected) {
$textarea.value = $textarea.value.replace(new RegExp(`(^|\\s+)${tag}(?=$|\\s)`, 'g'), '');
} else {
$textarea.value += `\n${tag}`;
}
$textarea.value = $textarea.value.trim();
updateSearch($textarea.value);
updateTextAreaSize();
selected = !selected;
$tag.classList.toggle('active', selected);
});
return $tag;
}) }
</p>
<div className='button-container'>
<div onclick={ () => modal.close() }>关闭</div>
</div>
</div> as HTMLDivElement
);
modal.setDismissible();
modal.open();
}
let $errorList: HTMLElement | null = null;
const searchBlock = content.addBlock({
initElement: (
<div>
<p>Please enter the tag you want to search for</p>
{ $textarea }
<div className='button-container' style={{ marginTop: '0.6em' }}>
<div onclick={ openTagsList }>Select Tag</div>
</div>
</div>
),
side: ContentBlockSide.LEFT,
});
const searchInfoBlock = content.addBlock({
initElement: (
<div>
<h1>Tag Search</h1>
<p>Enter the tag you need to find in the search input box to begin the search.</p>
<p>Seperate tags by using spaces or line breaks.</p>
<p>Adding a minus sign before a tag can exclude the label. (For example:<code>-含有男性</code>)</p>
<p>Adding a plus sign before a tag forces it to be required (For example: <code>+贞操带</code>)</p>
<p>You can also click below the search input box at <b>Select Tag</b> to quickly select.</p>
</div>
),
}).hide();
const noResultsBlock = content.addBlock({
initElement: (
<div>
<h1>Sorry, no matching articles were found.</h1>
<p>This tag search system can only search for article tags, not article titles or content. Check that the search tag you're using is the correct 《WEARABLE TECHNOLOGY》 article. You can list all available tags by clicking on the <b>Select Tag</b> below the search input box.</p>
<p>Because the label system has only just been implemented, the vast majority of articles have no labels. All articles without tags will not be searched. If you find that your favorite article doesn't have a tag yet, you can choose to help tag it.</p>
</div>
),
}).hide();
const chapterBlocks: Array<ContentBlock> = [];
let searchId = 0;
async function updateSearch(searchText: string) {
searchId++;
const thisSearchId = searchId;
searchText = searchText.trim();
const searchTerms = searchText.split(/\s+/).map(resolveAlias).filter(searchTerm => searchTerm !== '');
pagePath.set(searchTerms.join('/'));
const searchInput: SearchInput = searchTerms.map(searchTerm => {
if (searchTerm.startsWith('+')) {
return { searchTag: searchTerm.substr(1), type: 'required' };
}
if (searchTerm.startsWith('-')) {
return { searchTag: searchTerm.substr(1), type: 'excluded' };
}
return { searchTag: searchTerm, type: 'favored' };
});
const searchResult = await search(searchInput);
if (thisSearchId !== searchId) {
// New search launched.
return;
}
const errors: Array<HTMLElement> = [];
for (const { searchTag } of searchInput) {
const match = searchTag.match(/^[+-]?(\S+?)(?:((\S+?)))?$/)!;
const tagTuple = data.tags.find(([tag]) => tag === match[1]);
if (tagTuple === undefined) {
errors.push(<li>Tag "{ match[1] }" doesn't exist.</li>);
} else if (match[2] !== undefined) {
if (tagTuple[1] === null) {
errors.push(<li>Tag "{ match[1] }" does not support gender varieties.</li>);
} else if (!tagTuple[1].includes(match[2])) {
errors.push(<li>Tag "{ match[1] }" has no gender varieties "{ match[2] }".</li>);
}
}
}
$errorList?.remove();
if (errors.length !== 0) {
$errorList = (
<ul>{ ...errors }</ul>
);
searchBlock.element.append($errorList);
}
chapterBlocks.forEach(chapterBlock => chapterBlock.directRemove());
chapterBlocks.length = 0;
function showResultsFrom(startIndex: number) {
const maxIndex = Math.min(searchResult.length - 1, startIndex + 9);
for (let i = startIndex; i <= maxIndex; i++) {
const { chapter, score, matchedTags } = searchResult[i];
const chapterBlock = content.addBlock({
initElement: (
<div className='tag-search-chapter'>
{ (searchInput.length !== 1) && (
<p className='match-ratio'>匹配率:<span style={{
fontWeight: (score === searchInput.length) ? 'bold' : 'normal'
}}>{ (score / searchInput.length * 100).toFixed(0) }%</span></p>
) }
<h3 className='chapter-title'>
<a href={ chapterHref(chapter.htmlRelativePath) }>
{ formatRelativePath(chapter.htmlRelativePath) }
</a>
</h3>
<p>{ chapter.authors.map(authorInfo => authorInfo.role + ':' + authorInfo.name).join(',') }</p>
{ chapter.tags?.map(tag => {
const selected = matchedTags.includes(tag);
const $tag = tagSpan(tag, selected);
$tag.addEventListener('click', () => {
if (!selected) {
$textarea.value += `\n${tag}`;
} else {
let value = $textarea.value.replace(new RegExp(`(^|\\s+)\\+?${tag}(?=$|\\s)`, 'g'), '');
if (tag.includes('(')) {
value = value.replace(new RegExp(`(^|\\s+)\\+?${tag.split('(')[0]}(?=$|\\s)`, 'g'), '');
}
value = value.trim();
$textarea.value = value;
}
updateSearch($textarea.value);
updateTextAreaSize();
});
return $tag;
}) }
</div>
)
});
if (i === maxIndex && maxIndex < searchResult.length - 1) {
chapterBlock.onEnteringView(() => showResultsFrom(i + 1));
}
chapterBlocks.push(chapterBlock);
}
}
noResultsBlock.hide();
searchInfoBlock.hide();
if (searchResult.length === 0) {
if (searchText === '') {
searchInfoBlock.show();
} else {
noResultsBlock.show();
}
} else {
showResultsFrom(0);
}
}
updateSearch($textarea.value);
$textarea.addEventListener('input', () => updateSearch($textarea.value));
return true;
},
};
|
kink/kat
|
src/web/pages/tagSearch.tsx
|
TypeScript
|
unknown
| 9,469 |
import { $e } from '../$e';
import { TagSpec, TagsSpec } from '../../TagsSpec';
import { Content } from '../control/contentControl';
import { confirm, Modal, showGenericError, showGenericSuccess } from '../control/modalControl';
import { setNavbarPath } from '../control/navbarControl';
import { Page } from '../control/pageControl';
import { dbKVGet, dbKVKey, dbKVSet } from '../data/db';
import { DebugLogger } from '../DebugLogger';
import { h } from '../hs';
import { autoExpandTextArea } from '../util/DOM';
const debugLogger = new DebugLogger('Tagging Tool');
const selectedKey = dbKVKey<Array<string>>('taggingToolSelected');
const showingVariantsKey = dbKVKey<Array<string>>('taggingToolShowingVariants');
function createTagVariant(tag: string, variant: string) {
return `${tag}(${variant})`;
}
export const taggingTool: Page = {
name: 'tagging-tool',
handler: (content: Content) => {
setNavbarPath([{ display: '标签工具', hash: null }]);
const loadingBlock = content.addBlock({
initElement: h('div', '正在加载标签规格...')
});
(async () => {
const tagsSpec: TagsSpec = JSON.parse(await fetch('./tagsSpec.json')
.then(response => response.text()));
const showingVariants = new Set(await dbKVGet(showingVariantsKey) ?? ['女']);
loadingBlock.directRemove();
/** Mapping from tag to tag spec */
const tagSpecMap: Map<string, TagSpec> = new Map();
const tagIndexMap: Map<string, number> = new Map();
let index = 0;
for (const tagSpec of tagsSpec) {
tagSpecMap.set(tagSpec.tag, tagSpec);
tagIndexMap.set(tagSpec.tag, index);
index++;
}
const selectedTagVariants = new Set<string>();
const mainBlock = content.addBlock({ initElement: h('.tagging-tool') as HTMLDivElement });
const tagVariantElementsMap: Map<string, Array<{
span: HTMLSpanElement,
checkbox: HTMLInputElement,
}>> = new Map();
const variantsSet = new Set<string>();
tagsSpec.forEach(tagSpec => tagSpec.variants?.forEach(variant => variantsSet.add(variant)));
const variantMap: Map<string, Array<{
tagVariantSpan: HTMLSpanElement,
tag: string,
}>> = new Map(Array.from(variantsSet).map(variant => [variant, []]));
const prerequisiteLIs = new Array<HTMLLIElement>();
const prerequisites: Array<{
sourceTagVariant: string,
requiresTagVariants: Array<string>,
span: HTMLSpanElement,
li: HTMLLIElement,
}> = [];
const $selectedOutputCode = h('code');
function setSelected(tagVariant: string, value: boolean) {
const tagVariantElements = tagVariantElementsMap.get(tagVariant);
if (tagVariantElements === undefined) {
debugLogger.warn('Unknown tag variant:', tagVariant);
return false;
}
for (const { checkbox, span } of tagVariantElements) {
checkbox.checked = value;
span.classList.toggle('selected', value);
}
if (value) {
selectedTagVariants.add(tagVariant);
} else {
selectedTagVariants.delete(tagVariant);
}
for (const prerequisiteLI of prerequisiteLIs) {
prerequisiteLI.classList.remove('errored');
}
for (const tagVariantElements of tagVariantElementsMap.values()) {
for (const { span } of tagVariantElements) {
span.classList.remove('errored');
}
}
let errored = false;
for (const { sourceTagVariant, requiresTagVariants, span, li } of prerequisites) {
if (selectedTagVariants.has(sourceTagVariant) && !requiresTagVariants.some(requiresTagVariant => selectedTagVariants.has(requiresTagVariant))) {
errored = true;
li.classList.add('errored');
span.classList.add('errored');
}
}
if (errored) {
$selectedOutputCode.innerText = '有未满足的前置标签,输出已终止。缺失的前置标签已用红色标出。';
} else if (selectedTagVariants.size === 0) {
$selectedOutputCode.innerText = '请至少选择一个标签。';
} else {
$selectedOutputCode.innerText = Array
.from(selectedTagVariants)
.sort((a, b) => {
const aTag = a.split('(')[0];
const bTag = b.split('(')[0];
const comparePriority = tagSpecMap.get(bTag)!.priority - tagSpecMap.get(aTag)!.priority;
if (comparePriority !== 0) {
return comparePriority;
}
return tagIndexMap.get(aTag)! - tagIndexMap.get(bTag)!;
})
.join(',');
}
dbKVSet(selectedKey, Array.from(selectedTagVariants)).catch(error => debugLogger.error(error));
return true;
}
function setHovered(tagVariant: string, hovered: boolean) {
const tagVariantElements = tagVariantElementsMap.get(tagVariant)!;
for (const { span } of tagVariantElements) {
span.classList.toggle('hovered', hovered);
}
}
function createTagVariantElements(display: string, tag: string, variant?: string) {
const tagVariant = (variant === undefined) ? tag : createTagVariant(tag, variant);
const $checkbox = h('input', { type: 'checkbox' });
let tagVariantElements = tagVariantElementsMap.get(tagVariant);
if (tagVariantElements === undefined) {
tagVariantElements = [];
tagVariantElementsMap.set(tagVariant, tagVariantElements);
}
const $tagVariantSpan = h('span.tagging-tool-tag-variant', [
$checkbox,
display,
]) as HTMLSpanElement;
if (variant !== undefined) {
variantMap.get(variant)!.push({
tag,
tagVariantSpan: $tagVariantSpan,
});
}
tagVariantElements.push({
checkbox: $checkbox,
span: $tagVariantSpan,
});
$tagVariantSpan.addEventListener('click', () => {
if (selectedTagVariants.has(tagVariant)) {
setSelected(tagVariant, false);
} else {
setSelected(tagVariant, true);
}
});
$tagVariantSpan.addEventListener('mouseenter', () => {
setHovered(tagVariant, true);
});
$tagVariantSpan.addEventListener('mouseleave', () => {
setHovered(tagVariant, false);
});
return $tagVariantSpan;
}
function createTagElement(tagSpec: TagSpec, prerequisiteInfo?: { li: HTMLLIElement, sourceTagSpec: TagSpec }) {
if (tagSpec.variants === null) {
const $span = createTagVariantElements(tagSpec.tag, tagSpec.tag);
if (prerequisiteInfo !== undefined) {
const sourceTagSpec = prerequisiteInfo.sourceTagSpec;
if (sourceTagSpec.variants === null) {
prerequisites.push({
sourceTagVariant: sourceTagSpec.tag,
requiresTagVariants: [ tagSpec.tag ],
li: prerequisiteInfo.li,
span: $span,
});
} else {
for (const sourceVariant of sourceTagSpec.variants) {
prerequisites.push({
sourceTagVariant: createTagVariant(sourceTagSpec.tag, sourceVariant),
requiresTagVariants: [ tagSpec.tag ],
li: prerequisiteInfo.li,
span: $span,
});
}
}
}
return $span;
} else {
const spans: Array<HTMLSpanElement> = [];
for (const variant of tagSpec.variants) {
const $span = createTagVariantElements(
variant,
tagSpec.tag,
variant,
);
if (prerequisiteInfo !== undefined) {
const sourceTagSpec = prerequisiteInfo.sourceTagSpec;
if (sourceTagSpec.variants !== null) {
prerequisites.push({
sourceTagVariant: createTagVariant(sourceTagSpec.tag, variant),
requiresTagVariants: [ createTagVariant(tagSpec.tag, variant) ],
li: prerequisiteInfo.li,
span: $span,
});
} else {
prerequisites.push({
sourceTagVariant: sourceTagSpec.tag,
requiresTagVariants: tagSpec.variants.map(variant => createTagVariant(tagSpec.tag, variant)),
li: prerequisiteInfo.li,
span: $span,
});
}
}
spans.push($span);
}
return h(
'span.tagging-tool-tag',
[
tagSpec.tag,
h('span.no-available-variants', '无可用变种'),
...spans,
],
);
}
}
mainBlock.element.append(
<h1>标签工具</h1>,
<p>请注意,在《可穿戴科技》的标签系统中:
<ul>
<li>标签变种“男”是指非伪娘男性。如果小说中的角色是伪娘,请勿使用男性标签变种。</li>
<li>标签变种“机械”是指非人形机械,例如大型调教设备。如果小说中的角色是机器人,请用机器人的性别。</li>
</ul>
</p>,
<h2>标签变种过滤</h2>,
<p>请选择在小说中出现的人物性别。</p>,
<p>这些选项只会暂时隐藏对应的标签变种,在输出标签列表时,依然会输出在隐藏前所选择的标签。</p>,
);
const updateVariantFilter: Array<() => void> = [];
for (const variant of variantsSet) {
let selected = showingVariants.has(variant);
const $checkbox = h('input', { type: 'checkbox' });
const $span = h('span.tagging-tool-variant', [
$checkbox,
variant,
]);
const update = () => {
if (selected) {
showingVariants.add(variant);
} else {
showingVariants.delete(variant);
}
dbKVSet(showingVariantsKey, Array.from(showingVariants));
$checkbox.checked = selected;
$span.classList.toggle('selected', selected);
variantMap.get(variant)!.forEach(({ tagVariantSpan }) => {
tagVariantSpan.classList.toggle('display-none', !selected);
tagVariantSpan.parentElement!.classList.toggle(
'has-available-variant',
Array.from(tagVariantSpan.parentElement!.getElementsByClassName('tagging-tool-tag-variant'))
.some($element => !$element.classList.contains('display-none')),
);
});
};
updateVariantFilter.push(update);
$span.addEventListener('click', () => {
selected = !selected;
update();
});
mainBlock.element.append($span);
}
mainBlock.element.append(h('h2', '选择标签'));
function requestResettingTags() {
confirm('真的要重置所有选择的标签吗?', '这个操作不可撤销。', '确定重置', '不重置').then(result => {
if (result) {
for (const selectedTagVariant of selectedTagVariants) {
setSelected(selectedTagVariant, false);
}
}
});
}
function requestImportTags() {
const $textarea = <textarea className='general large' /> as HTMLTextAreaElement;
async function execute(replace: boolean) {
const value = $textarea.value.trim();
if (value === '') {
showGenericError('请输入要导入的标签。');
return;
}
if (replace) {
if (!await confirm('确定导入', '这将重置目前已经选择的所有标签。你真的要继续吗?', '确定导入', '取消导入')) {
return;
}
for (const selectedTagVariant of selectedTagVariants) {
setSelected(selectedTagVariant, false);
}
}
const failed: Array<string> = [];
for (const tagVariant of value.split(/[\s,,]+/)) {
if (!setSelected(tagVariant, true)) {
failed.push(tagVariant);
}
}
if (failed.length === 0) {
await showGenericSuccess('导入成功');
modal.close();
} else {
const warnModal = new Modal(
<div>
<h1>部分标签未能导入</h1>
<p>以下为导入失败的标签:</p>
<ul>{ failed.map(tagVariant => <li>{ tagVariant }</li>) }</ul>
<p>其余标签已导入完成。</p>
<div className='button-container'><div onclick={ () => warnModal.close() }>关闭</div></div>
</div> as HTMLDivElement
);
warnModal.setDismissible();
warnModal.open();
}
}
const modal = new Modal(
<div>
<h1>导入标签</h1>
<p>请输入要导入的标签,不同标签之间请用空格或逗号分开:</p>
{ $textarea }
<div className='button-container' style={{ marginTop: '0.6em' }}>
<div onclick={ () => execute(true) }>替换当前标签</div>
<div onclick={ () => execute(false) }>追加到当前标签</div>
<div onclick={ () => modal.close() }>取消导入</div>
</div>
</div> as HTMLDivElement
);
modal.setDismissible();
modal.open();
autoExpandTextArea($textarea);
}
mainBlock.element.append(
<div className='button-container'>
<div onclick={ requestResettingTags }>重置所有选择的标签</div>
<div onclick={ requestImportTags }>导入标签</div>
</div>
);
mainBlock.element.append(<p>请选择小说所含有的标签:</p>);
for (const tagSpec of tagsSpec) {
mainBlock.element.append(h('p.tag-title', createTagElement(tagSpec)));
const $descUL = h('ul');
for (const descLine of tagSpec.desc) {
const $descLineLI = h('li.desc-line') as HTMLLIElement;
if (descLine.isPrerequisite) {
prerequisiteLIs.push($descLineLI);
}
for (const segment of descLine.segments) {
if (segment.type === 'text') {
$descLineLI.append(segment.content);
} else {
if (descLine.isPrerequisite) {
$descLineLI.append(createTagElement(
tagSpecMap.get(segment.tag)!, {
li: $descLineLI,
sourceTagSpec: tagSpec,
})
);
} else {
$descLineLI.append(createTagElement(tagSpecMap.get(segment.tag)!));
}
}
}
$descUL.append($descLineLI);
}
mainBlock.element.append($descUL);
}
mainBlock.element.append(h('h2', '输出'));
mainBlock.element.append(h('p', '以下为选择的标签。'));
mainBlock.element.append(h('pre.wrapping', $selectedOutputCode));
mainBlock.element.append(
<p>
如果想要为其他文章打标签,请<span className='anchor-style' onclick={ requestResettingTags }>点此重置已经选择了的标签</span>。
</p>
);
updateVariantFilter.forEach(update => update());
(await dbKVGet(selectedKey) ?? []).forEach(tagVariant => setSelected(tagVariant, true));
})().catch(error => debugLogger.error(error));
return true;
},
};
|
kink/kat
|
src/web/pages/taggingTool.tsx
|
TypeScript
|
unknown
| 15,770 |
// !!! Super spaghetti code warning !!!
import { GO_TO_MENU, VISIT_COUNT_DESC_0, VISIT_COUNT_DESC_1, VISIT_COUNT_DESC_2, VISIT_COUNT_DISPLAYING, VISIT_COUNT_FAILED, VISIT_COUNT_LOADING, VISIT_COUNT_LOAD_MORE, VISIT_COUNT_LOAD_MORE_FAILED, VISIT_COUNT_LOAD_MORE_LOADING, VISIT_COUNT_TIMES, VISIT_COUNT_TIME_FRAME_ALL, VISIT_COUNT_TIME_FRAME_DAY, VISIT_COUNT_TIME_FRAME_HOUR, VISIT_COUNT_TIME_FRAME_MONTH, VISIT_COUNT_TIME_FRAME_WEEK, VISIT_COUNT_TIME_FRAME_YEAR, VISIT_COUNT_TITLE } from '../constant/messages';
import { backendUrl } from '../control/backendControl';
import { enterMenuMode } from '../control/menuControl';
import { setNavbarPath } from '../control/navbarControl';
import { Page } from '../control/pageControl';
import { AutoCache } from '../data/AutoCache';
import { relativePathLookUpMap } from '../data/data';
import { chapterHref } from '../data/hrefs';
import { DebugLogger } from '../DebugLogger';
import { h } from '../hs';
import { commaNumber } from '../util/commaNumber';
import { formatRelativePath } from '../util/formatRelativePath';
import { padName } from '../util/padName';
import { shortNumber } from '../util/shortNumber';
type TimeFrame = 'ALL' | 'HOUR' | 'DAY' | 'WEEK' | 'MONTH' | 'YEAR';
const timeFrames: Array<TimeFrame> = ['ALL', 'HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR'];
function getEndpoint(timeFrame: TimeFrame, page: number) {
if (timeFrame === 'ALL') {
return `${backendUrl}/stats/chapters/all?page=${page}`;
} else {
return `${backendUrl}/stats/chapters/recent?page=${page}&time_frame=${timeFrame}`;
}
}
const debugLogger = new DebugLogger('Visit Count Logger');
function getTimeFrameText(timeFrame: TimeFrame) {
switch (timeFrame) {
case 'ALL': return VISIT_COUNT_TIME_FRAME_ALL;
case 'HOUR': return VISIT_COUNT_TIME_FRAME_HOUR;
case 'DAY': return VISIT_COUNT_TIME_FRAME_DAY;
case 'WEEK': return VISIT_COUNT_TIME_FRAME_WEEK;
case 'YEAR': return VISIT_COUNT_TIME_FRAME_YEAR;
case 'MONTH': return VISIT_COUNT_TIME_FRAME_MONTH;
}
}
function formatTitle(relativePath: string, visitCount: number) {
return formatRelativePath(relativePath) + ': ' + shortNumber(visitCount, 2) + VISIT_COUNT_TIMES;
}
const visitCountCache = new AutoCache<string, any>(
endpoint => fetch(endpoint).then(data => data.json()),
new DebugLogger('Visit Count Cache'),
);
export const visitCount: Page = {
name: 'visit-count',
handler: content => {
setNavbarPath([{ display: VISIT_COUNT_TITLE, hash: null }]);
const block = content.addBlock();
block.element.appendChild(h('h1', VISIT_COUNT_TITLE));
block.element.appendChild(h('p', [
VISIT_COUNT_DESC_0,
h('a.regular', { href: '#META/隐私政策.html' }, VISIT_COUNT_DESC_1),
VISIT_COUNT_DESC_2,
]));
const $status = h('p');
const $results = h('.visit-count-holder') as HTMLDivElement;
const $loadMoreButton = h('div.rich') as HTMLDivElement;
const $loadMoreContainer = h('.button-container.display-none', {
style: { 'margin-top': '0.5em' },
}, $loadMoreButton) as HTMLDivElement;
// Used to determine whether the current request is still needed.
let currentRequestId = 0;
// Time frame to be used when clicking load more.
let nextLoadingTimeFrame: TimeFrame = 'ALL';
// Page to be load when clicking load more.
let nextLoadingPage = 2;
let maxVisits = 0;
const load = (timeFrame: TimeFrame, page: number) => {
const endpoint = getEndpoint(timeFrame, page);
currentRequestId++;
const requestId = currentRequestId;
debugLogger.log(`Request ID ${requestId}: Loading visit count info from ${endpoint}.`);
visitCountCache.get(endpoint).then(data => {
if (content.isDestroyed || requestId !== currentRequestId) {
debugLogger.log(`Request ID ${requestId}: Request completed, but the result is abandoned.`);
return;
}
if (page === 1) {
maxVisits = (data[0]?.visit_count) ?? 0;
$loadMoreContainer.classList.remove('display-none');
} else {
$loadMoreButton.classList.remove('disabled');
}
$status.innerText = VISIT_COUNT_DISPLAYING.replace(/\$/g, padName(getTimeFrameText(timeFrame)));
$loadMoreButton.innerText = VISIT_COUNT_LOAD_MORE;
// If there is less than 50, stop showing load more button
$loadMoreContainer.classList.toggle('display-none', data.length !== 50);
for (const entry of data) {
if (!relativePathLookUpMap.has(entry.relative_path)) {
continue;
}
$results.appendChild(h(
'a', {
style: {
'width': `${entry.visit_count / maxVisits * 100}%`,
},
title: commaNumber(entry.visit_count) + VISIT_COUNT_TIMES,
href: chapterHref(entry.relative_path),
}, formatTitle(entry.relative_path, entry.visit_count),
));
}
nextLoadingPage = page + 1;
}).catch(error => {
if (content.isDestroyed || requestId !== currentRequestId) {
debugLogger.warn(`Request ID ${requestId}: Request failed, but the result is abandoned.`, error);
return;
}
if (page === 1) {
$status.innerText = VISIT_COUNT_FAILED;
} else {
$loadMoreButton.classList.remove('disabled');
$loadMoreButton.innerText = VISIT_COUNT_LOAD_MORE_FAILED;
}
});
};
$loadMoreButton.addEventListener('click', () => {
// Yes, I am doing it. I am using class list as my state keeper.
if ($loadMoreButton.classList.contains('disabled')) {
return;
}
$loadMoreButton.classList.add('disabled');
$loadMoreButton.innerText = VISIT_COUNT_LOAD_MORE_LOADING;
load(nextLoadingTimeFrame, nextLoadingPage);
});
const loadTimeFrame = (timeFrame: TimeFrame) => {
$results.innerHTML = '';
$status.innerText = VISIT_COUNT_LOADING;
$loadMoreContainer.classList.add('display-none');
nextLoadingTimeFrame = timeFrame;
nextLoadingPage = 2;
load(timeFrame, 1);
};
const ltfButtons: Array<HTMLDivElement> = [];
/** Load time frame button */
const createLtfButton = (text: string, timeFrame: TimeFrame) => {
const $button = h('div.rich', {
onclick: () => {
for (const $ltfButton of ltfButtons) {
$ltfButton.classList.toggle('selected', $ltfButton === $button);
}
loadTimeFrame(timeFrame);
},
}, text) as HTMLDivElement;
if (timeFrame === 'ALL') {
$button.classList.add('selected');
}
ltfButtons.push($button);
return $button;
};
block.element.appendChild(h('.button-container', timeFrames.map(timeFrame => createLtfButton(
getTimeFrameText(timeFrame),
timeFrame,
)))),
block.element.appendChild($status);
block.element.appendChild($results);
block.element.appendChild($loadMoreContainer);
block.element.appendChild(h('div.page-switcher', [
h('a', {
href: window.location.pathname,
onclick: (event: MouseEvent) => {
event.preventDefault();
enterMenuMode();
},
}, GO_TO_MENU),
]));
loadTimeFrame('ALL');
return true;
},
};
|
kink/kat
|
src/web/pages/visitCount.ts
|
TypeScript
|
unknown
| 7,316 |
import { h } from '../hs';
import { Page } from '../control/pageControl';
import { registerWithResultPopup, tokenItem } from '../control/userControl';
import { Modal, showGenericError, showGenericLoading } from '../control/modalControl';
import { backendUrl } from '../control/backendControl';
import { formatRelativePath } from '../util/formatRelativePath';
import { lastElement } from '../util/array';
import { relativePathLookUpMap } from '../data/data';
import { padName } from '../util/padName';
import { StringPersistentItem } from '../control/persistentItem';
/**
* Convert a string to 32 bit hash
* https://stackoverflow.com/a/47593316
*/
function xmur3(strSeed: string) {
let h = 1779033703 ^ strSeed.length;
for (let i = 0; i < strSeed.length; i++) {
h = Math.imul(h ^ strSeed.charCodeAt(i), 3432918353),
h = h << 13 | h >>> 19;
}
return () => {
h = Math.imul(h ^ h >>> 16, 2246822507);
h = Math.imul(h ^ h >>> 13, 3266489909);
return (h ^= h >>> 16) >>> 0;
};
}
/**
* Create a seeded random number generator using the four passed in 32 bit
* number as seeds.
* https://stackoverflow.com/a/47593316
*
* @param a seed
* @param b seed
* @param c seed
* @param d seed
* @returns seeded random number generator
*/
function sfc32(a: number, b: number, c: number, d: number) {
return () => {
a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0;
let t = (a + b) | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = (c << 21 | c >>> 11);
d = d + 1 | 0;
t = t + d | 0;
c = c + t | 0;
return (t >>> 0) / 4294967296;
};
}
interface CandidateChapter {
voteId: number;
relativePath: string;
overrideTitle?: string;
}
const candidates: Array<CandidateChapter> = [
{ voteId: 0, relativePath: '特别篇-公主殿下.html' },
{ voteId: 1, relativePath: '新能源.html' },
{ voteId: 2, relativePath: '长期贞操带实验第七次定期报告/第一幕.html', overrideTitle: '长期贞操带实验第七次定期报告' },
{ voteId: 3, relativePath: 'SBC-基金会档案/次元阴蒂环.html' },
{ voteId: 4, relativePath: 'SBC-基金会档案/淫纹打印机.html' },
{ voteId: 5, relativePath: 'SBC-基金会档案/173-号拘束衣.html' },
{ voteId: 6, relativePath: '长期贞操带实验定期报告(番外).html' },
{ voteId: 7, relativePath: '疼痛实验记录/第一次调研报告.html', overrideTitle: '疼痛实验记录' },
{ voteId: 8, relativePath: '新能源:美妙的旅程.html' },
{ voteId: 9, relativePath: '城岭樱的游街仪式.html' },
{ voteId: 10, relativePath: '好朋友,不吵架.html' },
{ voteId: 11, relativePath: '梦野与千夏.html' },
{ voteId: 12, relativePath: '道具集/mWatch.html' },
{ voteId: 13, relativePath: '道具集/强制灌食器.html' },
{ voteId: 14, relativePath: '道具集/拟真穿戴式猫耳猫尾.html' },
{ voteId: 15, relativePath: '道具集/充电宝少女捕获器.html' },
{ voteId: 16, relativePath: '道具集/现代女仆管理系统.html' },
{ voteId: 17, relativePath: '道具集/可穿戴装置-γ-型介绍.html' },
{ voteId: 18, relativePath: '道具集/载人风筝.html' },
{ voteId: 19, relativePath: '道具集/强奸体验机.html' },
{ voteId: 20, relativePath: '道具集/未知录像文件.html' },
{ voteId: 21, relativePath: '道具集/智子.html' },
{ voteId: 22, relativePath: '道具集/强制高潮快感枪.html' },
{ voteId: 23, relativePath: '道具集/森宇奶茶杯.html' },
{ voteId: 24, relativePath: '道具集/拟真穿戴式猫耳猫尾-2.html' },
{ voteId: 25, relativePath: '道具集/可穿戴科技的其他版本-·-Flexible-(Episode-1).html' },
{ voteId: 26, relativePath: '道具集/家庭用多功能放置架套装.html' },
{ voteId: 27, relativePath: '道具集/使人快乐的-PS4.html' },
{ voteId: 28, relativePath: '道具集/家庭-SM-套件.html' },
{ voteId: 29, relativePath: '道具集/舔脚授权协议-0.0.html' },
{ voteId: 30, relativePath: '日常就是要惊险刺激——且淫乱.html'},
{ voteId: 31, relativePath: '所以说,甜蜜的反杀也是日常的一部分.html' },
];
export function isCandidate(relativePath: string) {
return candidates.some(candidate => candidate.relativePath === relativePath);
}
let hasRandomized = false;
const seedItem = new StringPersistentItem('wtcupRandomSeed');
function ensureCandidatesAreRandomized() {
if (hasRandomized) {
return;
}
hasRandomized = true;
// 原来打算用 token 当种子来决定随机顺序的,然后突然意识到这个 hash 和随机算法
// 估计并不密码学安全。有一定可能性可以通过投票顺序倒推出来 token... 即使
// 只用 token 的一部分也不行,因为早期的 token 是 hex,所以强度本身并不是非常
// 高。如果能倒推出一部分就会显著降低安全度,所以现在干脆直接随机生成一个值当
// 种子好了。当然这样的缺陷是不同设备同一个账号显示顺序会不一样,不过这个问题
// 应该不大。
// 另外,不使用用户名作为种子的原因是,其实现在不确定 initialization 是否完
// 成,所以如果要用用户名这里还要等一个 initialization,特别麻烦。
// 不使用 SHA256 的原因也是嫌麻烦。
// const token = tokenItem.getValue()!;
// const seedFn = xmur3(token.substr(8));
if (!seedItem.exists()) {
const seed = String(Math.random());
seedItem.setValue(seed);
}
const seedFn = xmur3(seedItem.getValue()!);
const rng = sfc32(seedFn(), seedFn(), seedFn(), seedFn());
candidates.sort(() => rng() - 0.5);
}
let hasStarted = false;
const voteStatus: Array<number> = new Array(candidates.length).fill(0);
export const wtcupVote: Page = {
name: 'wtcup-vote',
handler: content => {
const startVote = () => {
if (!tokenItem.exists()) {
const $nameInput = h('input');
const $emailInput = h('input');
const registerModal = new Modal(h('div', [
h('h1', '请填写投票人信息'),
h('p', '您的昵称或邮箱不会伴随投票结果公开。'),
h('.input-group', [
h('span', '昵称(必填):'),
$nameInput,
]),
h('.input-group', [
h('span', '邮箱(可选):'),
$emailInput,
]),
h('.button-container', [
h('div', {
onclick: () => {
const loadingModal = showGenericLoading();
registerWithResultPopup(
$nameInput.value,
$emailInput.value === '' ? null : $emailInput.value
).then(success => {
if (success) {
registerModal.close();
initializeVotingBlocks();
}
}).finally(() => loadingModal.close());
}
}, '确认'),
h('div', {
onclick: () => registerModal.close(),
}, '取消'),
]),
]));
registerModal.open();
} else {
const loadingModal = showGenericLoading('正在加载投票记录...');
fetch(`${backendUrl}/event/getWtcupVotes`, {
cache: 'no-cache',
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({ token: tokenItem.getValue()! }),
}).then(response => response.json()).then((votes: Array<{
chapter_vote_id: number,
rating: number,
}>) => {
for (const vote of votes) {
voteStatus[vote.chapter_vote_id] = vote.rating;
}
initializeVotingBlocks();
}, showGenericError).finally(() => loadingModal.close());
}
};
const $welcomeBlock = h('div', [
h('h1', '《可穿戴科技》第一届西塔杯评选投票'),
h('p', [
'欢迎参与《可穿戴科技》',
h('a.regular', {
href: '#META/第一届西塔杯评选.html',
}, '第一届西塔杯'),
'评选投票。您的投票将直接决定西塔杯的评选结果。'
]),
h('p', '请点击下方按钮开始投票。'),
h('.button-container', [
h('div', {
onclick: startVote,
}, '开始投票'),
]),
]);
const welcomeBlock = content.addBlock({
initElement: $welcomeBlock,
});
if (hasStarted) {
initializeVotingBlocks();
}
function initializeVotingBlocks() {
hasStarted = true;
ensureCandidatesAreRandomized();
welcomeBlock.directRemove();
content.addBlock({
initElement: h('div', [
h('h1', '投票方式'),
h('p', '请点击星星对以下作品评分。所有作品默认处于“未评分”状态。处于“未评分”状态的评分项将不用作计算作品分数。点击星星左侧的“×”可将作品评分重置为“未评分”状态。'),
h('p', '作品将以随机顺序出现。'),
h('p', '您的投票会被实时保存。您可以随时回到这里修改所做出的评分。')
]),
});
for (const candidate of candidates) {
const formattedRelativePath = formatRelativePath(candidate.relativePath);
const title = candidate.overrideTitle ?? lastElement(formattedRelativePath.split(' > '));
const $clear = h('.choice.clear', 'clear');
const stars: Array<HTMLDivElement> = [];
let hovering = -1;
const updateDisplay = () => {
const rating = voteStatus[candidate.voteId];
$clear.classList.toggle('dimmed', rating === 0);
stars.forEach(($star, index) => {
if (rating === 0) {
if (hovering !== -1) {
$star.classList.toggle('dimmed', false);
$star.classList.toggle('less-dimmed', true);
} else {
$star.classList.toggle('dimmed', true);
$star.classList.toggle('less-dimmed', false);
}
} else {
$star.classList.toggle('dimmed', false);
$star.classList.toggle('less-dimmed', false);
}
$star.innerText = (index <= (hovering !== -1 ? hovering : (rating - 1))) ? 'star' : 'star_border';
});
};
let lastConfirmed = voteStatus[candidate.voteId];
let isSending = false;
let waitingToSend = -1;
const fetchSendVote = (rating: number) => {
isSending = true;
fetch(`${backendUrl}/event/voteWtcup`, {
cache: 'no-cache',
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
token: tokenItem.getValue()!,
chapter_vote_id: candidate.voteId,
rating,
}),
}).then(response => response.json()).then(() => {
isSending = false;
lastConfirmed = rating;
if (waitingToSend !== -1) {
fetchSendVote(waitingToSend);
waitingToSend = -1;
}
}, () => {
isSending = false;
showGenericError(padName(title) + '的评分提交失败,请重试。');
voteStatus[candidate.voteId] = lastConfirmed; // Revert
updateDisplay();
waitingToSend = -1;
});
};
const castVote = (rating: number) => {
if (isSending) {
waitingToSend = rating;
}
voteStatus[candidate.voteId] = rating;
updateDisplay();
fetchSendVote(rating);
};
for (let i = 0; i < 5; i++) {
let touchStart = 0;
const onClick = () => {
if (voteStatus[candidate.voteId] === i + 1) {
castVote(0);
} else {
castVote(i + 1);
}
};
stars.push(h('.choice.star', {
onmouseenter: () => {
hovering = i;
updateDisplay();
},
onmouseleave: () => {
hovering = -1;
updateDisplay();
},
ontouchstart: () => {
touchStart = Date.now();
},
ontouchend: (event: TouchEvent) => {
if (event.cancelable) {
event.preventDefault();
}
if (Date.now() - touchStart > 200) {
return;
}
onClick();
},
onclick: onClick,
}));
}
$clear.addEventListener('click', () => castVote(0));
updateDisplay();
content.addBlock({
initElement: h('.wtcup-vote', [
h('h2', title),
h('p', relativePathLookUpMap.get(candidate.relativePath)!.chapter.authors
.map(authorRole => authorRole.role + ':' + authorRole.name).join(',')),
h('p', '请选择评分:'),
h('.stars-container', [
$clear,
...stars,
]),
h('p', [
'文章链接:',
h('a.regular', {
href: `#${candidate.relativePath}`,
}, formattedRelativePath),
]),
]) as HTMLDivElement,
});
}
content.addBlock({
initElement: h('div', [
h('h1', '投票完成!'),
h('p', '以上就是所有参与评选的作品。感谢参与《可穿戴科技》第一届西塔杯评选投票,您的评分都已自动保存并上传至服务器。评选结果将在投票结束(北京时间 2020 年 12 月 31 日 23 时)后尽快发布。在投票结束前,您可以随时回到这里修改所做出的评分。'),
]),
});
}
return true;
},
};
|
kink/kat
|
src/web/pages/wtcupVote.ts
|
TypeScript
|
unknown
| 13,954 |
import { DebugLogger } from '../DebugLogger';
import { h } from '../hs';
export function id<T extends HTMLElement = HTMLDivElement>(id: string) {
return document.getElementById(id) as T;
}
export function getTextNodes(parent: HTMLElement, initArray?: Array<Text>) {
const textNodes: Array<Text> = initArray || [];
let pointer: Node | null = parent.firstChild;
while (pointer !== null) {
if (pointer instanceof HTMLElement) {
getTextNodes(pointer, textNodes);
}
if (pointer instanceof Text) {
textNodes.push(pointer);
}
pointer = pointer.nextSibling;
}
return textNodes;
}
const selectNodeDebugLogger = new DebugLogger('Select Node');
export function selectNode(node: Node) {
try {
const selection = window.getSelection()!;
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
} catch (error) {
selectNodeDebugLogger.log('Failed to select node: ', node, '; Error: ', error);
}
}
export function isAnyParent(
$element: HTMLElement | null,
predicate: (node: HTMLElement) => boolean,
) {
while ($element !== null) {
if (predicate($element)) {
return true;
}
$element = $element.parentElement;
}
return false;
}
export function insertAfter(
$newElement: HTMLElement,
$referencingElement: HTMLElement,
) {
$referencingElement.parentElement!.insertBefore(
$newElement,
$referencingElement.nextSibling,
);
}
export function insertAfterH1(
$newElement: HTMLElement,
$parent: HTMLElement,
) {
const $first = $parent.firstChild;
if (
$first !== null &&
$first instanceof HTMLHeadingElement &&
$first.tagName.toLowerCase() === 'h1'
) {
insertAfter($newElement, $first);
} else {
$parent.prepend($newElement);
}
}
export function externalLink(text: string, href: string) {
return h('a.regular', {
target: '_blank',
href,
rel: 'noopener noreferrer',
}, text);
}
export function linkButton(text: string, callback: () => void) {
return h('a.regular', {
href: '#',
onclick: ((event: any) => {
event.preventDefault();
callback();
}),
}, text);
}
export function forceReflow($element: HTMLElement) {
// tslint:disable-next-line:no-unused-expression
$element.offsetHeight;
}
export function autoExpandTextArea($textarea: HTMLTextAreaElement, minHeightPx: number = 120) {
function update() {
$textarea.style.height = `1px`;
$textarea.style.height = `${Math.max(minHeightPx, $textarea.scrollHeight)}px`;
}
$textarea.addEventListener('input', update, false);
setTimeout(update, 1);
return update;
}
|
kink/kat
|
src/web/util/DOM.ts
|
TypeScript
|
unknown
| 2,677 |
export function lastElement<T>(array: Array<T>): T {
return array[array.length - 1];
}
export function range(fromInclusive: number, toExclusive: number, step: number = 1) {
const result: Array<number> = [];
for (let i = fromInclusive; i < toExclusive; i += step) {
result.push(i);
}
return result;
}
export function produce<T>(count: number, producer: () => T) {
const result: Array<T> = [];
for (let i = 0; i < count; i++) {
result.push(producer());
}
return result;
}
|
kink/kat
|
src/web/util/array.ts
|
TypeScript
|
unknown
| 498 |
export function commaNumber(num: number) {
const segments: Array<string> = [];
while (num >= 1000) {
segments.push(String(num % 1000).padStart(3, '0'));
num = Math.floor(num / 1000);
}
segments.push(String(num));
segments.reverse();
return segments.join(',');
}
|
kink/kat
|
src/web/util/commaNumber.ts
|
TypeScript
|
unknown
| 282 |
export function formatRelativePath(relativePath: string) {
if (relativePath.endsWith('.html')) {
relativePath = relativePath.substr(0, relativePath.length - '.html'.length);
}
relativePath = relativePath.replace(/\//g, ' > ');
relativePath = relativePath.replace(/-/g, ' ');
return relativePath;
}
|
kink/kat
|
src/web/util/formatRelativePath.ts
|
TypeScript
|
unknown
| 313 |
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const MONTH = 365 / 12 * DAY; // Doesn't matter
const YEAR = 365 * DAY;
const MAX_RELATIVE_TIME = 7 * DAY;
export function formatTimeRelative(time: Date) {
const relativeTime = Date.now() - time.getTime();
if (relativeTime > MAX_RELATIVE_TIME) {
return `${time.getFullYear()}/${time.getMonth() + 1}/${time.getDate()}`;
}
if (relativeTime > DAY) {
return `${Math.floor(relativeTime / DAY)} 天前`;
}
if (relativeTime > HOUR) {
return `${Math.floor(relativeTime / HOUR)} 小时前`;
}
if (relativeTime > MINUTE) {
return `${Math.floor(relativeTime / MINUTE)} 分钟前`;
}
return `${Math.floor(relativeTime / SECOND)} 秒前`;
}
export function formatTimeRelativeLong(time: Date) {
const relativeTime = Date.now() - time.getTime();
if (relativeTime <= MAX_RELATIVE_TIME) {
return formatTimeRelative(time);
}
if (relativeTime > YEAR) {
return `${Math.floor(relativeTime / YEAR)} 年前`;
}
if (relativeTime > MONTH) {
return `${Math.floor(relativeTime / MONTH)} 个月前`;
}
return `${Math.floor(relativeTime / DAY)} 天前`;
}
export function formatDurationCoarse(milliseconds: number) {
if (milliseconds > 10 * DAY) {
return ` ${Math.floor(milliseconds / DAY)} 天`;
} else if (milliseconds > HOUR) {
const day = Math.floor(milliseconds / DAY);
const hour = Math.floor((milliseconds % DAY) / HOUR);
if (hour === 0) {
return ` ${day} 天`;
} else {
return ` ${day} 天 ${hour} 小时`;
}
} else {
return '不到一小时';
}
}
export function formatTimeSimple(time: Date) {
return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()} ` +
`${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}`;
}
|
kink/kat
|
src/web/util/formatTime.ts
|
TypeScript
|
unknown
| 1,836 |
import { DebugLogger } from '../DebugLogger';
import { matchAll } from './matchAll';
const debugLogger = new DebugLogger('Load Google Fonts');
const parseRegex = /@font-face {[^}]*?font-family:\s*['"]?([^;'"]+?)['"]?;[^}]*?font-style:\s*([^;]+);[^}]*?font-weight:\s*([^;]+);[^}]*?src:\s*([^;]+);[^}]*?(?:unicode-range:\s*([^;]+))?;/g;
export async function loadGoogleFonts(fontName: string) {
const cssLink = `https://fonts.googleapis.com/css2?family=${fontName.replace(/ /g, '+')}`;
debugLogger.log(`Loading font: "${fontName}" from "${cssLink}".`);
const response = await fetch(cssLink);
const text = await response.text();
const matches = matchAll(text, parseRegex);
return Promise.all(matches.map(match => new FontFace(match[1], match[4], {
style: match[2],
weight: match[3],
unicodeRange: match[5],
}).load()))
.then(fontFaces => fontFaces.map(fontFace => (document.fonts as any).add(fontFace)))
.then(() => fontName);
}
|
kink/kat
|
src/web/util/loadGooleFonts.ts
|
TypeScript
|
unknown
| 961 |
export function matchAll(str: string, regex: RegExp): Array<RegExpExecArray> {
if (regex.global !== true) {
throw new Error('Global flag is required.');
}
const results = [];
let array;
while ((array = regex.exec(str)) !== null) {
results.push(array);
}
return results;
}
|
kink/kat
|
src/web/util/matchAll.ts
|
TypeScript
|
unknown
| 294 |
export function randomInt(minInclusive: number, maxExclusive: number) {
return Math.floor(Math.random() * (maxExclusive - minInclusive)) + minInclusive;
}
export function randomNumber(minInclusive: number, maxExclusive: number) {
return Math.random() * (maxExclusive - minInclusive) + minInclusive;
}
|
kink/kat
|
src/web/util/math.ts
|
TypeScript
|
unknown
| 306 |
const cjkBeginRegex = /^(?:[\u4E00-\u9FCC\u3400-\u4DB5\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d])/;
const cjkEndRegex = /(?:[\u4E00-\u9FCC\u3400-\u4DB5\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d])$/;
export function padName(name: string) {
if (!cjkBeginRegex.test(name)) {
name = ' ' + name;
}
if (!cjkEndRegex.test(name)) {
name = name + ' ';
}
return name;
}
|
kink/kat
|
src/web/util/padName.ts
|
TypeScript
|
unknown
| 738 |
/**
* Input: ['a/b', '..', 'c/../e', 'f']
* Output: 'a/e/f'
*/
export function resolvePath(...paths: Array<string>) {
const pathStack: Array<string> = [];
for (const path of paths) {
const segments = path.split('/');
for (const segment of segments) {
switch (segment) {
case '':
case '.':
return null;
case '..':
if (pathStack.length === 0) {
return null;
} else {
pathStack.pop();
}
break;
default:
pathStack.push(segment);
}
}
}
return pathStack.join('/');
}
|
kink/kat
|
src/web/util/resolvePath.ts
|
TypeScript
|
unknown
| 612 |
export function shortNumber(input: number, digits: number = 1) {
if (input < 1_000) {
return String(input);
}
if (input < 1_000_000) {
return (input / 1000).toFixed(digits) + 'k';
}
return (input / 1_000_000).toFixed(digits) + 'M';
}
|
kink/kat
|
src/web/util/shortNumber.ts
|
TypeScript
|
unknown
| 252 |
/**
* Input: 'asdasd.html', '.html'
* Output: 'asdasd'
*
* Input: 'asdasd', '.html'
* Output: 'asdasd'
*/
export function removePotentialSuffix(input: string, potentialSuffix: string) {
return input.endsWith(potentialSuffix)
? input.substr(0, input.length - potentialSuffix.length)
: input;
}
|
kink/kat
|
src/web/util/string.ts
|
TypeScript
|
unknown
| 309 |
// https://stackoverflow.com/a/7616484
export function stringHash(str: string) {
let hash = 0;
if (str.length === 0) {
return hash;
}
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return hash;
}
|
kink/kat
|
src/web/util/stringHash.ts
|
TypeScript
|
unknown
| 275 |
import { $e } from '../$e';
import { tagCountMap } from '../data/data';
export function tagSpan(tag: string, active: boolean) {
const count = tagCountMap.get(tag) ?? 0;
return (
<div className={ 'tag-div' + (active ? ' active' : '') }>
<span
className={ 'tag' + ((count === 0) ? ' empty' : '') }
>
<span className={ 'text' + (tag.endsWith(')') ? ' parentheses-ending' : '') }>{ tag }</span>
<span className='count'>{ count }</span>
</span>
</div>
);
}
|
kink/kat
|
src/web/util/tag.tsx
|
TypeScript
|
unknown
| 510 |
export function smartThrottle(fn: () => void, timeMs: number) {
let timerRunning = false;
let scheduled = false;
return () => {
if (!timerRunning) {
fn();
const timedOut = () => {
if (scheduled) {
fn();
scheduled = false;
setTimeout(timedOut, timeMs);
} else {
timerRunning = false;
}
};
timerRunning = true;
setTimeout(timedOut, timeMs);
} else {
scheduled = true;
}
};
}
|
kink/kat
|
src/web/util/throttle.ts
|
TypeScript
|
unknown
| 493 |
/**
* Completely replaces the pre-existing arguments.
*/
export function resetUrlArgumentsTo(args: Map<string, string>) {
window.history.replaceState(
null,
document.title,
window.location.origin + '/' + window.location.hash.split('~')[0]
+ ((args.size === 0)
? ''
: ('~' + Array.from(args).map(([key, value]) => (value === '') ? key : `${key}=${value}`))),
);
}
|
kink/kat
|
src/web/util/urlArguments.ts
|
TypeScript
|
unknown
| 403 |
export class ChainedCanvas {
public readonly canvas: HTMLCanvasElement;
public readonly ctx: CanvasRenderingContext2D;
private promise: Promise<any> = Promise.resolve();
public constructor(width: number, height: number) {
this.canvas = document.createElement('canvas');
this.canvas.width = width;
this.canvas.height = height;
this.ctx = this.canvas.getContext('2d')!;
}
public updatePromise(updater: () => Promise<any>) {
this.promise = this.promise.then(updater);
}
public onResolve(callback: () => void) {
this.promise.then(callback);
}
public getWidth() {
return this.canvas.width;
}
public getHeight() {
return this.canvas.height;
}
}
|
kink/kat
|
src/wtcd/ChainedCanvas.ts
|
TypeScript
|
unknown
| 697 |
/**
* Implement methods to provide additional feature support.
*/
export class FeatureProvider {
/**
* When using the canvas functionality of WTCD, user may choose to put an
* external image to the canvas. Whenever that happens, this method is called.
*/
loadImage(path: string): Promise<CanvasImageSource> {
return Promise.reject('Loading images is not allowed.');
}
/**
* When using the canvas functionality of WTCD, user may choose to use a
* custom font in the canvas. Whenever that happens, this method is called.
*
* Please make sure the font is loaded in DOM via document.fonts#add
*
* Returns the name of the font
*/
loadFont(identifier: string): Promise<string> {
return Promise.reject('Loading fonts is not allowed.');
}
/**
* Draw loading screen on the provided canvas.
*/
drawLoadingCanvas($canvas: HTMLCanvasElement): void {
return undefined;
}
}
export const defaultFeatureProvider = new FeatureProvider();
|
kink/kat
|
src/wtcd/FeatureProvider.ts
|
TypeScript
|
unknown
| 990 |
import { ContentOutput, Interpreter } from './Interpreter';
import { Random } from './Random';
import { WTCDRoot } from './types';
import { FeatureProvider, defaultFeatureProvider } from './FeatureProvider';
/** Data persisted in the localStorage */
interface Data {
random: string;
decisions: Array<number>;
}
/**
* This is one of the possible implementations of a WTCD reader.
*
* In this implementation, all new content and buttons are appended to a single
* HTML element. The user is expected to continuously scroll down the page in
* order to read more, thus the name "flow reader".
*
* This reader implementation persists data via memorizing all users' decisions.
* When restoring a previous session, it replays all decisions.
*
* Since all decisions are recorded, this implementation allows the user to undo
* decisions, in which case, it resets the interpreter and replay all decisions
* until the decision that is being undone. This means, however, if the logic of
* WTCD section is extremely complicated and takes a long time to compute, it
* will potentially lag user's interface every time the user undoes a decision.
*/
export class FlowReader {
/** The interpreter */
private interpreter!: Interpreter;
/** The iterator of the interpreter */
private interpreterIterator!: Iterator<ContentOutput, ContentOutput, number>;
/** Key in local storage */
private storageKey: string;
/** Persisted data */
private data: Data;
/** Where to render the output */
private target!: HTMLElement;
/** Which decision the current buttons are for */
private currentDecisionIndex: number = 0;
/** Buttons for each group of output */
private buttons: Array<Array<HTMLDivElement>> = [];
/** Content output after each decision */
private contents: Array<HTMLElement> = [];
/**
* Verify and parse data stored in localStorage.
*/
private parseData(data: any): Data | null {
if (typeof data !== 'string') {
return null;
}
let obj: any;
try {
obj = JSON.parse(data);
} catch (error) {
return null;
}
if (typeof obj.random !== 'string') {
return null;
}
if (!Array.isArray(obj.decisions)) {
return null;
}
if (obj.decisions.some((decision: any) => typeof decision !== 'number')) {
return null;
}
return obj;
}
/** Fancy name for "save" */
private persist() {
window.localStorage.setItem(this.storageKey, JSON.stringify(this.data));
}
/**
* Calls this.interpreterIterator.next() and handles error.
*/
private next(decision?: number): IteratorResult<ContentOutput, ContentOutput> {
try {
return this.interpreterIterator.next(decision as any);
} catch (error) {
const $errorMessage = this.errorMessageCreator(error as Error);
this.target.appendChild($errorMessage);
this.contents.push($errorMessage);
return {
done: true,
value: {
choices: [],
content: [],
},
};
}
}
/** Restart the interpreter and reset the interpreterIterator */
public resetInterpreter() {
this.interpreter = new Interpreter(
this.wtcdRoot,
new Random(this.data.random),
this.featureProvider,
);
this.interpreterIterator = this.interpreter.start();
}
public constructor(
docIdentifier: string,
private wtcdRoot: WTCDRoot,
private errorMessageCreator: (error: Error) => HTMLElement,
private elementPreprocessor: ($element: HTMLElement) => void,
private featureProvider: FeatureProvider = defaultFeatureProvider,
) {
this.storageKey = `wtcd.fr.${docIdentifier}`;
this.data = this.parseData(window.localStorage.getItem(this.storageKey)) || {
random: String(Math.random()),
decisions: [],
};
this.resetInterpreter();
}
/**
* Make a decision at currentDecisionIndex and update buttons accordingly
*
* @param decision the index of choice to be made
* @param replay whether this is during a replay; If true, the decision will
* not be added to data.
*/
private decide(decision: number, replay: boolean = false) {
this.buttons[this.currentDecisionIndex].forEach(($button, choiceIndex) => {
if ($button.classList.contains('disabled')) {
return;
}
$button.classList.remove('candidate');
if (choiceIndex === decision) {
$button.classList.add('selected');
} else {
$button.classList.add('unselected');
}
});
if (!replay) {
this.data.decisions.push(decision);
}
// Advance current decision index
this.currentDecisionIndex++;
const yieldValue = this.next(decision);
this.handleOutput(yieldValue.value);
return yieldValue.done;
}
/**
* Undo a decision made previously; It also removes every decision after the
* specified decision.
*
* @param decisionIndex which decision to be undone
*/
private undecide(decisionIndex: number) {
this.resetInterpreter();
// Clear those no longer needed content
this.data.decisions.splice(decisionIndex);
this.buttons.splice(decisionIndex + 1);
this.contents.splice(decisionIndex + 1)
.forEach($deletedContent => $deletedContent.remove());
// Replay
this.next();
for (const decision of this.data.decisions) {
this.next(decision);
}
// Update current decision's buttons so they become available to click
// again.
this.buttons[decisionIndex].forEach($button => {
if (!$button.classList.contains('disabled')) {
$button.classList.remove('selected', 'unselected');
$button.classList.add('candidate');
}
});
this.currentDecisionIndex = decisionIndex;
}
/**
* Handle an instance of output from the interpreter. This will add the
* content output and buttons to target.
*
* @param output the content output to be added
*/
private handleOutput(output: ContentOutput) {
// Create a container for all elements involved so deletion will be easier.
const $container = document.createElement('div');
$container.classList.add('wtcd-group-container');
output.content.forEach($element => $container.appendChild($element));
this.interpreter.getPinned().forEach($element =>
$container.appendChild($element),
);
const decisionIndex = this.currentDecisionIndex;
this.buttons.push(output.choices.map((choice, choiceIndex) => {
const $button = document.createElement('div');
$button.classList.add('wtcd-button');
$button.innerText = choice.content;
if (choice.disabled) {
$button.classList.add('disabled');
} else {
$button.classList.add('candidate');
$button.addEventListener('click', () => {
if (this.data.decisions[decisionIndex] === choiceIndex) {
this.undecide(decisionIndex);
this.persist();
} else if (this.currentDecisionIndex === decisionIndex) {
this.decide(choiceIndex);
this.persist();
}
});
}
$container.appendChild($button);
return $button;
}));
this.contents.push($container);
this.target.appendChild($container);
this.elementPreprocessor($container);
}
private started: boolean = false;
public renderTo($target: HTMLElement) {
if (this.started) {
throw new Error('Flow reader already started.');
}
this.started = true;
this.target = $target;
const init = this.next();
let done = init.done;
this.handleOutput(init.value);
for (const decision of this.data.decisions) {
if (done) {
return;
}
done = this.decide(decision, true);
}
}
}
|
kink/kat
|
src/wtcd/FlowReader.ts
|
TypeScript
|
unknown
| 7,715 |
import { ContentOutput, Interpreter } from './Interpreter';
import { Random } from './Random';
import { WTCDRoot } from './types';
import { FeatureProvider, defaultFeatureProvider } from './FeatureProvider';
interface GameData {
random: string;
decisions: Array<number>;
}
function isGameData(data: any): data is GameData {
if (typeof data !== 'object' || data === null) {
return false;
}
if (typeof data.random !== 'string') {
return false;
}
if (!Array.isArray(data.decisions)) {
return false;
}
if (data.decisions.some((decision: any) => typeof decision !== 'number')) {
return false;
}
return true;
}
interface SaveData extends GameData {
date: number;
desc: string;
}
function isSaveData(data: any): data is SaveData {
if (!isGameData(data)) {
return false;
}
if (typeof (data as any).date !== 'number') {
return false;
}
if (typeof (data as any).desc !== 'string') {
return false;
}
return true;
}
interface Data {
saves: Array<SaveData | null>;
current: GameData;
}
function isData(data: any): data is Data {
if (typeof data !== 'object' || data === null) {
return false;
}
if (!isGameData(data.current)) {
return false;
}
if (!Array.isArray(data.saves)) {
return false;
}
if (!data.saves.every((save: any) => save === null || isSaveData(save))) {
return false;
}
return true;
}
/**
* This is one of the possible implementations of a WTCD reader.
*
* This is a reader specialized for games. This reader only display one section
* at a time. This reader also does not allow undo.
*
* However, this reader does support save/load. It persists data via memorizing
* all decisions too.
*/
export class GameReader {
private storageKey: string;
private data: Data;
/** The interpreter */
private interpreter!: Interpreter;
/** The iterator of the interpreter */
private interpreterIterator!: Iterator<ContentOutput, ContentOutput, number>;
public constructor(
docIdentifier: string,
private wtcdRoot: WTCDRoot,
private onOutput: (content: HTMLDivElement) => void,
private onError: (error: Error) => void,
private featureProvider: FeatureProvider = defaultFeatureProvider,
) {
this.storageKey = `wtcd.gr.${docIdentifier}`;
this.data = this.parseData(
window.localStorage.getItem(this.storageKey),
) || {
saves: [null, null, null],
current: {
random: String(Math.random()),
decisions: [],
},
};
}
private parseData(data: any): Data | null {
if (typeof data !== 'string') {
return null;
}
let obj: any;
try {
obj = JSON.parse(data);
} catch (error) {
return null;
}
if (!isData(obj)) {
return null;
}
return obj;
}
private persist() {
window.localStorage.setItem(this.storageKey, JSON.stringify(this. data));
}
public getSaves() {
return this.data.saves.map(save => save === null
? null
: {
desc: save.desc,
date: new Date(save.date),
},
);
}
public reset(reseed: boolean) {
this.data.current.decisions = [];
if (reseed) {
this.data.current.random = String(Math.random());
}
this.restoreGameState();
this.persist();
}
public save(saveIndex: number) {
const save = this.data.saves[saveIndex];
if (save === undefined) {
throw new Error(`Illegal save index: ${saveIndex}`);
}
this.data.saves[saveIndex] = {
date: Date.now(),
desc: this.interpreter.getStateDesc() || '',
random: this.data.current.random,
decisions: this.data.current.decisions.slice(),
};
if (this.data.saves[this.data.saves.length - 1] !== null) {
this.data.saves.push(null);
}
this.persist();
}
public load(saveIndex: number) {
const save = this.data.saves[saveIndex];
if (save === undefined || save === null) {
throw new Error(`Illegal save index: ${saveIndex}.`);
}
this.data.current.random = save.random;
this.data.current.decisions = save.decisions.slice();
this.restoreGameState();
this.persist();
}
/** Calls this.interpreterIterator.next() and handles error. */
private next(
decision?: number,
): IteratorResult<ContentOutput, ContentOutput> {
try {
return this.interpreterIterator.next(decision as any);
} catch (error) {
this.onError(error as Error);
return {
done: true,
value: {
choices: [],
content: [],
},
};
}
}
private restoreGameState() {
this.interpreter = new Interpreter(
this.wtcdRoot,
new Random(this.data.current.random),
this.featureProvider,
);
this.interpreterIterator = this.interpreter.start();
let lastOutput = this.next();
this.data.current.decisions.forEach(decision =>
lastOutput = this.next(decision),
);
this.handleOutput(lastOutput.value);
}
private handleOutput(output: ContentOutput) {
const $output = document.createElement('div');
output.content.forEach($element => $output.appendChild($element));
this.interpreter.getPinned()
.forEach($element => $output.appendChild($element));
const decisionIndex = this.data.current.decisions.length;
const buttons = output.choices.map((choice, choiceIndex) => {
const $button = document.createElement('div');
$button.classList.add('wtcd-button');
$button.innerText = choice.content;
if (choice.disabled) {
$button.classList.add('disabled');
} else {
$button.classList.add('candidate');
$button.addEventListener('click', () => {
if (decisionIndex !== this.data.current.decisions.length) {
return;
}
this.data.current.decisions.push(choiceIndex);
buttons.forEach($eachButton => {
if ($eachButton === $button) {
$eachButton.classList.add('selected');
} else {
$eachButton.classList.add('unselected');
}
});
this.handleOutput(this.next(choiceIndex).value);
this.persist();
});
}
$output.appendChild($button);
return $button;
});
this.onOutput($output);
}
private started = false;
public start() {
if (this.started) {
throw new Error('Game reader already started.');
}
this.started = true;
this.restoreGameState();
}
}
|
kink/kat
|
src/wtcd/GameReader.ts
|
TypeScript
|
unknown
| 6,461 |
import { getMaybePooled } from './constantsPool';
import { FunctionInvocationError, invokeFunctionRaw } from './invokeFunction';
import { binaryOperators, unaryOperators } from './operators';
import { Random } from './Random';
import { stdFunctions } from './std';
import {
BlockExpression,
ChoiceExpression,
ConditionalExpression,
DeclarationStatement,
Expression,
FunctionExpression,
IfExpression,
ListExpression,
NativeFunction,
OptionalLocationInfo,
RegisterName,
Section,
SelectionAction,
Statement,
SwitchExpression,
VariableType,
WhileExpression,
WTCDRoot,
} from './types';
import { arrayEquals, flat } from './utils';
import { WTCDError } from './WTCDError';
import { FeatureProvider } from './FeatureProvider';
import { ChainedCanvas } from './ChainedCanvas';
// Dispatching code for the runtime of WTCD
interface SingleChoice {
content: string;
disabled: boolean;
}
export interface ContentOutput {
readonly content: Array<HTMLElement>;
readonly choices: Array<SingleChoice>;
}
export type NumberValueRaw = number;
export interface NumberValue {
readonly type: 'number';
readonly value: NumberValueRaw;
}
export type BooleanValueRaw = boolean;
export interface BooleanValue {
readonly type: 'boolean';
readonly value: BooleanValueRaw;
}
export type StringValueRaw = string;
export interface StringValue {
readonly type: 'string';
readonly value: StringValueRaw;
}
export type NullValueRaw = null;
export interface NullValue {
readonly type: 'null';
readonly value: NullValueRaw;
}
export type ListValueRaw = ReadonlyArray<RuntimeValue>;
export interface ListValue {
readonly type: 'list';
readonly value: ListValueRaw;
}
export type ActionValueRaw = {
readonly action: 'goto';
readonly target: Array<string>;
} | {
readonly action: 'exit';
} | {
readonly action: 'selection';
readonly choices: ReadonlyArray<ChoiceValue>;
} | {
readonly action: 'function';
readonly fn: FunctionValue;
readonly creator: ChoiceExpression;
};
export interface ActionValue {
readonly type: 'action';
readonly value: ActionValueRaw;
}
export interface ChoiceValueRaw {
readonly text: string;
readonly action: ActionValue | NullValue;
}
export interface ChoiceValue {
readonly type: 'choice';
readonly value: ChoiceValueRaw;
}
export type FunctionValueRaw = {
readonly fnType: 'wtcd',
readonly expr: FunctionExpression;
readonly captured: ReadonlyArray<{
readonly name: string,
readonly value: Variable,
}>;
} | {
readonly fnType: 'native',
readonly nativeFn: NativeFunction,
} | {
readonly fnType: 'partial';
readonly isLeft: boolean;
readonly applied: ReadonlyArray<RuntimeValue>;
readonly targetFn: FunctionValue,
};
export interface FunctionValue {
readonly type: 'function';
readonly value: FunctionValueRaw;
}
export type RuntimeValue
= NumberValue
| BooleanValue
| StringValue
| NullValue
| ActionValue
| ChoiceValue
| ListValue
| FunctionValue;
/**
* Represents all possible type names for runtime values.
*/
export type RuntimeValueType = RuntimeValue['type'];
/**
* Represents a variable. It stores its type information and its value.
*/
export interface Variable {
readonly types: null | Array<RuntimeValueType>;
value: RuntimeValue;
}
/**
* Extracts the unwrapped value type for a give runtime value type name
*
* For example, RuntimeValueRaw<"number"> = number
*/
export type RuntimeValueRaw<T extends RuntimeValueType> = Extract<
RuntimeValue,
{ type: T }
>['value'];
/**
* Determine whether two runtime values are equal. Uses deep value equality
* instead of reference equality.
*/
export function isEqual(v0: RuntimeValue, v1: RuntimeValue): boolean {
// TypeScript's generic currently does not support type narrowing.
// Until that is fixed, this function has to have so many any, unfortunately
if (v0.type !== v1.type) {
return false;
}
switch (v0.type) {
case 'null':
return true;
case 'number':
case 'boolean':
case 'string':
return v0.value === v1.value;
case 'action':
if (v0.value.action !== (v1 as any).value.action) {
return false;
}
switch (v0.value.action) {
case 'exit':
return true;
case 'goto':
return arrayEquals(v0.value.target, (v1 as any).value.target);
case 'selection':
return (v0.value.choices.length
=== (v1 as any).value.choices.length) &&
(v0.value.choices.every((choice, index) => isEqual(
choice,
(v1 as any).value.choices[index]),
));
}
throw new Error('Shouldn\'t fall through.');
case 'choice':
return (
(v0.value.text === (v1 as any).value.text) &&
(isEqual(v0.value.action, (v1 as any).value.action))
);
case 'function':
if (v0.value.fnType !== (v1 as FunctionValue).value.fnType) {
return false;
}
if (v0.value.fnType === 'native') {
return (v0.value.nativeFn === (v1 as any).value.nativeFn);
} else if (v0.value.fnType === 'wtcd') {
return (
// They refer to same expression
(v0.value.expr === (v1 as any).value.expr) &&
(v0.value.captured.every((v0Cap, index) => {
const v1Cap = (v1 as any).value.captured[index];
return (
(v0Cap.name === v1Cap.name) &&
// Reference equality to make sure they captured the same
// variable
(v0Cap.value === v1Cap.value)
);
}))
);
} else {
return (
(v0.value.isLeft === (v1 as any).value.isLeft) &&
(isEqual(v0.value.targetFn, (v1 as any).value.targetFn)) &&
(arrayEquals(v0.value.applied, (v1 as any).value.applied, isEqual))
);
}
case 'list':
return (
(v0.value.length === (v1 as ListValue).value.length) &&
(v0.value.every((element, index) => isEqual(
element,
(v1 as ListValue).value[index]),
))
);
}
}
/**
* An evaluator is responsible for evaluating an expression and return its value
*/
export type Evaluator = (expr: Expression) => RuntimeValue;
/**
* Type of a thrown bubble signal.
*/
export enum BubbleSignalType {
YIELD,
RETURN,
BREAK,
CONTINUE,
}
/**
* Bubble signal is used for traversing upward the call stack. It is implemented
* with JavaScript's Error. Such signal might be yield, return, break, or
* continue.
*/
export class BubbleSignal extends Error {
public constructor(
public readonly type: BubbleSignalType,
) {
super('Uncaught Bubble Signal.');
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Create a string describing a runtime value including its type and value.
*/
export function describe(rv: RuntimeValue): string {
switch (rv.type) {
case 'number':
case 'boolean':
return `${rv.type} (value = ${rv.value})`;
case 'string':
return `string (value = "${rv.value}")`;
case 'choice':
return `choice (action = ${describe(rv.value.action)}, label = ` +
`"${rv.value.text}")`;
case 'action':
switch (rv.value.action) {
case 'goto':
return `action (type = goto, target = ${rv.value.target})`;
case 'exit':
return `action (type = exit)`;
case 'selection':
return `action (type = selection, choices = [${rv.value.choices
.map(describe).join(', ')}])`;
}
case 'null':
return 'null';
case 'list':
return `list (elements = [${rv.value.map(describe).join(', ')}])`;
case 'function':
if (rv.value.fnType === 'native') {
return `function (native ${rv.value.nativeFn.name})`;
} else if (rv.value.fnType === 'wtcd') {
return `function (arguments = [${rv.value.expr.arguments
.map(arg => arg.name)
.join(', ')
}])`;
} else {
return `function (partial ${rv.value.isLeft ? 'left' : 'right'}, ` +
`applied = [${rv.value.applied.map(describe).join(', ')}], ` +
`targetFn = ${describe(rv.value.targetFn)})`;
}
}
}
/**
* Determine whether a given value is assignable to a given type declaration.
*
* @param type given value's type
* @param types type declaration that is to be compared to
* @returns whether a value with type type is assignable to a variable with type
* declaration types
*/
export function isTypeAssignableTo(
type: RuntimeValueType,
types: VariableType,
) {
return types === null || types.includes(type);
}
export function assignValueToVariable(
variable: Variable,
value: RuntimeValue,
location: OptionalLocationInfo, // For error message
variableName: string, // For error message
) {
if (!isTypeAssignableTo(value.type, variable.types)) {
throw WTCDError.atLocation(location, `Cannot assign value (` +
`${describe(value)}) to variable "${variableName}". "${variableName}" ` +
`can only store these types: ${(
variable.types as Array<RuntimeValueType>
).join(', ')}`);
}
variable.value = value;
}
class RuntimeScope {
private variables: Map<string, Variable> = new Map();
private registers: Map<string, RuntimeValue> | null = null;
/**
* Attempt to resolve the given variable name within this scope. If variable
* is not found, return null.
*
* @param variableName
* @returns
*/
public resolveVariableReference(variableName: string): Variable | null {
return this.variables.get(variableName) || null;
}
public addVariable(variableName: string, value: Variable) {
this.variables.set(variableName, value);
}
public addRegister(registerName: RegisterName) {
if (this.registers === null) {
this.registers = new Map();
}
this.registers.set(registerName, getMaybePooled('null', null));
}
/**
* If a register with given name exists on this scope, set the value of it and
* return true. Otherwise, return false.
*
* @param registerName name of register
* @param value value to set to
* @returns whether the requested register is found
*/
public setRegisterIfExist(registerName: RegisterName, value: RuntimeValue): boolean {
if (this.registers === null) {
return false;
}
if (!this.registers.has(registerName)) {
return false;
}
this.registers.set(registerName, value);
return true;
}
public getRegister(registerName: RegisterName): RuntimeValue | null {
return this.registers && this.registers.get(registerName) || null;
}
}
export class InvalidChoiceError extends Error {
public constructor(
public readonly choiceId: number,
) {
super(`Invalid choice ${choiceId}.`);
}
}
export interface InterpreterHandle {
evaluator(expr: Expression): RuntimeValue;
pushScope(): RuntimeScope;
popScope(): RuntimeScope | undefined;
resolveVariableReference(variableName: string): Variable;
getRandom(): Random;
pushContent($element: HTMLElement): void;
readonly timers: Map<string, number>;
setPinnedFunction(pinnedFunction: FunctionValue | null): void;
setStateDesc(stateDesc: string | null): void;
readonly featureProvider: FeatureProvider;
readonly canvases: Map<string, ChainedCanvas>;
}
export class Interpreter {
private timers: Map<string, number> = new Map();
private interpreterHandle: InterpreterHandle = {
evaluator: this.evaluator.bind(this),
pushScope: this.pushScope.bind(this),
popScope: this.popScope.bind(this),
resolveVariableReference: this.resolveVariableReference.bind(this),
getRandom: () => this.random,
pushContent: this.pushContent.bind(this),
timers: this.timers,
setPinnedFunction: this.setPinnedFunction.bind(this),
setStateDesc: this.setStateDesc.bind(this),
featureProvider: this.featureProvider,
canvases: new Map(),
};
private pinnedFunction: FunctionValue | null = null;
private pinned: Array<HTMLElement> = [];
private stateDesc: string | null = null;
private setPinnedFunction(pinnedFunction: FunctionValue | null) {
this.pinnedFunction = pinnedFunction;
}
private setStateDesc(stateDesc: string | null) {
this.stateDesc = stateDesc;
}
public constructor(
private wtcdRoot: WTCDRoot,
private random: Random,
private featureProvider: FeatureProvider
) {
this.sectionStack.push(this.wtcdRoot.sections[0]);
}
private scopes: Array<RuntimeScope> = [];
private sectionStack: Array<Section> = [];
private resolveVariableReference(variableName: string) {
for (let i = this.scopes.length - 1; i >= 0; i--) {
const variable = this.scopes[i].resolveVariableReference(variableName);
if (variable !== null) {
return variable;
}
}
throw WTCDError.atUnknown(`Cannot resolve variable reference ` +
`"${variableName}". This is most likely caused by WTCD compiler's ` +
`error or the compiled output ` +
`has been modified`);
}
/**
* Iterate through the scopes and set the first register with registerName to
* given value.
*
* @param registerName The name of register to look for
* @param value The value to set to
*/
private setRegister(registerName: RegisterName, value: RuntimeValue) {
for (let i = this.scopes.length - 1; i >= 0; i--) {
if (this.scopes[i].setRegisterIfExist(registerName, value)) {
return;
}
}
throw WTCDError.atUnknown(`Cannot resolve register reference "${registerName}". ` +
`This is mostly likely caused by WTCD compiler's error or the compiled output ` +
`has been modified`);
}
private getCurrentScope(): RuntimeScope {
return this.scopes[this.scopes.length - 1];
}
private pushScope() {
const scope = new RuntimeScope();
this.scopes.push(scope);
return scope;
}
private popScope() {
return this.scopes.pop();
}
private evaluateChoiceExpression(expr: ChoiceExpression): ChoiceValue {
const text = this.evaluator(expr.text);
if (text.type !== 'string') {
throw WTCDError.atLocation(expr, `First argument of choice is expected to be a string, ` +
`received: ${describe(text)}`);
}
let action = this.evaluator(expr.action);
if (action.type !== 'action' && action.type !== 'function' && action.type !== 'null') {
throw WTCDError.atLocation(expr, `Second argument of choice is expected to be an action, a function, ` +
`or null, received: ${describe(text)}`);
}
if (action.type === 'function') {
action = {
type: 'action',
value: {
action: 'function',
fn: action,
creator: expr,
},
};
}
return {
type: 'choice',
value: {
text: text.value,
action,
},
};
}
private evaluateConditionalExpression(expr: ConditionalExpression): RuntimeValue {
const condition = this.evaluator(expr.condition);
if (condition.type !== 'boolean') {
throw WTCDError.atLocation(expr, `First argument of a conditional expression is expected to ` +
`be a boolean, received: ${describe(condition)}`);
}
// Only evaluate the necessary branch
if (condition.value) {
return this.evaluator(expr.then);
} else {
return this.evaluator(expr.otherwise);
}
}
private executeDeclarationStatement(expr: DeclarationStatement) {
for (const singleDeclaration of expr.declarations) {
let value: RuntimeValue;
if (singleDeclaration.initialValue !== null) {
value = this.evaluator(singleDeclaration.initialValue);
} else {
if (singleDeclaration.variableType === null) {
value = getMaybePooled('null', null);
} else if (singleDeclaration.variableType.length === 1) {
switch (singleDeclaration.variableType[0]) {
case 'boolean':
value = getMaybePooled('boolean', false);
break;
case 'number':
value = getMaybePooled('number', 0);
break;
case 'string':
value = getMaybePooled('string', '');
break;
case 'list':
value = { type: 'list', value: [] };
break;
default:
throw WTCDError.atLocation(expr, `Variable type ` +
`"${singleDeclaration.variableType[0]}" ` +
`does not have a default initial value`);
}
} else if (singleDeclaration.variableType.includes('null')) {
// Use null if null is allowed
value = getMaybePooled('null', null);
} else {
throw WTCDError.atLocation(expr, `Variable type ` +
`"${singleDeclaration.variableType.join(' ')}" does not have a ` +
`default initial value`);
}
}
if (!isTypeAssignableTo(value.type, singleDeclaration.variableType)) {
throw WTCDError.atLocation(expr, `The type of variable ` +
`${singleDeclaration.variableName} is ` +
`${singleDeclaration.variableType}, thus cannot hold ` +
`${describe(value)}`);
}
this.getCurrentScope().addVariable(singleDeclaration.variableName, {
types: singleDeclaration.variableType,
value,
});
}
}
private evaluateBlockExpression(expr: BlockExpression): RuntimeValue {
const scope = this.pushScope();
try {
scope.addRegister('yield');
for (const statement of expr.statements) {
this.executeStatement(statement);
}
return scope.getRegister('yield')!;
} catch (error) {
if (
(error instanceof BubbleSignal) &&
(error.type === BubbleSignalType.YIELD)
) {
return scope.getRegister('yield')!;
}
throw error;
} finally {
this.popScope();
}
}
private evaluateSelectionExpression(expr: SelectionAction): ActionValue {
const choicesList = this.evaluator(expr.choices);
if (choicesList.type !== 'list') {
throw WTCDError.atLocation(expr, `Expression after selection is ` +
`expected to be a list of choices, received: ` +
`${describe(choicesList)}`);
}
const choices = choicesList.value
.filter(choice => choice.type !== 'null');
for (let i = 0; i < choices.length; i++) {
if (choices[i].type !== 'choice') {
throw WTCDError.atLocation(expr, `Choice at index ${i} is expected ` +
`to be a choice, received: ${describe(choices[i])}`);
}
}
return {
type: 'action',
value: {
action: 'selection',
choices: choices as Array<Readonly<ChoiceValue>>,
},
};
}
private evaluateListExpression(expr: ListExpression): ListValue {
return {
type: 'list',
value: flat(expr.elements.map(expr => {
if (expr.type !== 'spread') {
return this.evaluator(expr);
}
const list = this.evaluator(expr.expression);
if (list.type !== 'list') {
throw WTCDError.atLocation(expr, `Spread operator "..." can only ` +
`be used before a list, received: ${describe(list)}`);
}
return list.value;
})),
};
}
private evaluateFunctionExpression(expr: FunctionExpression): FunctionValue {
return {
type: 'function',
value: {
fnType: 'wtcd',
expr,
captured: expr.captures.map(variableName => ({
name: variableName,
value: this.resolveVariableReference(variableName),
})),
},
};
}
private evaluateSwitchExpression(expr: SwitchExpression): RuntimeValue {
const switchValue = this.evaluator(expr.expression);
for (const switchCase of expr.cases) {
const matches = this.evaluator(switchCase.matches);
if (matches.type !== 'list') {
throw WTCDError.atLocation(switchCase.matches, `Value to match for ` +
`each case is expected to be a list, received: ` +
`${describe(matches)}`);
}
if (matches.value.some(oneMatch => isEqual(oneMatch, switchValue))) {
// Matched
return this.evaluator(switchCase.returns);
}
}
// Default
if (expr.defaultCase === null) {
throw WTCDError.atLocation(expr, `None of the cases matched and no ` +
`default case is provided`);
} else {
return this.evaluator(expr.defaultCase);
}
}
private evaluateWhileExpression(expr: WhileExpression) {
const scope = this.pushScope();
scope.addRegister('break');
let continueFlag = false;
try { // Break
while (true) {
if (!continueFlag && expr.preExpr !== null) {
try { // Continue
this.evaluator(expr.preExpr);
} catch (error) {
if (!(
(error instanceof BubbleSignal) &&
(error.type === BubbleSignalType.CONTINUE)
)) {
throw error;
}
}
}
continueFlag = false;
const whileCondition = this.evaluator(expr.condition);
if (whileCondition.type !== 'boolean') {
throw WTCDError.atLocation(expr, `Condition expression of a while ` +
`loop is expected to return a boolean. Received: ` +
`${describe(whileCondition)}`);
}
if (whileCondition.value === false) {
break;
}
if (expr.postExpr !== null) {
try { // Continue
this.evaluator(expr.postExpr);
} catch (error) {
if (!(
(error instanceof BubbleSignal) &&
(error.type === BubbleSignalType.CONTINUE)
)) {
throw error;
}
continueFlag = true;
}
}
}
} catch (error) {
if (
(error instanceof BubbleSignal) &&
(error.type === BubbleSignalType.BREAK)
) {
return scope.getRegister('break')!;
}
throw error;
} finally {
this.popScope();
}
return scope.getRegister('break')!;
}
private evaluateIfExpression(expr: IfExpression) {
const condition = this.evaluator(expr.condition);
if (condition.type !== 'boolean') {
throw WTCDError.atLocation(expr, `The condition of an if expression is ` +
`expected to be a boolean. Received: ${describe(condition)}`);
}
if (condition.value) {
return this.evaluator(expr.then);
} else if (expr.otherwise !== null) {
return this.evaluator(expr.otherwise);
} else {
return getMaybePooled('null', null);
}
}
private evaluator(expr: Expression): RuntimeValue {
switch (expr.type) {
case 'unaryExpression':
return unaryOperators.get(expr.operator)!.fn(
expr,
this.interpreterHandle,
);
case 'binaryExpression':
return binaryOperators.get(expr.operator)!.fn(
expr,
this.interpreterHandle,
);
case 'booleanLiteral':
return getMaybePooled('boolean', expr.value);
case 'numberLiteral':
return getMaybePooled('number', expr.value);
case 'stringLiteral':
return getMaybePooled('string', expr.value);
case 'nullLiteral':
return getMaybePooled('null', null);
case 'list':
return this.evaluateListExpression(expr);
case 'choiceExpression':
return this.evaluateChoiceExpression(expr);
case 'conditionalExpression':
return this.evaluateConditionalExpression(expr);
case 'block':
return this.evaluateBlockExpression(expr);
case 'gotoAction':
return {
type: 'action',
value: {
action: 'goto',
target: expr.sections,
},
};
case 'exitAction':
return {
type: 'action',
value: {
action: 'exit',
},
};
case 'selection':
return this.evaluateSelectionExpression(expr);
case 'variableReference':
return this.resolveVariableReference(expr.variableName).value;
case 'function':
return this.evaluateFunctionExpression(expr);
case 'switch':
return this.evaluateSwitchExpression(expr);
case 'while':
return this.evaluateWhileExpression(expr);
case 'if':
return this.evaluateIfExpression(expr);
case 'tag':
return {
type: 'list',
value: [ getMaybePooled('string', expr.name) ],
};
}
}
private executeStatement(statement: Statement) {
switch (statement.type) {
case 'declaration':
this.executeDeclarationStatement(statement);
return;
case 'expression':
this.evaluator(statement.expression);
return;
case 'yield':
this.setRegister('yield', this.evaluator(statement.value));
throw new BubbleSignal(BubbleSignalType.YIELD); // Bubble up
case 'setYield':
this.setRegister('yield', this.evaluator(statement.value));
return;
case 'return':
this.setRegister('return', this.evaluator(statement.value));
throw new BubbleSignal(BubbleSignalType.RETURN);
case 'setReturn':
this.setRegister('return', this.evaluator(statement.value));
return;
case 'break':
this.setRegister('break', this.evaluator(statement.value));
throw new BubbleSignal(BubbleSignalType.BREAK);
case 'setBreak':
this.setRegister('break', this.evaluator(statement.value));
return;
case 'continue':
throw new BubbleSignal(BubbleSignalType.CONTINUE);
}
}
private addToSectionStack(sectionName: string) {
for (const section of this.wtcdRoot.sections) {
if (section.name === sectionName) {
this.sectionStack.push(section);
return;
}
}
throw WTCDError.atUnknown(`Unknown section "${sectionName}"`);
}
private updatePinned() {
if (this.pinnedFunction !== null) {
try {
invokeFunctionRaw(
this.pinnedFunction.value,
[],
this.interpreterHandle,
);
} catch (error) {
if (error instanceof FunctionInvocationError) {
throw WTCDError.atUnknown(`Failed to invoke the pinned ` +
`function (${describe(this.pinnedFunction)}): ` +
error.message);
} else if (error instanceof WTCDError) {
error.pushWTCDStack(`Pinned function (` +
`${describe(this.pinnedFunction)})`);
}
throw error;
}
this.pinned = this.currentlyBuilding;
this.currentlyBuilding = [];
} else if (this.pinned.length !== 0) {
this.pinned = [];
}
}
private *executeAction(action: ActionValue): Generator<ContentOutput, void, number> {
switch (action.value.action) {
case 'goto':
for (let i = action.value.target.length - 1; i >= 0; i--) {
this.addToSectionStack(action.value.target[i]);
}
break;
case 'exit':
// Clears the section stack so the scripts end immediately
this.sectionStack.length = 0;
break;
case 'selection': {
const choicesRaw = action.value.choices;
const choices: Array<SingleChoice> = choicesRaw.map(choice => ({
content: choice.value.text,
disabled: choice.value.action.type === 'null',
}));
const yieldValue: ContentOutput = {
content: this.currentlyBuilding,
choices,
};
this.currentlyBuilding = [];
this.updatePinned();
// Hands over control so player can make a decision
const playerChoiceIndex = yield yieldValue;
const playerChoice = choicesRaw[playerChoiceIndex];
if (playerChoice === undefined || playerChoice.value.action.type === 'null') {
throw new InvalidChoiceError(playerChoiceIndex);
}
yield* this.executeAction(playerChoice.value.action);
break;
}
case 'function': {
let newAction: RuntimeValue;
try {
newAction = invokeFunctionRaw(
action.value.fn.value,
[], this.interpreterHandle,
);
} catch (error) {
if (error instanceof FunctionInvocationError) {
throw WTCDError.atLocation(
action.value.creator,
`Failed to evaluate the function action for this choice: ` +
`${error.message}`,
);
} else if (error instanceof WTCDError) {
error.pushWTCDStack(`Function action`, action.value.creator);
}
throw error;
}
if (newAction.type === 'action') {
yield* this.executeAction(newAction);
} else if (newAction.type !== 'null') {
throw WTCDError.atLocation(action.value.creator, `Value returned ` +
`an function action is expected to be an action or null. ` +
`Received: ${describe(newAction)}`);
}
break;
}
}
}
private started = false;
private sectionEnterTimes = new Map<string, number>();
private currentlyBuilding: Array<HTMLElement> = [];
private pushContent($element: HTMLElement) {
this.currentlyBuilding.push($element);
}
private runSection(section: Section): RuntimeValue {
const $mdHost = document.createElement('div');
// Evaluate the executes clause
if (section.executes !== null) {
this.evaluator(section.executes);
}
/** Times this section has been entered including this time */
const enterTime = this.sectionEnterTimes.has(section.name)
? this.sectionEnterTimes.get(section.name)! + 1
: 1;
this.sectionEnterTimes.set(section.name, enterTime);
/** Content that fits within the bounds */
const eligibleSectionContents = section.content.filter(
content => (content.lowerBound === undefined || content.lowerBound <= enterTime) &&
(content.upperBound === undefined || content.upperBound >= enterTime),
);
if (eligibleSectionContents.length !== 0) {
const selectedContent = eligibleSectionContents[
this.random.nextInt(0, eligibleSectionContents.length)
];
$mdHost.innerHTML = selectedContent.html;
// Parameterize
for (const variable of selectedContent.variables) {
($mdHost.getElementsByClassName(variable.elementClass)[0] as HTMLSpanElement)
.innerText = String(this.resolveVariableReference(variable.variableName).value.value);
}
let $current = $mdHost.firstChild;
while ($current !== null) {
if ($current instanceof HTMLElement) {
this.pushContent($current);
}
$current = $current.nextSibling;
}
}
return this.evaluator(section.then);
}
public getPinned() {
return this.pinned;
}
public getStateDesc() {
return this.stateDesc;
}
public *start(): Generator<ContentOutput, ContentOutput, number> {
const stdScope = this.pushScope();
for (const stdFunction of stdFunctions) {
stdScope.addVariable(stdFunction.name, {
types: ['function'],
value: {
type: 'function',
value: {
fnType: 'native',
nativeFn: stdFunction,
},
},
});
}
// Global scope
this.pushScope();
if (this.started) {
throw new Error('Interpretation has already started.');
}
this.started = true;
let lastSection: Section | null = null;
try {
// Initialization
for (const statement of this.wtcdRoot.initStatements) {
this.executeStatement(statement);
}
while (this.sectionStack.length !== 0) {
const currentSection = this.sectionStack.pop()!;
lastSection = currentSection;
const then = this.runSection(currentSection);
if (then.type === 'action') {
yield* this.executeAction(then);
} else if (then.type !== 'null') {
throw WTCDError.atLocation(currentSection.then, `Expression after ` +
`then is expected to return an action, or null, ` +
`received: ${describe(then)}`);
}
}
} catch (error) {
if (error instanceof BubbleSignal) {
throw WTCDError.atUnknown(`Uncaught BubbleSignal with type "${error.type}".`);
}
if (error instanceof WTCDError) {
if (lastSection === null) {
error.pushWTCDStack(`initialization`);
} else {
error.pushWTCDStack(`section "${lastSection.name}"`, lastSection);
}
}
throw error;
}
const lastContent = {
content: this.currentlyBuilding,
choices: [],
};
this.updatePinned();
return lastContent;
}
}
|
kink/kat
|
src/wtcd/Interpreter.ts
|
TypeScript
|
unknown
| 32,816 |
/**
* Convert a string to 32 bit hash
* https://stackoverflow.com/a/47593316
*/
function xmur3(strSeed: string) {
let h = 1779033703 ^ strSeed.length;
for (let i = 0; i < strSeed.length; i++) {
h = Math.imul(h ^ strSeed.charCodeAt(i), 3432918353),
h = h << 13 | h >>> 19;
}
return () => {
h = Math.imul(h ^ h >>> 16, 2246822507);
h = Math.imul(h ^ h >>> 13, 3266489909);
return (h ^= h >>> 16) >>> 0;
};
}
/**
* Create a seeded random number generator using the four passed in 32 bit
* number as seeds.
* https://stackoverflow.com/a/47593316
*
* @param a seed
* @param b seed
* @param c seed
* @param d seed
* @returns seeded random number generator
*/
function sfc32(a: number, b: number, c: number, d: number) {
return () => {
a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0;
let t = (a + b) | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = (c << 21 | c >>> 11);
d = d + 1 | 0;
t = t + d | 0;
c = c + t | 0;
return (t >>> 0) / 4294967296;
};
}
export class Random {
private rng: () => number;
public constructor(seed: string) {
const seedFn = xmur3(seed);
this.rng = sfc32(seedFn(), seedFn(), seedFn(), seedFn());
}
public next(low = 0, high = 1) {
return this.rng() * (high - low) + low;
}
public nextBool() {
return this.rng() < 0.5;
}
public nextInt(low: number, high: number) {
return Math.floor(this.next(low, high));
}
}
|
kink/kat
|
src/wtcd/Random.ts
|
TypeScript
|
unknown
| 1,464 |
/**
* This is used to generate ids for interpolated values in sections. Name
* generator is used in order to prevent reader from learning all the variable
* names simply by inspecting elements. Of course, reader can still read the
* compiled tree structure or the source code for the corresponding passage.
* However, that will involve slightly more effort.
*/
export class SimpleIdGenerator {
private charPool!: Array<string>;
private index: number = 0;
private getName(index: number): string {
if (index >= this.charPool.length) {
return this.getName(Math.floor(index / this.charPool.length) - 1)
+ this.charPool[index % this.charPool.length];
}
return this.charPool[index];
}
public next() {
if (this.charPool === undefined) {
this.charPool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
.split('')
.sort(() => Math.random() - 0.5);
}
return this.getName(this.index++);
}
}
|
kink/kat
|
src/wtcd/SimpleIdGenerator.ts
|
TypeScript
|
unknown
| 975 |
import { englishConcatenation } from './englishConcatenation';
import { operators } from './operators';
import { WTCDError } from './WTCDError';
/**
* A stream of discrete items.
*/
abstract class ItemStream<T> {
/** Whether the first element is read */
private initCompleted: boolean = false;
/** Element next #next() or #peek() call will return */
private current: T | undefined;
/**
* Symbol for #readNext() implementation to indicate additional call is
* required.
*/
public static readonly RECALL = Symbol('recall');
/**
* Read next item. If this read failed to obtain an item, return
* ItemStream.RECALL will result an additional call.
* @return asd
*/
protected abstract readNext(): T | undefined | typeof ItemStream.RECALL;
/** Callback when next is called but next item does not exist */
protected abstract onNextCallWhenEOF(): never;
/** Calls readNext and handles ItemStream.RECALL */
private readNextWithRecall() {
this.initCompleted = true;
let item;
do {
item = this.readNext();
} while (item === ItemStream.RECALL);
this.current = item;
return this.current as T | undefined;
}
private ensureInitCompleted() {
if (!this.initCompleted) {
this.readNextWithRecall();
}
}
public peek(): T | undefined {
this.ensureInitCompleted();
return this.current;
}
public next(): T {
this.ensureInitCompleted();
const item = this.current;
if (item === undefined) {
return this.onNextCallWhenEOF();
}
this.readNextWithRecall();
return item;
}
public eof() {
return this.peek() === undefined;
}
}
/**
* A steam of characters. Automatically handles inconsistency in line breaks and
* line/column counting.
*/
class CharStream extends ItemStream<string> {
public constructor(
private source: string,
) {
super();
}
private pointer: number = -1;
private line: number = 1;
private column: number = 0;
protected readNext() {
this.pointer++;
const current = this.source[this.pointer];
if (current === '\r' || current === '\n') {
this.line++;
this.column = 0;
if (current === '\r' && (this.source[this.pointer + 1] === '\n')) { // Skip \r\n
this.pointer++;
}
return '\n';
}
this.column++;
return current;
}
protected onNextCallWhenEOF() {
return this.throwUnexpectedNext();
}
public throw(message: string): never {
throw WTCDError.atLineColumn(this.line, this.column, message);
}
public describeNext(): string {
switch (this.peek()) {
case undefined: return '<EOF>';
case '\t': return '<TAB>';
case '\n': return '<LF>';
default: return '"' + this.peek() + '"';
}
}
public throwUnexpectedNext(expecting?: string): never {
if (expecting === undefined) {
return this.throw(`Unexpected character ${this.describeNext()}`);
} else {
return this.throw(`Unexpected character ${this.describeNext()}, expecting ${expecting}`);
}
}
public getLine(): number {
return this.line;
}
public getColumn(): number {
return this.column;
}
/** Reads next n chars without handling line breaks. */
public peekNextNChars(n: number): string {
return this.source.substr(this.pointer, n);
}
}
function includes(from: string, char: string | undefined) {
if (char === undefined) {
return false;
}
return from.includes(char);
}
function isNumberPart(char: string | undefined) {
return includes('0123456789.', char);
}
function isAtNumberStart(charStream: CharStream) {
return includes('0123456789', charStream.peek()) || (
(charStream.peek() === '.') &&
(includes('0123456789', charStream.peekNextNChars(2)[1]))
);
}
function isSpace(char: string | undefined) {
return includes(' \t\n', char);
}
function isIdentifierStart(char: string | undefined) {
return includes('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_', char);
}
function isIdentifierBody(char: string | undefined) {
return includes('1234567890', char) || isIdentifierStart(char);
}
function isOperatorPart(char: string | undefined) {
return includes('+-*/^&|=><!?:%~.', char);
}
function isPunctuation(char: string | undefined) {
return includes('[](){}$', char);
}
function isStringQuote(char: string | undefined) {
return includes('"\'`', char);
}
function isTagStart(char: string | undefined) {
return char === '#';
}
function isTagBody(char: string | undefined) {
return isIdentifierBody(char);
}
function isCommentStarter(str: string) {
return ['//', '/*'].includes(str);
}
type TokenType = 'identifier' | 'keyword' | 'operator' | 'punctuation' | 'string' | 'number' | 'tag';
interface TokenContent {
type: TokenType;
content: string;
}
export type Token = TokenContent & {
line: number;
column: number;
};
const keywords = new Set([
'declare',
'section',
'then',
'goto',
'null',
'true',
'false',
'number',
'boolean',
'string',
'action',
'choice',
'selection',
'yield',
'exit',
'function',
'return',
'switch',
'while',
'do',
'continue',
'break',
'if',
'else',
'list',
// Reserved
'for',
'in',
'of',
'enum',
'dict',
'dictionary',
'const',
'mixed',
]);
const escapeMap = new Map([
['n', '\n'],
['t', '\t'],
['\'', '\''],
['"', '"'],
['`', '`'],
['\\', '\\'],
]);
export class TokenStream extends ItemStream<Token> {
private charStream: CharStream;
public constructor(
source: string,
) {
super();
this.charStream = new CharStream(source);
}
public isNext(type: TokenType, content?: string | Array<string>) {
const token = this.peek();
if (token === undefined) {
return false;
}
return (token.type === type) && (content === undefined || (Array.isArray(content)
? content.includes(token.content)
: token.content === content));
}
private describeToken(token: Token) {
return `${token.type} "${token.content}"`;
}
public assertNext(type: TokenType, content?: string | Array<string>) {
if (!this.isNext(type, content)) {
const expecting = content === undefined
? type
: Array.isArray(content)
? `${type} ${englishConcatenation(content.map(item => `"${item}"`))}`
: `${type} "${content}"`;
return this.throwUnexpectedNext(expecting);
}
return this.peek()!;
}
public assertAndSkipNext(type: TokenType, content?: string | Array<string>) {
this.assertNext(type, content);
return this.next()!;
}
public throwUnexpectedNext(expecting?: string): never {
const token = this.peek();
if (token === undefined) {
throw this.charStream.throwUnexpectedNext(expecting);
}
if (expecting === undefined) {
throw WTCDError.atLineColumn(token.line, token.column, `Unexpected token ${this.describeToken(token)}`);
} else {
throw WTCDError.atLineColumn(token.line, token.column, `Unexpected token ${this.describeToken(token)}, expecting ${expecting}`);
}
}
protected onNextCallWhenEOF(): never {
throw WTCDError.atLineColumn(this.charStream.getLine(), this.charStream.getColumn(), 'Unexpected <EOF>');
}
/** Reads from charStream until predicate returns false for next char */
private readWhile(predicate: (char: string | undefined) => boolean) {
let result = '';
while (predicate(this.charStream.peek())) {
result += this.charStream.next();
}
return result;
}
/** Assuming next char is a part of an identifier, reads next identifier */
private readIdentifier() {
return this.charStream.next() + this.readWhile(isIdentifierBody);
}
private readTag() {
this.charStream.next();
return this.readWhile(isTagBody); // # <- is ignored
}
/** Assuming next char is a part of a number, reads next number */
private readNumber() {
let num = this.charStream.next();
/** Whether dot appeared yet */
let dot = num === '.';
while (isNumberPart(this.charStream.peek())) {
if (this.charStream.peek() === '.') {
if (dot) {
return this.charStream.throwUnexpectedNext('number');
} else {
dot = true;
}
}
num += this.charStream.next();
}
return num;
}
/** Assuming next char is a part of an operator, reads next operator */
private readOperator() {
return this.charStream.next() + this.readWhile(isOperatorPart);
}
/** Assuming next char is a string quote, reads the string */
private readString() {
const quote = this.charStream.next();
let str = '';
while (this.charStream.peek() !== quote) {
if (this.charStream.eof()) {
this.charStream.throwUnexpectedNext(quote);
}
if (this.charStream.peek() !== '\\') {
str += this.charStream.next();
} else {
this.charStream.next();
const escaped = escapeMap.get(this.charStream.peek()!);
if (escaped === undefined) {
this.charStream.throw(`Unescapable character ${this.charStream.describeNext()}`);
}
str += escaped;
this.charStream.next();
}
}
this.charStream.next();
return str;
}
/** Assuming next char is a comment starter ("/"), skips the entire comment */
private skipComment() {
this.charStream.next(); // Skips /
if (this.charStream.peek() === '*') { // Block comment
this.charStream.next(); // Skips *
while (true) {
while (this.charStream.peek() !== '*') {
this.charStream.next();
}
this.charStream.next(); // Skips *
if (this.charStream.next() === '/') { // Skips /
return;
}
}
} else if (this.charStream.peek() === '/') { // Line comment
this.charStream.next(); // Skips the second /
while (this.charStream.peek() !== '\n') {
this.charStream.next();
}
this.charStream.next(); // Skips \n
} else {
this.charStream.throw(`Unknown comment type.`);
}
}
protected readNext() {
while (isSpace(this.charStream.peek())) {
this.charStream.next();
}
if (this.charStream.eof()) {
return undefined;
}
if (isCommentStarter(this.charStream.peekNextNChars(2))) {
this.skipComment();
return ItemStream.RECALL;
}
const line = this.charStream.getLine();
const column = this.charStream.getColumn();
let tokenContent: TokenContent;
if (isIdentifierStart(this.charStream.peek())) {
const identifier = this.readIdentifier();
tokenContent = {
type: keywords.has(identifier) ? 'keyword' : 'identifier',
content: identifier,
};
} else if (isAtNumberStart(this.charStream)) {
tokenContent = {
type: 'number',
content: this.readNumber(),
};
} else if (isOperatorPart(this.charStream.peek())) {
tokenContent = {
type: 'operator',
content: this.readOperator(),
};
if (!operators.has(tokenContent.content)) {
throw WTCDError.atLineColumn(line, column, `Unknown operator: "${tokenContent.content}"`);
}
} else if (isPunctuation(this.charStream.peek())) {
tokenContent = {
type: 'punctuation',
content: this.charStream.next(),
};
} else if (isStringQuote(this.charStream.peek())) {
tokenContent = {
type: 'string',
content: this.readString(),
};
} else if (isTagStart(this.charStream.peek())) {
tokenContent = {
type: 'tag',
content: this.readTag(),
};
} else {
return this.charStream.throwUnexpectedNext();
}
return {
line,
column,
...tokenContent,
};
}
}
|
kink/kat
|
src/wtcd/TokenStream.ts
|
TypeScript
|
unknown
| 11,725 |
import { OptionalLocationInfo } from './types';
const empty = {};
export class WTCDError<TLocationInfo extends boolean> extends Error {
private readonly wtcdStackArray: Array<string> = [];
private constructor(
message: string,
public readonly line: TLocationInfo extends true ? number : null,
public readonly column: TLocationInfo extends true ? number : null,
) {
super(message);
this.name = 'WTCDError';
}
public get wtcdStack() {
return this.message + '\n' + this.wtcdStackArray.join('\n');
}
public pushWTCDStack(info: string, location: OptionalLocationInfo = empty) {
this.wtcdStackArray.push(` at ${info}`
+ (location.line
? ':' + location.line
+ (location.column
? ':' + location.column
: '')
: ''),
);
}
public static atUnknown(message: string) {
return new WTCDError<false>(message + ` at unknown location. (Location `
+ `info is not available for this type of error)`, null, null);
}
public static atLineColumn(line: number, column: number, message: string) {
return new WTCDError<true>(
message + ` at ${line}:${column}.`,
line,
column,
);
}
public static atLocation(
location: OptionalLocationInfo | null,
message: string,
) {
if (location === null) {
return WTCDError.atUnknown(message);
}
if (location.line === undefined) {
return new WTCDError(message + ' at unknown location. (Try recompile in '
+ 'debug mode to enable source map)', null, null);
} else {
return WTCDError.atLineColumn(location.line, location.column!, message);
}
}
}
|
kink/kat
|
src/wtcd/WTCDError.ts
|
TypeScript
|
unknown
| 1,664 |
import { InterpreterHandle, RuntimeValue } from './Interpreter';
import { BinaryOperatorFn } from './operators';
import { BinaryExpression } from './types';
export function autoEvaluated(fn: (
arg0: RuntimeValue,
arg1: RuntimeValue,
expr: BinaryExpression,
interpreterHandle: InterpreterHandle,
) => RuntimeValue): BinaryOperatorFn {
return (expr, interpreterHandle) => {
const arg0 = interpreterHandle.evaluator(expr.arg0);
const arg1 = interpreterHandle.evaluator(expr.arg1);
return fn(arg0, arg1, expr, interpreterHandle);
};
}
|
kink/kat
|
src/wtcd/autoEvaluated.ts
|
TypeScript
|
unknown
| 555 |
import { BooleanValue, NullValue, NumberValue, RuntimeValue, RuntimeValueRaw, RuntimeValueType, Variable } from './Interpreter';
// Your typical immature optimization
// Caches null values, boolean values, and small integers to somewhat reduce GC
export const nullValue: NullValue = { type: 'null', value: null };
export const trueValue: BooleanValue = { type: 'boolean', value: true };
export const falseValue: BooleanValue = { type: 'boolean', value: false };
export const smallIntegers: Array<NumberValue> = [];
for (let i = 0; i <= 100; i++ ) {
smallIntegers.push({
type: 'number',
value: i,
});
}
export function booleanValue(value: boolean) {
return value ? trueValue : falseValue;
}
export function getMaybePooled<T extends RuntimeValueType>(
type: T,
value: RuntimeValueRaw<T>,
): Extract<RuntimeValue, { type: T }> {
if (type === 'null') {
return nullValue as any;
}
if (type === 'boolean') {
return booleanValue(value as boolean) as any;
}
if (type === 'number' && (value as number) >= 0 && (value as number) <= 100 && ((value as number) % 1 === 0)) {
return smallIntegers[value as number] as any;
}
return {
type,
value,
} as any;
}
|
kink/kat
|
src/wtcd/constantsPool.ts
|
TypeScript
|
unknown
| 1,200 |
export function englishConcatenation(strings: Array<string>, relation = 'or') {
switch (strings.length) {
case 0: return '';
case 1: return strings[0];
case 2: return `${strings[0]} ${relation} ${strings[1]}`;
default: return strings
.slice()
.splice(-1, 1, `${relation} ${strings[strings.length - 1]}`)
.join(', ');
}
}
|
kink/kat
|
src/wtcd/englishConcatenation.ts
|
TypeScript
|
unknown
| 359 |
import { autoEvaluated } from './autoEvaluated';
import { getMaybePooled } from './constantsPool';
import { BubbleSignal, BubbleSignalType, describe, InterpreterHandle, isTypeAssignableTo, RuntimeValue, RuntimeValueRaw } from './Interpreter';
import { NativeFunctionError } from './std/utils';
import { BinaryExpression } from './types';
import { WTCDError } from './WTCDError';
export class FunctionInvocationError extends Error {
public constructor(message: string) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
export function invokeFunctionRaw(
functionValue: RuntimeValueRaw<'function'>,
args: ReadonlyArray<RuntimeValue>,
interpreterHandle: InterpreterHandle,
): RuntimeValue {
const {
evaluator,
pushScope,
popScope,
} = interpreterHandle;
if (functionValue.fnType === 'native') {
try {
return functionValue.nativeFn(args, interpreterHandle);
} catch (error) {
if (error instanceof NativeFunctionError) {
// Wrap up native function errors
throw new FunctionInvocationError(`Failed to call native function ` +
`"${functionValue.nativeFn.name}". Reason: ${error.message}`);
} else {
throw error;
}
}
} else if (functionValue.fnType === 'wtcd') {
const scope = pushScope();
try {
scope.addRegister('return');
// Check and add arguments to the scope
functionValue.expr.arguments.forEach((argument, index) => {
let value = args[index];
if (value === undefined || value.type === 'null') {
// Use default
if (argument.defaultValue !== null) {
value = evaluator(argument.defaultValue);
} else if (isTypeAssignableTo('null', argument.type)) {
value = getMaybePooled('null', null);
} else {
throw new FunctionInvocationError(`The argument with index = ` +
`${index} of invocation is omitted, but it does not have a ` +
`default value and it does not allow null values`);
}
}
if (!isTypeAssignableTo(value.type, argument.type)) {
throw new FunctionInvocationError(`The argument with index = ` +
`${index} of invocation has wrong type. Expected: ` +
`${argument.type}, received: ${describe(value)}`);
}
scope.addVariable(argument.name, {
types: [value.type],
value,
});
});
// Rest arg
if (functionValue.expr.restArgName !== null) {
scope.addVariable(
functionValue.expr.restArgName, {
types: ['list'],
value: {
type: 'list',
value: args.slice(functionValue.expr.arguments.length),
},
},
);
}
// Restore captured variables
functionValue.captured.forEach(captured => {
scope.addVariable(
captured.name,
captured.value,
);
});
// Invoke function
const evaluatedValue = evaluator(functionValue.expr.expression);
const registerValue = scope.getRegister('return')!;
// Prioritize register value
if (registerValue.type === 'null') {
// Only use evaluated value if no return or setReturn statement is
// executed.
return evaluatedValue;
} else {
return registerValue;
}
} catch (error) {
if (
(error instanceof BubbleSignal) &&
(error.type === BubbleSignalType.RETURN)
) {
return scope.getRegister('return')!;
}
throw error;
} finally {
popScope();
}
} else {
let fn: RuntimeValueRaw<'function'> = functionValue;
const leftApplied = [];
const rightApplied = [];
do {
if (fn.isLeft) {
leftApplied.unshift(...fn.applied);
} else {
rightApplied.push(...fn.applied);
}
fn = fn.targetFn.value;
} while (fn.fnType === 'partial');
return invokeFunctionRaw(
fn,
[...leftApplied, ...args, ...rightApplied],
interpreterHandle,
);
}
}
function handleError(expr: BinaryExpression, error: any): never {
if (error instanceof FunctionInvocationError) {
throw WTCDError.atLocation(expr, error.message);
} else if (error instanceof WTCDError) {
error.pushWTCDStack(`"${expr.operator}" invocation`, expr);
}
throw error;
}
export const regularInvocationRaw = (
arg0: RuntimeValue,
arg1: RuntimeValue,
expr: BinaryExpression,
interpreterHandle: InterpreterHandle,
) => {
if (arg0.type !== 'function') {
throw WTCDError.atLocation(expr, `Left side of function invocation ` +
`"${expr.operator}" is expected to be a function, received: ` +
`${describe(arg0)}`);
}
if (arg1.type !== 'list') {
throw WTCDError.atLocation(expr, `Right side of function invocation ` +
`"${expr.operator}" is expected to be a list, received: ` +
`${describe(arg1)}`);
}
try {
return invokeFunctionRaw(arg0.value, arg1.value, interpreterHandle);
} catch (error) {
return handleError(expr, error);
}
};
export const regularInvocation = autoEvaluated(regularInvocationRaw);
export const pipelineInvocation = autoEvaluated((
arg0,
arg1,
expr,
interpreterHandle,
) => {
if (arg1.type !== 'function') {
throw WTCDError.atLocation(expr, `Right side of pipeline invocation "|>" ` +
`is expected to be a function, received: ${describe(arg1)}`);
}
try {
return invokeFunctionRaw(arg1.value, [ arg0 ], interpreterHandle);
} catch (error) {
return handleError(expr, error);
}
});
export const reverseInvocation = autoEvaluated((
arg0,
arg1,
expr,
interpreterHandle,
) => {
if (arg0.type !== 'list') {
throw WTCDError.atLocation(expr, `Left side of reverse invocation "|::" ` +
`is expected to be a list, received: ${describe(arg0)}`);
}
if (arg1.type !== 'function') {
throw WTCDError.atLocation(expr, `Right side of reverse invocation "|::" ` +
`is expected to be a function, received: ${describe(arg1)}`);
}
try {
return invokeFunctionRaw(arg1.value, arg0.value, interpreterHandle);
} catch (error) {
return handleError(expr, error);
}
});
|
kink/kat
|
src/wtcd/invokeFunction.ts
|
TypeScript
|
unknown
| 6,239 |
// This file defines all infix and prefix operators in WTCD.
import { autoEvaluated } from './autoEvaluated';
import { getMaybePooled } from './constantsPool';
import { assignValueToVariable, describe, InterpreterHandle, isEqual, RuntimeValue, RuntimeValueRaw, RuntimeValueType } from './Interpreter';
import {pipelineInvocation, regularInvocation, regularInvocationRaw, reverseInvocation} from './invokeFunction';
import { BinaryExpression, UnaryExpression } from './types';
import { WTCDError } from './WTCDError';
export type UnaryOperator = '-' | '!';
type UnaryOperatorFn = (expr: UnaryExpression, interpreterHandle: InterpreterHandle) => RuntimeValue;
export interface UnaryOperatorDefinition {
precedence: number;
fn: UnaryOperatorFn;
}
export const unaryOperators = new Map<string, UnaryOperatorDefinition>([
['-', {
precedence: 17,
fn: (expr, { evaluator }) => {
const arg = evaluator(expr.arg);
if (arg.type !== 'number') {
throw WTCDError.atLocation(expr, `Unary operator "-" can only be applied ` +
`to a number, received: ${describe(arg)}`);
}
return getMaybePooled('number', -arg.value);
},
}],
['!', {
precedence: 17,
fn: (expr, { evaluator }) => {
const arg = evaluator(expr.arg);
if (arg.type !== 'boolean') {
throw WTCDError.atLocation(expr, `Unary operator "!" can only be applied ` +
`to a boolean, received: ${describe(arg)}`);
}
return getMaybePooled('boolean', !arg.value);
},
}],
]);
export type BinaryOperator = '+' | '-' | '*' | '/' | '~/' | '%' | '=' | '+=' | '-=' | '*=' | '/=' | '~/=' | '%=';
export type BinaryOperatorFn = (
expr: BinaryExpression,
interpreterHandle: InterpreterHandle,
) => RuntimeValue;
export interface BinaryOperatorDefinition {
precedence: number;
fn: BinaryOperatorFn;
}
function autoEvaluatedSameTypeArg<TArg extends RuntimeValueType, TReturn extends RuntimeValueType>(
argType: TArg,
returnType: TReturn,
fn: (
arg0Raw: RuntimeValueRaw<TArg>,
arg1Raw: RuntimeValueRaw<TArg>,
expr: BinaryExpression,
interpreterHandle: InterpreterHandle,
) => RuntimeValueRaw<TReturn>,
): BinaryOperatorFn {
return autoEvaluated((arg0, arg1, expr, interpreterHandle) => {
if (arg0.type === argType && arg1.type === argType) {
// TypeScript is not smart enough to do the conversion here
return getMaybePooled(
returnType,
fn(
arg0.value as RuntimeValueRaw<TArg>,
arg1.value as RuntimeValueRaw<TArg>,
expr,
interpreterHandle,
),
);
} else {
throw WTCDError.atLocation(expr, `Binary operator "${expr.operator}" can only be ` +
`applied to two ${argType}s, received: ${describe(arg0)} (left) and ` +
`${describe(arg1)} (right)`);
}
});
}
function opAssignment<T0 extends RuntimeValueType, T1 extends RuntimeValueType>(
arg0Type: T0, // Type of the variable
arg1Type: T1,
fn: (
arg0Raw: RuntimeValueRaw<T0>,
arg1Raw: RuntimeValueRaw<T1>,
expr: BinaryExpression,
interpreterHandle: InterpreterHandle,
) => RuntimeValueRaw<T0>,
): BinaryOperatorFn {
return (expr, interpreterHandle) => {
if (expr.arg0.type !== 'variableReference') {
throw WTCDError.atLocation(expr, `Left side of binary operator "${expr.operator}" ` +
`has to be a variable reference`);
}
const varRef = interpreterHandle.resolveVariableReference(expr.arg0.variableName);
if (varRef.value.type !== arg0Type) {
throw WTCDError.atLocation(expr, `Left side of binary operator "${expr.operator}" has to be a ` +
`variable of type ${arg0Type}, actual type: ${varRef.value.type}`);
}
const arg1 = interpreterHandle.evaluator(expr.arg1);
if (arg1.type !== arg1Type) {
throw WTCDError.atLocation(expr, `Right side of binary operator "${expr.operator}" ` +
` has to be a ${arg1Type}, received: ${describe(arg1)}`);
}
const newValue = getMaybePooled(arg0Type, fn(
varRef.value.value as RuntimeValueRaw<T0>,
arg1.value as RuntimeValueRaw<T1>,
expr,
interpreterHandle,
));
varRef.value = newValue;
return newValue;
};
}
export const binaryOperators = new Map<string, BinaryOperatorDefinition>([
['=', {
precedence: 3,
fn: (expr, { evaluator, resolveVariableReference }) => {
if (expr.arg0.type !== 'variableReference') {
throw WTCDError.atLocation(expr, `Left side of binary operator "=" has to be a ` +
`variable reference`);
}
const varRef = resolveVariableReference(expr.arg0.variableName);
const arg1 = evaluator(expr.arg1);
assignValueToVariable(varRef, arg1, expr, expr.arg0.variableName);
return arg1;
},
}],
['+=', {
precedence: 3,
fn: (expr, { evaluator, resolveVariableReference }) => {
if (expr.arg0.type !== 'variableReference') {
throw WTCDError.atLocation(expr, `Left side of binary operator "+=" ` +
`has to be a variable reference`);
}
const varRef = resolveVariableReference(expr.arg0.variableName);
if (varRef.value.type !== 'string' && varRef.value.type !== 'number') {
throw WTCDError.atLocation(expr, `Left side of binary operator "+=" has to be a ` +
`variable of type number or string, actual type: ${varRef.value.type}`);
}
const arg1 = evaluator(expr.arg1);
if (arg1.type !== varRef.value.type) {
throw WTCDError.atLocation(expr, `Right side of binary operator "+=" has to ` +
` be a ${varRef.value.type}, received: ${describe(arg1)}`);
}
const newValue = getMaybePooled(
varRef.value.type,
(varRef.value.value as any) + arg1.value,
);
varRef.value = newValue;
return newValue;
},
}],
['-=', {
precedence: 3,
fn: opAssignment('number', 'number', (arg0Raw, arg1Raw) => arg0Raw - arg1Raw),
}],
['*=', {
precedence: 3,
fn: opAssignment('number', 'number', (arg0Raw, arg1Raw) => arg0Raw * arg1Raw),
}],
['/=', {
precedence: 3,
fn: opAssignment('number', 'number', (arg0Raw, arg1Raw) => arg0Raw / arg1Raw),
}],
['~/=', {
precedence: 3,
fn: opAssignment('number', 'number', (arg0Raw, arg1Raw) => Math.trunc(arg0Raw / arg1Raw)),
}],
['%=', {
precedence: 3,
fn: opAssignment('number', 'number', (arg0Raw, arg1Raw) => arg0Raw % arg1Raw),
}],
['|>', {
precedence: 5,
fn: pipelineInvocation,
}],
['|::', {
precedence: 5,
fn: reverseInvocation,
}],
['||', {
precedence: 6,
fn: (expr, { evaluator }) => {
const arg0 = evaluator(expr.arg0);
if (arg0.type !== 'boolean') {
throw WTCDError.atLocation(expr, `Left side of binary operator "||" has to be a boolean. ` +
`Received ${describe(arg0)}`);
}
if (arg0.value === true) {
return getMaybePooled('boolean', true);
}
const arg1 = evaluator(expr.arg1); // Short-circuit evaluation
if (arg1.type !== 'boolean') {
throw WTCDError.atLocation(expr, `Right side of binary operator "||" has to be a boolean. ` +
`Received ${describe(arg1)}`);
}
return getMaybePooled('boolean', arg1.value);
},
}],
['?!', {
precedence: 6,
fn: (expr, { evaluator }) => {
const arg0 = evaluator(expr.arg0);
if (arg0.type !== 'null') {
return arg0;
}
const arg1 = evaluator(expr.arg1);
if (arg1.type === 'null') {
throw WTCDError.atLocation(expr, `Right side of binary operator "?!" ` +
`cannot be null. If returning null is desired in this case, please ` +
`use "??" instead`);
}
return arg1;
},
}],
['??', {
precedence: 6,
fn: (expr, { evaluator }) => {
const arg0 = evaluator(expr.arg0);
if (arg0.type !== 'null') {
return arg0;
}
return evaluator(expr.arg1);
},
}],
['&&', {
precedence: 7,
fn: (expr, { evaluator }) => {
const arg0 = evaluator(expr.arg0);
if (arg0.type !== 'boolean') {
throw WTCDError.atLocation(expr, `Left side of binary operator "&&" has to be a boolean. ` +
`Received ${describe(arg0)}`);
}
if (arg0.value === false) {
return getMaybePooled('boolean', false);
}
const arg1 = evaluator(expr.arg1); // Short-circuit evaluation
if (arg1.type !== 'boolean') {
throw WTCDError.atLocation(expr, `Right side of binary operator "&&" has to be a boolean. ` +
`Received ${describe(arg1)}`);
}
return getMaybePooled('boolean', arg1.value);
},
}],
['==', {
precedence: 11,
fn: autoEvaluated((arg0, arg1) => (getMaybePooled(
'boolean',
isEqual(arg0, arg1),
))),
}],
['!=', {
precedence: 11,
fn: autoEvaluated((arg0, arg1) => (getMaybePooled(
'boolean',
!isEqual(arg0, arg1),
))),
}],
['<', {
precedence: 12,
fn: autoEvaluatedSameTypeArg('number', 'boolean', (arg0Raw, arg1Raw) => arg0Raw < arg1Raw),
}],
['<=', {
precedence: 12,
fn: autoEvaluatedSameTypeArg('number', 'boolean', (arg0Raw, arg1Raw) => arg0Raw <= arg1Raw),
}],
['>', {
precedence: 12,
fn: autoEvaluatedSameTypeArg('number', 'boolean', (arg0Raw, arg1Raw) => arg0Raw > arg1Raw),
}],
['>=', {
precedence: 12,
fn: autoEvaluatedSameTypeArg('number', 'boolean', (arg0Raw, arg1Raw) => arg0Raw >= arg1Raw),
}],
['+', {
precedence: 14,
fn: autoEvaluated((arg0, arg1, expr) => {
if (arg0.type === 'number' && arg1.type === 'number') {
return getMaybePooled(
'number',
arg0.value + arg1.value,
);
} else if (arg0.type === 'string' && arg1.type === 'string') {
return getMaybePooled(
'string',
arg0.value + arg1.value,
);
} else {
throw WTCDError.atLocation(expr, `Binary operator "+" can only be applied to two ` +
`strings or two numbers, received: ${describe(arg0)} (left) and ` +
`${describe(arg1)} (right)`);
}
}),
}],
['-', {
precedence: 14,
fn: autoEvaluatedSameTypeArg('number', 'number', (arg0Raw, arg1Raw) => arg0Raw - arg1Raw),
}],
['*', {
precedence: 15,
fn: autoEvaluatedSameTypeArg('number', 'number', (arg0Raw, arg1Raw) => arg0Raw * arg1Raw),
}],
['/', {
precedence: 15,
fn: autoEvaluatedSameTypeArg('number', 'number', (arg0Raw, arg1Raw) => arg0Raw / arg1Raw),
}],
['~/', {
precedence: 15,
fn: autoEvaluatedSameTypeArg('number', 'number', (arg0Raw, arg1Raw) => Math.trunc(arg0Raw / arg1Raw)),
}],
['%', {
precedence: 15,
fn: autoEvaluatedSameTypeArg('number', 'number', (arg0Raw, arg1Raw) => arg0Raw % arg1Raw),
}],
['**', {
precedence: 16,
fn: autoEvaluatedSameTypeArg('number', 'number', (arg0Raw, arg1Raw) => arg0Raw ** arg1Raw),
}],
['.', {
precedence: 19,
fn: autoEvaluated((arg0, arg1, expr) => {
if (arg0.type !== 'list') {
throw WTCDError.atLocation(expr, `Left side of binary operator "." ` +
`is expected to be a list. Received: ${describe(arg0)}`);
}
if (arg1.type !== 'number' || arg1.value % 1 !== 0) {
throw WTCDError.atLocation(expr, `Right side of binary operator "." ` +
`is expected to be an integer. Received: ${describe(arg1)}`);
}
const value = arg0.value[arg1.value];
if (value === undefined) {
throw WTCDError.atLocation(expr, `List does not have an element at ` +
`${arg1.value}. If return null is desired, use ".?" instead. List ` +
`contents: ${describe(arg0)}`);
}
return value;
}),
}],
['.?', {
precedence: 19,
fn: autoEvaluated((arg0, arg1, expr) => {
if (arg0.type !== 'list') {
throw WTCDError.atLocation(expr, `Left side of binary operator ".?" ` +
`is expected to be a list. Received: ${describe(arg0)}`);
}
if (arg1.type !== 'number' || arg1.value % 1 !== 0) {
throw WTCDError.atLocation(expr, `Right side of binary operator ".?" ` +
`is expected to be an integer. Received: ${describe(arg1)}`);
}
const value = arg0.value[arg1.value];
if (value === undefined) {
return getMaybePooled('null', null);
}
return value;
}),
}],
['?.', {
precedence: 19,
fn: (expr, { evaluator }) => {
const arg0 = evaluator(expr.arg0);
if (arg0.type === 'null') {
return arg0; // Short circuit
}
if (arg0.type !== 'list') {
throw WTCDError.atLocation(expr, `Left side of binary operator "?." ` +
`is expected to be a list or null. Received: ${describe(arg0)}`);
}
const arg1 = evaluator(expr.arg1);
if (arg1.type !== 'number' || arg1.value % 1 !== 0) {
throw WTCDError.atLocation(expr, `Right side of binary operator "?." ` +
`is expected to be an integer. Received: ${describe(arg1)}`);
}
const value = arg0.value[arg1.value];
if (value === undefined) {
throw WTCDError.atLocation(expr, `List does not have an element at ` +
`${arg1.value}. If return null is desired, use "?.?" instead. ` +
`List contents: ${describe(arg0)}`);
}
return value;
},
}],
['?.?', {
precedence: 19,
fn: (expr, { evaluator }) => {
const arg0 = evaluator(expr.arg0);
if (arg0.type === 'null') {
return arg0; // Short circuit
}
if (arg0.type !== 'list') {
throw WTCDError.atLocation(expr, `Left side of binary operator "?.?" ` +
`is expected to be a list or null. Received: ${describe(arg0)}`);
}
const arg1 = evaluator(expr.arg1);
if (arg1.type !== 'number' || arg1.value % 1 !== 0) {
throw WTCDError.atLocation(expr, `Right side of binary operator ` +
`"?.?" is expected to be an integer. Received: ${describe(arg1)}`);
}
const value = arg0.value[arg1.value];
if (value === undefined) {
return getMaybePooled('null', null);
}
return value;
},
}],
['::', {
precedence: 20,
fn: regularInvocation,
}],
['?::', {
precedence: 20,
fn: (expr, interpreterHandle) => {
const { evaluator } = interpreterHandle;
const arg0 = evaluator(expr.arg0);
if (arg0.type === 'null') {
return arg0; // Short circuit
}
return regularInvocationRaw(
arg0,
evaluator(expr.arg1),
expr,
interpreterHandle,
);
},
}],
['.:', {
precedence: 20,
fn: autoEvaluated((arg0, arg1, expr) => {
if (arg0.type !== 'function') {
throw WTCDError.atLocation(expr, `Left side of binary operator ".:" ` +
`is expected to be a function. Received: ${describe(arg0)}`);
}
if (arg1.type !== 'list') {
throw WTCDError.atLocation(expr, `Right side of binary operator ".:" ` +
`is expected to be a list. Received: ${describe(arg1)}`);
}
if (arg1.value.length === 0) {
return arg0;
}
return {
type: 'function',
value: {
fnType: 'partial',
isLeft: false,
applied: arg1.value,
targetFn: arg0,
},
};
}),
}],
[':.', {
precedence: 20,
fn: autoEvaluated((arg0, arg1, expr) => {
if (arg0.type !== 'function') {
throw WTCDError.atLocation(expr, `Left side of binary operator ":." ` +
`is expected to be a function. Received: ${describe(arg0)}`);
}
if (arg1.type !== 'list') {
throw WTCDError.atLocation(expr, `Right side of binary operator ":." ` +
`is expected to be a list. Received: ${describe(arg1)}`);
}
if (arg1.value.length === 0) {
return arg0;
}
return {
type: 'function',
value: {
fnType: 'partial',
isLeft: true,
applied: arg1.value,
targetFn: arg0,
},
};
}),
}],
]);
export const conditionalOperatorPrecedence = 4;
export const operators = new Set([...unaryOperators.keys(), ...binaryOperators.keys(), '?', ':', '...']);
|
kink/kat
|
src/wtcd/operators.ts
|
TypeScript
|
unknown
| 16,274 |
import * as MDI from 'markdown-it';
import { RuntimeValueType } from './Interpreter';
import { BinaryOperator, binaryOperators, conditionalOperatorPrecedence, UnaryOperator, unaryOperators } from './operators';
import { SimpleIdGenerator } from './SimpleIdGenerator';
import { stdFunctions } from './std';
import { Token, TokenStream } from './TokenStream';
import {
BinaryExpression,
BlockExpression,
BooleanLiteral,
BreakStatement,
ChoiceExpression,
ConditionalExpression,
ContinueStatement,
DeclarationStatement,
ExitAction,
Expression,
ExpressionStatement,
FunctionArgument,
FunctionExpression,
GotoAction,
IfExpression,
ListExpression,
NullLiteral,
NumberLiteral,
OneVariableDeclaration,
OptionalLocationInfo,
RegisterName,
ReturnStatement,
Section,
SelectionAction,
SetBreakStatement,
SetReturnStatement,
SetYieldStatement,
SingleSectionContent,
SpreadExpression,
Statement,
StringLiteral,
SwitchCase,
SwitchExpression,
TagExpression,
UnaryExpression,
VariableReference,
VariableType,
WhileExpression,
WTCDParseResult,
WTCDRoot,
YieldStatement,
} from './types';
import { WTCDError } from './WTCDError';
const CURRENT_MAJOR_VERSION = 1;
const CURRENT_MINOR_VERSION = 3;
const CURRENT_VERSION_STR = CURRENT_MAJOR_VERSION + '.' + CURRENT_MINOR_VERSION;
const variableTypes = [
'null',
'number',
'boolean',
'string',
'action',
'choice',
'selection',
'list',
'function',
];
// V1.1 removed selection type and combined it into action
function backwardsCompTypeTransformer(
variableType: RuntimeValueType | 'selection',
): RuntimeValueType {
if (variableType === 'selection') {
return 'action';
} else {
return variableType;
}
}
export interface SimpleLogger {
info(msg: string): void;
error(msg: string): void;
warn(msg: string): void;
}
/**
* Represents a single lexical scope. Managed by LexicalScopeProvide.
*/
class LexicalScope {
private declaredVariables: Set<string> = new Set();
private registers: Set<RegisterName> = new Set();
private onVariableReferenceNotFoundTriggers: Array<(variableName: string) => void> = [];
/** Whether this lexical scope contains the given variable */
public hasVariable(variableName: string) {
const result = this.declaredVariables.has(variableName);
if (!result) {
this.onVariableReferenceNotFoundTriggers.forEach(trigger => trigger(variableName));
}
return result;
}
/** Add a variable to this lexical scope */
public addVariable(variableName: string) {
this.declaredVariables.add(variableName);
}
/** Whether this lexical scope contains the given register */
public hasRegister(registerName: RegisterName) {
return this.registers.has(registerName);
}
/** Add a register to this lexical scope */
public addRegister(registerName: RegisterName) {
this.registers.add(registerName);
}
public addOnVariableReferenceNotFoundTrigger(trigger: (variableName: string) => void) {
this.onVariableReferenceNotFoundTriggers.push(trigger);
}
}
/**
* Provide lexical context for the parser.
* Mainly used to resolve lexical scope each variable reference uses.
*/
class LexicalScopeProvider {
private scopes: Array<LexicalScope> = [];
public constructor() {
this.enterScope(); // Std scope
stdFunctions.forEach(
stdFunction => this.addVariableToCurrentScope(stdFunction.name),
);
this.enterScope(); // Global scope
}
private getCurrentScope() {
return this.scopes[this.scopes.length - 1];
}
public enterScope() {
this.scopes.push(new LexicalScope());
}
public exitScope() {
this.scopes.pop();
}
public currentScopeHasVariable(variableName: string) {
return this.getCurrentScope().hasVariable(variableName);
}
public addVariableToCurrentScope(variableName: string) {
this.getCurrentScope().addVariable(variableName);
}
/**
* Add a callback function when a variable lookup is crossing the boundary of
* this scope.
*
* This is currently used to detect variables that require capture in a
* closure.
*
* @param trigger Callback
*/
public addOnVariableReferenceNotFoundTriggerToCurrentScope(trigger: (variableName: string) => void) {
this.getCurrentScope().addOnVariableReferenceNotFoundTrigger(trigger);
}
public hasVariableReference(variableName: string): boolean {
// Use a manual for loop instead of Array.prototype.some to ensure access order
for (let i = this.scopes.length - 1; i >= 0; i--) {
if (this.scopes[i].hasVariable(variableName)) {
return true;
}
}
return false;
}
public addRegisterToCurrentScope(registerName: RegisterName) {
this.getCurrentScope().addRegister(registerName);
}
public hasRegister(registerName: RegisterName) {
return this.scopes.some(scope => scope.hasRegister(registerName));
}
}
class LogicParser {
private tokenStream: TokenStream;
private lexicalScopeProvider = new LexicalScopeProvider();
private initStatements: Array<Statement> = [];
private postChecks: Array<() => void | never> = [];
private sections: Array<Section> = [];
private rootDeclarations: Set<string> = new Set();
public constructor(
source: string,
private readonly logger: SimpleLogger,
private readonly sourceMap: boolean,
) {
this.tokenStream = new TokenStream(source);
}
private attachLocationInfo<T extends OptionalLocationInfo>(token: OptionalLocationInfo | undefined, target: T) {
if (this.sourceMap) {
if (token === undefined) {
return this.tokenStream.throwUnexpectedNext();
}
target.line = token.line;
target.column = token.column;
}
return target;
}
private parseVariableType(): VariableType {
if (!this.tokenStream.isNext('keyword', variableTypes)) {
return null;
}
const types: Array<RuntimeValueType> = [];
do {
types.push(backwardsCompTypeTransformer(
this.tokenStream.next().content as RuntimeValueType,
));
} while (this.tokenStream.isNext('keyword', variableTypes));
return types;
}
private parseChoice() {
const choiceToken = this.tokenStream.assertAndSkipNext('keyword', 'choice');
const text = this.parseExpression();
const action = this.parseExpression();
return this.attachLocationInfo<ChoiceExpression>(choiceToken, {
type: 'choiceExpression',
text,
action,
});
}
private parseSectionName: () => string = () => {
const targetToken = this.tokenStream.assertAndSkipNext('identifier');
this.postChecks.push(() => {
if (!this.sections.some(section => section.name === targetToken.content)) {
throw WTCDError.atLocation(targetToken, `Unknown section "${targetToken.content}"`);
}
});
return targetToken.content;
}
private parseGotoAction(): GotoAction {
const gotoToken = this.tokenStream.assertAndSkipNext('keyword', 'goto');
return this.attachLocationInfo<GotoAction>(gotoToken, {
type: 'gotoAction',
sections: this.parseListOrSingleElement(
this.parseSectionName,
// Allow zero elements because we allow actions like goto []
false,
),
});
}
private parseList() {
const leftBracket = this.tokenStream.assertAndSkipNext('punctuation', '[');
const elements: Array<Expression | SpreadExpression> = [];
while (!this.tokenStream.isNext('punctuation', ']')) {
if (this.tokenStream.isNext('operator', '...')) {
elements.push(this.attachLocationInfo<SpreadExpression>(
this.tokenStream.next(), {
type: 'spread',
expression: this.parseExpression(),
},
));
} else {
elements.push(this.parseExpression());
}
}
this.tokenStream.assertAndSkipNext('punctuation', ']');
return this.attachLocationInfo<ListExpression>(leftBracket, {
type: 'list',
elements,
});
}
private parseFunctionCore(isFull: boolean): FunctionExpression {
const functionArguments: Array<FunctionArgument> = [];
this.lexicalScopeProvider.enterScope();
this.lexicalScopeProvider.addRegisterToCurrentScope('return');
const capturesSet: Set<string> = new Set();
this.lexicalScopeProvider
.addOnVariableReferenceNotFoundTriggerToCurrentScope(
variableName => capturesSet.add(variableName),
);
let restArgName: string | null = null;
let expression: null | Expression = null;
// If is full, parameter list is mandatory
if (isFull || this.tokenStream.isNext('punctuation', '[')) {
// Function switch
if (this.tokenStream.isNext('keyword', 'switch')) {
const switchToken = this.tokenStream.assertAndSkipNext(
'keyword',
'switch',
);
functionArguments.push(this.attachLocationInfo<FunctionArgument>(
switchToken, {
type: null,
name: '$switch',
defaultValue: null,
},
));
expression = this.parseSwitchCore(
switchToken,
this.attachLocationInfo<VariableReference>(switchToken, {
type: 'variableReference',
variableName: '$switch',
}),
);
} else {
this.tokenStream.assertAndSkipNext('punctuation', '[');
const usedArgumentNames: Set<string> = new Set();
while (!this.tokenStream.isNext('punctuation', ']')) {
if (this.tokenStream.isNext('operator', '...')) {
this.tokenStream.next(); // Skip over ...
// Rest arguments
const restArgToken = this.tokenStream.assertAndSkipNext('identifier');
if (usedArgumentNames.has(restArgToken.content)) {
throw WTCDError.atLocation(restArgToken, `Argument ` +
`"${restArgToken.content}" already existed.`);
}
restArgName = restArgToken.content;
break; // Stop reading any more arguments
}
const argType = this.parseVariableType();
const argNameToken = this.tokenStream.assertAndSkipNext('identifier');
if (usedArgumentNames.has(argNameToken.content)) {
throw WTCDError.atLocation(argNameToken, `Argument ` +
`"${argNameToken.content}" already existed.`);
}
usedArgumentNames.add(argNameToken.content);
let defaultValue: null | Expression = null;
if (this.tokenStream.isNext('operator', '=')) {
this.tokenStream.next();
defaultValue = this.parseExpression();
}
functionArguments.push(this.attachLocationInfo<FunctionArgument>(
argNameToken, {
type: argType,
name: argNameToken.content,
defaultValue,
},
));
}
this.tokenStream.assertAndSkipNext('punctuation', ']');
}
}
functionArguments.forEach(
argument => this.lexicalScopeProvider.addVariableToCurrentScope(
argument.name,
),
);
if (restArgName !== null) {
this.lexicalScopeProvider.addVariableToCurrentScope(restArgName);
}
if (expression === null) {
expression = this.parseExpression();
}
this.lexicalScopeProvider.exitScope();
return {
type: 'function',
arguments: functionArguments,
restArgName,
captures: Array.from(capturesSet),
expression,
};
}
// function [...] ...
private parseFullFunctionExpression() {
return this.attachLocationInfo<FunctionExpression>(
this.tokenStream.assertAndSkipNext('keyword', 'function'),
this.parseFunctionCore(true),
);
}
private parseShortFunctionExpression() {
return this.attachLocationInfo<FunctionExpression>(
this.tokenStream.assertAndSkipNext('punctuation', '$'),
this.parseFunctionCore(false),
);
}
private parseSwitchCore(switchToken: Token, expression: Expression) {
this.tokenStream.assertAndSkipNext('punctuation', '[');
const cases: Array<SwitchCase> = [];
let defaultCase: Expression | null = null;
while (!this.tokenStream.isNext('punctuation', ']')) {
const matches = this.parseExpression();
if (this.tokenStream.isNext('punctuation', ']')) {
// Default case
defaultCase = matches;
break;
}
const returns = this.parseExpression();
cases.push({ matches, returns });
}
this.tokenStream.assertAndSkipNext('punctuation', ']');
return this.attachLocationInfo<SwitchExpression>(switchToken, {
type: 'switch',
expression,
cases,
defaultCase,
});
}
private parseSwitchExpression() {
const switchToken = this.tokenStream.assertAndSkipNext('keyword', 'switch');
const expression = this.parseExpression();
return this.parseSwitchCore(switchToken, expression);
}
private parseWhileExpression(): WhileExpression {
const mainToken = this.tokenStream.peek();
this.lexicalScopeProvider.enterScope();
this.lexicalScopeProvider.addRegisterToCurrentScope('break');
let preExpr: Expression | null = null;
if (this.tokenStream.isNext('keyword', 'do')) {
this.tokenStream.next();
preExpr = this.parseExpression();
}
this.tokenStream.assertAndSkipNext('keyword', 'while');
const condition = this.parseExpression();
let postExpr: Expression | null = null;
if (preExpr === null) {
postExpr = this.parseExpression();
} else if (this.tokenStream.isNext('keyword', 'then')) {
this.tokenStream.next();
postExpr = this.parseExpression();
}
this.lexicalScopeProvider.exitScope();
return this.attachLocationInfo<WhileExpression>(mainToken, {
type: 'while',
preExpr,
condition,
postExpr,
});
}
private parseIfExpression(): IfExpression {
const ifToken = this.tokenStream.assertAndSkipNext('keyword', 'if');
const condition = this.parseExpression();
const then = this.parseExpression();
let otherwise: Expression | null = null;
if (this.tokenStream.isNext('keyword', 'else')) {
this.tokenStream.next();
otherwise = this.parseExpression();
}
return this.attachLocationInfo<IfExpression>(ifToken, {
type: 'if',
condition,
then,
otherwise,
});
}
/**
* Try to parse an atom node, which includes:
* - number literals
* - string literals
* - boolean literals
* - nulls
* - selection
* - choices
* - goto actions
* - exit actions
* - groups
* - lists
* - functions
* - variables
* - switches
* - while loops
* - if
* - tags
* - block expressions
* - unary expressions
*
* @param softFail If true, when parsing failed, null is returned instead of
* throwing error.
*/
private parseAtom(): Expression;
private parseAtom(softFail: true): Expression | null;
private parseAtom(softFail?: true): Expression | null {
// Number literal
if (this.tokenStream.isNext('number')) {
return this.attachLocationInfo<NumberLiteral>(this.tokenStream.peek(), {
type: 'numberLiteral',
value: Number(this.tokenStream.next().content),
});
}
// String literal
if (this.tokenStream.isNext('string')) {
return this.attachLocationInfo<StringLiteral>(this.tokenStream.peek(), {
type: 'stringLiteral',
value: this.tokenStream.next().content,
});
}
// Boolean literal
if (this.tokenStream.isNext('keyword', ['true', 'false'])) {
return this.attachLocationInfo<BooleanLiteral>(this.tokenStream.peek(), {
type: 'booleanLiteral',
value: this.tokenStream.next().content === 'true',
});
}
// Null
if (this.tokenStream.isNext('keyword', 'null')) {
return this.attachLocationInfo<NullLiteral>(this.tokenStream.next(), {
type: 'nullLiteral',
});
}
// Selection
if (this.tokenStream.isNext('keyword', 'selection')) {
return this.attachLocationInfo<SelectionAction>(this.tokenStream.next(), {
type: 'selection',
choices: this.parseExpression(),
});
}
// Choice
if (this.tokenStream.isNext('keyword', 'choice')) {
return this.parseChoice();
}
// Goto actions
if (this.tokenStream.isNext('keyword', 'goto')) {
return this.parseGotoAction();
}
// Exit actions
if (this.tokenStream.isNext('keyword', 'exit')) {
return this.attachLocationInfo<ExitAction>(this.tokenStream.next(), {
type: 'exitAction',
});
}
// Group
if (this.tokenStream.isNext('punctuation', '(')) {
this.tokenStream.next();
const result = this.parseExpression();
this.tokenStream.assertAndSkipNext('punctuation', ')');
return result;
}
// List
if (this.tokenStream.isNext('punctuation', '[')) {
return this.parseList();
}
// Function
if (this.tokenStream.isNext('keyword', 'function')) {
return this.parseFullFunctionExpression();
}
// Short function
if (this.tokenStream.isNext('punctuation', '$')) {
return this.parseShortFunctionExpression();
}
// Switch
if (this.tokenStream.isNext('keyword', 'switch')) {
return this.parseSwitchExpression();
}
// While
if (this.tokenStream.isNext('keyword', ['while', 'do'])) {
return this.parseWhileExpression();
}
// If
if (this.tokenStream.isNext('keyword', 'if')) {
return this.parseIfExpression();
}
// Tag
if (this.tokenStream.isNext('tag')) {
return this.attachLocationInfo<TagExpression>(
this.tokenStream.peek(),
{ type: 'tag', name: this.tokenStream.next().content },
);
}
// Block expression
if (this.tokenStream.isNext('punctuation', '{')) {
return this.parseBlockExpression();
}
// Variable
if (this.tokenStream.isNext('identifier')) {
const identifierToken = this.tokenStream.next();
if (!this.lexicalScopeProvider.hasVariableReference(identifierToken.content)) {
throw WTCDError.atLocation(
identifierToken,
`Cannot locate lexical scope for variable "${identifierToken.content}"`,
);
}
return this.attachLocationInfo<VariableReference>(identifierToken, {
type: 'variableReference',
variableName: identifierToken.content,
});
}
// Unary
if (this.tokenStream.isNext('operator')) {
const operatorToken = this.tokenStream.next();
if (!unaryOperators.has(operatorToken.content)) {
throw WTCDError.atLocation(
operatorToken,
`Invalid unary operator: ${operatorToken.content}`,
);
}
return this.attachLocationInfo<UnaryExpression>(operatorToken, {
type: 'unaryExpression',
operator: operatorToken.content as UnaryOperator,
arg: this.parseExpression(
this.parseAtom(),
unaryOperators.get(operatorToken.content)!.precedence,
),
});
}
if (softFail === true) {
return null;
} else {
return this.tokenStream.throwUnexpectedNext('atom');
}
}
private parseBlockExpression() {
const firstBraceToken = this.tokenStream.assertAndSkipNext('punctuation', '{');
this.lexicalScopeProvider.enterScope();
this.lexicalScopeProvider.addRegisterToCurrentScope('yield');
const expressions: Array<Statement> = [];
while (!this.tokenStream.isNext('punctuation', '}')) {
expressions.push(this.parseStatement());
}
this.lexicalScopeProvider.exitScope();
this.tokenStream.assertAndSkipNext('punctuation', '}');
return this.attachLocationInfo<BlockExpression>(firstBraceToken, {
type: 'block',
statements: expressions,
});
}
private assertHasRegister(registerName: RegisterName, token: Token) {
if (!this.lexicalScopeProvider.hasRegister(registerName)) {
throw WTCDError.atLocation(
token,
`Cannot locate lexical scope for ${registerName} register`,
);
}
}
private parseYieldOrSetYieldExpression(): YieldStatement | SetYieldStatement {
const yieldToken = this.tokenStream.assertAndSkipNext('keyword', 'yield');
this.assertHasRegister('yield', yieldToken);
if (this.tokenStream.isNext('operator', '=')) {
// Set yield
this.tokenStream.next();
return this.attachLocationInfo<SetYieldStatement>(yieldToken, {
type: 'setYield',
value: this.parseExpression(),
});
} else {
// Yield
return this.attachLocationInfo<YieldStatement>(yieldToken, {
type: 'yield',
value: this.parseExpressionImpliedNull(yieldToken),
});
}
}
private parseReturnOrSetReturnStatement(): ReturnStatement | SetReturnStatement {
const returnToken = this.tokenStream.assertAndSkipNext('keyword', 'return');
this.assertHasRegister('return', returnToken);
if (this.tokenStream.isNext('operator', '=')) {
// Set return
this.tokenStream.next();
return this.attachLocationInfo<SetReturnStatement>(returnToken, {
type: 'setReturn',
value: this.parseExpression(),
});
} else {
// Return
return this.attachLocationInfo<ReturnStatement>(returnToken, {
type: 'return',
value: this.parseExpressionImpliedNull(returnToken),
});
}
}
private parseBreakOrSetBreakStatement(): BreakStatement | SetBreakStatement {
const breakToken = this.tokenStream.assertAndSkipNext('keyword', 'break');
this.assertHasRegister('break', breakToken);
if (this.tokenStream.isNext('operator', '=')) {
// Set return
this.tokenStream.next();
return this.attachLocationInfo<SetBreakStatement>(breakToken, {
type: 'setBreak',
value: this.parseExpression(),
});
} else {
// Return
return this.attachLocationInfo<BreakStatement>(breakToken, {
type: 'break',
value: this.parseExpressionImpliedNull(breakToken),
});
}
}
private parseContinueStatement(): ContinueStatement {
return this.attachLocationInfo<ContinueStatement>(this.tokenStream.next(), {
type: 'continue',
});
}
private parseExpressionImpliedNull(location: OptionalLocationInfo) {
const atom = this.parseAtom(true);
if (atom === null) {
return this.attachLocationInfo<NullLiteral>(location, { type: 'nullLiteral' });
}
return this.parseExpression(atom, 0);
}
/**
* - If next token is not an operator, return left as is.
* - If next operator's precedence is smaller than or equal to the precedence
* threshold, return left as is. (Because in this case, we want to left
* someone on the left wrap us.)
* - Otherwise, for binary operators call #maybeInfixExpression with next
* element as left and new operator's precedence as the threshold. (This is
* to bind everything that binds tighter (higher precedence) than this
* operator together.) Using this and current precedence threshold, call
* #maybeInfixExpression again. (This is to bind everything that reaches the
* threshold together.)
* - For conditional operator (?), parse a expression (between "?" and ":"),
* then read in ":". Last, do the same thing as with the binary case.
* @param left expression on the left of next operator
* @param precedenceMin minimum (exclusive) precedence required in order
* to bind with left
* @param precedenceMax minimum (inclusive) precedence required in order
* to bind with left
*/
private parseExpression: (
left?: Expression,
precedenceMin?: number,
precedenceMax?: number,
) => Expression = (
left = this.parseAtom(),
precedenceMin = 0,
precedenceMax = Infinity,
) => {
if (!this.tokenStream.isNext('operator')) {
return left;
}
const operatorToken = this.tokenStream.peek()!;
const isConditional = operatorToken.content === '?';
if (!isConditional && !binaryOperators.has(operatorToken.content)) {
return left;
}
const nextPrecedence = isConditional
? conditionalOperatorPrecedence
: binaryOperators.get(operatorToken.content)!.precedence;
if (nextPrecedence <= precedenceMin || (isConditional && nextPrecedence > precedenceMax)) {
return left;
}
this.tokenStream.next(); // Read in operator
if (isConditional) {
// Implementation here might contain bug. It works for all my cases though.
const then = this.parseExpression();
this.tokenStream.assertAndSkipNext('operator', ':');
const otherwise = this.parseExpression(this.parseAtom(), precedenceMin, nextPrecedence);
const conditional = this.attachLocationInfo<ConditionalExpression>(operatorToken, {
type: 'conditionalExpression',
condition: left,
then,
otherwise,
});
return this.parseExpression(conditional, precedenceMin, precedenceMax);
} else {
const right = this.parseExpression(this.parseAtom(), nextPrecedence, precedenceMax);
const binary = this.attachLocationInfo<BinaryExpression>(operatorToken, {
type: 'binaryExpression',
operator: operatorToken.content as BinaryOperator,
arg0: left,
arg1: right,
});
return this.parseExpression(binary, precedenceMin, precedenceMax);
}
}
/**
* Parse a single expression, which includes:
* - unary expressions
* - declare expressions
* - infix expressions (binary and conditional)
*/
private parseStatement: () => Statement = () => {
if (this.tokenStream.isNext('keyword', 'declare')) {
return this.parseDeclaration();
} else if (this.tokenStream.isNext('keyword', 'return')) {
return this.parseReturnOrSetReturnStatement();
} else if (this.tokenStream.isNext('keyword', 'yield')) {
return this.parseYieldOrSetYieldExpression();
} else if (this.tokenStream.isNext('keyword', 'break')) {
return this.parseBreakOrSetBreakStatement();
} else if (this.tokenStream.isNext('keyword', 'continue')) {
return this.parseContinueStatement();
} else {
return this.attachLocationInfo<ExpressionStatement>(this.tokenStream.peek(), {
type: 'expression',
expression: this.parseExpression(),
});
}
}
private parseOneDeclaration: () => OneVariableDeclaration = () => {
const type = this.parseVariableType();
const variableNameToken = this.tokenStream.assertAndSkipNext('identifier');
let initialValue: Expression | null = null;
if (this.tokenStream.isNext('operator', '=')) {
// Explicit initialization (number a = 123)
this.tokenStream.next();
initialValue = this.parseExpression();
} else if (
(
(this.tokenStream.isNext('punctuation', '[')) ||
(this.tokenStream.isNext('keyword', 'switch'))
) &&
(type !== null) &&
(type.length === 1) &&
(type[0] === 'function')
) {
// Simplified function declaration (declare function test[ ... ] ...)
initialValue = this.attachLocationInfo<FunctionExpression>(
variableNameToken,
this.parseFunctionCore(true),
);
}
if (this.lexicalScopeProvider.currentScopeHasVariable(variableNameToken.content)) {
throw WTCDError.atLocation(
variableNameToken,
`Variable "${variableNameToken.content}" has already been declared within the same lexical scope`,
);
}
this.lexicalScopeProvider.addVariableToCurrentScope(variableNameToken.content);
return this.attachLocationInfo<OneVariableDeclaration>(variableNameToken, {
variableName: variableNameToken.content,
variableType: type,
initialValue,
});
}
private parseListOrSingleElement<T>(parseOneFn: () => T, atLestOne: boolean = true): Array<T> {
if (this.tokenStream.isNext('punctuation', '[')) {
const results: Array<T> = [];
this.tokenStream.next(); // [
while (!this.tokenStream.isNext('punctuation', ']')) {
results.push(parseOneFn());
}
if (atLestOne && results.length === 0) {
return this.tokenStream.throwUnexpectedNext('at least one element');
}
this.tokenStream.next(); // ]
return results;
} else {
return [parseOneFn()];
}
}
private parseDeclaration() {
const declareToken = this.tokenStream.assertAndSkipNext('keyword', 'declare');
const declarations = this.parseListOrSingleElement(this.parseOneDeclaration);
return this.attachLocationInfo<DeclarationStatement>(declareToken, {
type: 'declaration',
declarations,
});
}
private parseSection() {
const sectionToken = this.tokenStream.assertAndSkipNext('keyword', 'section');
const nameToken = this.tokenStream.assertAndSkipNext('identifier');
if (this.sections.some(section => section.name === nameToken.content)) {
throw WTCDError.atLocation(nameToken, `Cannot redefine section "${nameToken.content}"`);
}
let executes: Expression | null = null;
if (!this.tokenStream.isNext('keyword', 'then')) {
executes = this.parseExpression();
}
this.tokenStream.assertAndSkipNext('keyword', 'then');
const then = this.parseExpression();
return this.attachLocationInfo<Section>(sectionToken, {
name: nameToken.content,
executes,
then,
content: [],
});
}
private parseRootBlock() {
this.tokenStream.assertNext('keyword', ['declare', 'section']);
if (this.tokenStream.isNext('keyword', 'declare')) {
const declarationStatement = this.parseDeclaration();
for (const declaration of declarationStatement.declarations) {
this.rootDeclarations.add(declaration.variableName);
}
this.initStatements.push(declarationStatement);
} else if (this.tokenStream.isNext('keyword', 'section')) {
this.sections.push(this.parseSection());
}
}
public hasRootDeclaration(variableName: string) {
return this.rootDeclarations.has(variableName);
}
/**
* Read the WTCD version declaration and verify version
* Give warning when needed.
*/
private parseVersion() {
this.tokenStream.assertAndSkipNext('identifier', 'WTCD');
const versionToken = this.tokenStream.assertAndSkipNext('number');
const versionContent = versionToken.content;
const split = versionContent.split('.');
if (split.length !== 2) {
throw WTCDError.atLocation(versionToken, `Invalid WTCD version ${versionContent}`);
}
const majorVersion = Number(split[0]);
const minorVersion = Number(split[1]);
if (
(majorVersion > CURRENT_MAJOR_VERSION) ||
(majorVersion === CURRENT_MAJOR_VERSION && minorVersion > CURRENT_MINOR_VERSION)
) {
// If version stated is larger
this.logger.warn(`Document's WTCD version (${versionContent}) is newer than parser ` +
`version (${CURRENT_VERSION_STR}). New features might break parser.`);
} else if (majorVersion < CURRENT_MAJOR_VERSION) {
this.logger.warn(`Document's WTCD version (${versionContent}) is a least one major ` +
`version before parser's (${CURRENT_VERSION_STR}). Breaking changes introduced might break ` +
`parser.`);
}
}
public parse() {
const logger = this.logger;
logger.info('Parsing logic section...');
this.parseVersion();
while (!this.tokenStream.eof()) {
this.parseRootBlock();
}
logger.info('Run post checks...');
this.postChecks.forEach(postCheck => postCheck());
return {
initStatements: this.initStatements,
sections: this.sections,
};
}
}
function identity<T>(input: T) {
return input;
}
/**
* Parse the given WTCD document.
*/
export function parse({ source, mdi, sourceMap = false, logger = console, markdownPreProcessor = identity, htmlPostProcessor = identity }: {
source: string;
mdi: MDI;
sourceMap?: boolean;
logger?: SimpleLogger;
markdownPreProcessor?: (markdown: string) => string;
htmlPostProcessor?: (html: string) => string;
}): WTCDParseResult {
try {
// Parse sections and extract the logic part of this WTCD document
/** Regex used to extract section headers. */
const sectionRegex = /^---<<<\s+([a-zA-Z_][a-zA-Z_0-9]*)(?:@([0-9\-]+))?\s+>>>---$/gm;
/** Markdown source of each section */
const sectionMarkdowns: Array<string> = [];
/** Name of each section, excluding bounds */
const sectionNames: Array<string> = [];
/** Bounds of each section, not parsed. Undefined means unbounded. */
const sectionBounds: Array<string | undefined> = [];
/** End index of last section */
let lastIndex = 0;
/** Rolling regex result object */
let result: RegExpExecArray | null;
while ((result = sectionRegex.exec(source)) !== null) {
sectionMarkdowns.push(source.substring(lastIndex, result.index));
sectionNames.push(result[1]);
sectionBounds.push(result[2]);
lastIndex = sectionRegex.lastIndex;
}
// Push the remaining content to last section's markdown
sectionMarkdowns.push(source.substring(lastIndex));
const logicParser = new LogicParser(
sectionMarkdowns.shift()!,
logger,
sourceMap,
);
const wtcdRoot: WTCDRoot = logicParser.parse();
const sig = new SimpleIdGenerator();
sectionContentLoop:
for (let i = 0; i < sectionMarkdowns.length; i++) {
/** Markdown content of the section */
const sectionMarkdown = markdownPreProcessor(sectionMarkdowns[i]);
/** Name (without bound) of the section */
const sectionName = sectionNames[i];
/** Unparsed bounds of the section */
const sectionBound = sectionBounds[i];
const sectionFullName = (sectionBound === undefined)
? sectionName
: `${sectionName}@${sectionBound}`;
const variables: Array<{ elementClass: string, variableName: string }> = [];
const sectionHTML = mdi.render(sectionMarkdown);
/**
* HTML content of the section whose interpolated values are converted to
* spans with unique classes.
*/
const sectionParameterizedHTML = sectionHTML.replace(/<\$\s+([a-zA-Z_][a-zA-Z_0-9]*)\s+\$>/g, (_, variableName) => {
if (!logicParser.hasRootDeclaration(variableName)) {
throw WTCDError.atUnknown(`Cannot resolve variable reference "${variableName}" in section "${sectionFullName}"`);
}
const elementClass = 'wtcd-variable-' + sig.next();
variables.push({
elementClass,
variableName,
});
return `<span class="${elementClass}"></span>`;
});
// Parse bounds
let lowerBound: number | undefined;
let upperBound: number | undefined;
if (sectionBound !== undefined) {
if (sectionBound.includes('-')) {
const split = sectionBound.split('-');
lowerBound = split[0] === '' ? undefined : Number(split[0]);
upperBound = split[1] === '' ? undefined : Number(split[1]);
} else {
lowerBound = upperBound = Number(sectionBound);
}
}
const singleSectionContent: SingleSectionContent = {
html: htmlPostProcessor(sectionParameterizedHTML),
variables,
lowerBound,
upperBound,
};
for (const section of wtcdRoot.sections) {
if (section.name === sectionName) {
section.content.push(singleSectionContent);
continue sectionContentLoop;
}
}
// Currently, location data for content sections are not available
throw WTCDError.atUnknown(`Cannot find a logic declaration for ` +
`section content ${sectionFullName}`);
}
return {
error: false,
wtcdRoot,
};
} catch (error) {
return {
error: true,
message: (error as Error).message,
internalStack: (error as Error).stack!,
};
}
}
|
kink/kat
|
src/wtcd/parse.ts
|
TypeScript
|
unknown
| 35,990 |
import { NativeFunction } from '../types';
import { getMaybePooled } from '../constantsPool';
import { assertArgsLength, assertArgType, NativeFunctionError } from './utils';
import { ChainedCanvas } from '../ChainedCanvas';
import { InterpreterHandle } from '../Interpreter';
function obtainCanvas(interpreterHandle: InterpreterHandle, id: string) {
const canvas = interpreterHandle.canvases.get(id)!;
if (canvas === undefined) {
throw new NativeFunctionError(`Canvas with id="${id}" does not exist.`);
}
return canvas;
}
function assertIsHAlign(hAlign: string): asserts hAlign is CanvasTextAlign {
switch (hAlign) {
case 'left':
case 'center':
case 'right':
case 'start':
case 'end':
break;
default:
throw new NativeFunctionError(`Unknown text hAlign: ${hAlign}`);
}
}
function assertIsVAlign(vAlign: string): asserts vAlign is CanvasTextBaseline {
switch (vAlign) {
case 'top':
case 'hanging':
case 'middle':
case 'alphabetic':
case 'ideographic':
case 'bottom':
break;
default:
throw new NativeFunctionError(`Unknown text vAlign: ${vAlign}`);
}
}
export const canvasStdFunctions: Array<NativeFunction> = [
function canvasCreate(args, interpreterHandle) {
assertArgsLength(args, 3);
const id = assertArgType(args, 0, 'string');
const width = assertArgType(args, 1, 'number');
const height = assertArgType(args, 2, 'number');
if (interpreterHandle.canvases.has(id)) {
throw new NativeFunctionError(`Canvas with id="${id}" already exists`);
}
if (width % 1 !== 0) {
throw new NativeFunctionError(`Width (${width}) has to be an integer`);
}
if (width <= 0) {
throw new NativeFunctionError(`Width (${width}) must be positive`);
}
if (height % 1 !== 0) {
throw new NativeFunctionError(`Height (${height}) has to be an integer`);
}
if (height <= 0) {
throw new NativeFunctionError(`Height (${height}) must be positive`);
}
interpreterHandle.canvases.set(id, new ChainedCanvas(width, height));
return getMaybePooled('null', null);
},
function canvasOutput(args, interpreterHandle) {
const id = assertArgType(args, 0, 'string');
const canvas = obtainCanvas(interpreterHandle, id);
const $newCanvas = document.createElement('canvas');
$newCanvas.width = canvas.getWidth();
$newCanvas.height = canvas.getHeight();
$newCanvas.style.maxWidth = '100%';
interpreterHandle.featureProvider.drawLoadingCanvas($newCanvas);
interpreterHandle.pushContent($newCanvas);
canvas.onResolve(() => {
if (document.body.contains($newCanvas)) {
const ctx = $newCanvas.getContext('2d')!;
ctx.clearRect(0, 0, $newCanvas.width, $newCanvas.height);
ctx.drawImage(canvas.canvas, 0, 0);
}
});
return getMaybePooled('null', null);
},
function canvasClear(args, interpreterHandle) {
const id = assertArgType(args, 0, 'string');
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
canvas.ctx.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
});
return getMaybePooled('null', null);
},
function canvasPutImage(args, interpreterHandle) {
assertArgsLength(args, 4, 6);
const id = assertArgType(args, 0, 'string');
const path = assertArgType(args, 1, 'string');
const x = assertArgType(args, 2, 'number');
const y = assertArgType(args, 3, 'number');
const width = assertArgType(args, 4, 'number', -1);
const height = assertArgType(args, 5, 'number', -1);
if ((width < 0) !== (height < 0)) {
throw new NativeFunctionError('Width and height must be provided at ' +
'the same time.');
}
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
try {
const image = await interpreterHandle.featureProvider.loadImage(path);
if (width < 0) {
canvas.ctx.drawImage(image, x, y);
} else {
canvas.ctx.drawImage(image, x, y, width, height);
}
} catch (error) {
console.error(`WTCD failed to load image with path="${path}".`, error);
}
});
return getMaybePooled('null', null);
},
function canvasPutImagePart(args, interpreterHandle) {
assertArgsLength(args, 8, 10);
const id = assertArgType(args, 0, 'string');
const path = assertArgType(args, 1, 'string');
const sourceX = assertArgType(args, 2, 'number');
const sourceY = assertArgType(args, 3, 'number');
const sourceWidth = assertArgType(args, 4, 'number');
const sourceHeight = assertArgType(args, 5, 'number');
const destX = assertArgType(args, 6, 'number');
const destY = assertArgType(args, 7, 'number');
const destWidth = assertArgType(args, 8, 'number', -1);
const destHeight = assertArgType(args, 9, 'number', -1);
if ((destWidth < 0) !== (destHeight < 0)) {
throw new NativeFunctionError('destWidth and destHeight must be ' +
'provided at the same time.');
}
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
try {
const image = await interpreterHandle.featureProvider.loadImage(path);
if (destWidth < 0) {
canvas.ctx.drawImage(
image,
sourceX, sourceY,
sourceWidth, sourceHeight,
destX, destY,
sourceWidth, sourceHeight
);
} else {
canvas.ctx.drawImage(
image,
sourceX, sourceY,
sourceWidth, sourceHeight,
destX, destY,
destWidth, destHeight
);
}
} catch (error) {
console.error(`WTCD failed to load image with path="${path}".`, error);
}
});
return getMaybePooled('null', null);
},
function canvasSetFont(args, interpreterHandle) {
assertArgsLength(args, 3);
const id = assertArgType(args, 0, 'string');
const size = assertArgType(args, 1, 'number');
const fontIdentifier = assertArgType(args, 2, 'string');
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
try {
const fontName = await interpreterHandle.featureProvider
.loadFont(fontIdentifier);
canvas.ctx.font = `${size}px ${fontName}`;
} catch (error) {
console.error(`WTCD failed to load font with ` +
`identifier="${fontIdentifier}".`, error);
}
});
return getMaybePooled('null', null);
},
function canvasSetFillStyle(args, interpreterHandle) {
assertArgsLength(args, 2);
const id = assertArgType(args, 0, 'string');
const color = assertArgType(args, 1, 'string');
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
canvas.ctx.fillStyle = color;
});
return getMaybePooled('null', null);
},
function canvasFillText(args, interpreterHandle) {
assertArgsLength(args, 4, 6);
const id = assertArgType(args, 0, 'string');
const text = assertArgType(args, 1, 'string');
const x = assertArgType(args, 2, 'number');
const y = assertArgType(args, 3, 'number');
const hAlign = assertArgType(args, 4, 'string', 'start');
const vAlign = assertArgType(args, 5, 'string', 'alphabetic');
const canvas = obtainCanvas(interpreterHandle, id);
assertIsHAlign(hAlign);
assertIsVAlign(vAlign);
canvas.updatePromise(async () => {
const ctx = canvas.ctx;
ctx.textAlign = hAlign;
ctx.textBaseline = vAlign;
ctx.fillText(text, x, y);
});
return getMaybePooled('null', null);
},
function canvasFillRect(args, interpreterHandle) {
assertArgsLength(args, 5);
const id = assertArgType(args, 0, 'string');
const x = assertArgType(args, 1, 'number');
const y = assertArgType(args, 2, 'number');
const width = assertArgType(args, 3, 'number');
const height = assertArgType(args, 4, 'number');
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
canvas.ctx.fillRect(x, y, width, height);
});
return getMaybePooled('null', null);
},
function canvasSetStrokeStyle(args, interpreterHandle) {
assertArgsLength(args, 2);
const id = assertArgType(args, 0, 'string');
const color = assertArgType(args, 1, 'string');
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
canvas.ctx.strokeStyle = color;
});
return getMaybePooled('null', null);
},
function canvasSetLineWidth(args, interpreterHandle) {
assertArgsLength(args, 2);
const id = assertArgType(args, 0, 'string');
const lineWidth = assertArgType(args, 1, 'number');
const canvas = obtainCanvas(interpreterHandle, id);
canvas.updatePromise(async () => {
canvas.ctx.lineWidth = lineWidth;
});
return getMaybePooled('null', null);
},
function canvasStrokeText(args, interpreterHandle) {
assertArgsLength(args, 4, 6);
const id = assertArgType(args, 0, 'string');
const text = assertArgType(args, 1, 'string');
const x = assertArgType(args, 2, 'number');
const y = assertArgType(args, 3, 'number');
const hAlign = assertArgType(args, 4, 'string', 'start');
const vAlign = assertArgType(args, 5, 'string', 'alphabetic');
const canvas = obtainCanvas(interpreterHandle, id);
assertIsHAlign(hAlign);
assertIsVAlign(vAlign);
canvas.updatePromise(async () => {
const ctx = canvas.ctx;
ctx.textAlign = hAlign;
ctx.textBaseline = vAlign;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeText(text, x, y);
});
return getMaybePooled('null', null);
},
];
|
kink/kat
|
src/wtcd/std/canvas.ts
|
TypeScript
|
unknown
| 9,780 |
import { getMaybePooled } from '../constantsPool';
import { describe } from '../Interpreter';
import { NativeFunction } from '../types';
import { assertArgsLength, assertArgType, NativeFunctionError } from './utils';
export const contentStdFunctions: Array<NativeFunction> = [
function contentAddParagraph(args, interpreterHandle) {
assertArgsLength(args, 1);
const $paragraph = document.createElement('p');
$paragraph.innerText = assertArgType(args, 0, 'string');
interpreterHandle.pushContent($paragraph);
return getMaybePooled('null', null);
},
function contentAddImage(args, interpreterHandle) {
assertArgsLength(args, 1);
const $image = document.createElement('img');
$image.src = assertArgType(args, 0, 'string');
interpreterHandle.pushContent($image);
return getMaybePooled('null', null);
},
function contentAddUnorderedList(args, interpreterHandle) {
const $container = document.createElement('ul');
for (let i = 0; i < args.length; i++) {
const content = assertArgType(args, i, 'string');
const $li = document.createElement('li');
$li.innerText = content;
$container.appendChild($li);
}
interpreterHandle.pushContent($container);
return getMaybePooled('null', null);
},
function contentAddOrderedList(args, interpreterHandle) {
const $container = document.createElement('ol');
for (let i = 0; i < args.length; i++) {
const content = assertArgType(args, i, 'string');
const $li = document.createElement('li');
$li.innerText = content;
$container.appendChild($li);
}
interpreterHandle.pushContent($container);
return getMaybePooled('null', null);
},
function contentAddHeader(args, interpreterHandle) {
assertArgsLength(args, 1, 2);
const level = assertArgType(args, 1, 'number', 1);
if (![1, 2, 3, 4, 5, 6].includes(level)) {
throw new NativeFunctionError(`There is no header with level ${level}`);
}
const $header = document.createElement('h' + level);
$header.innerText = assertArgType(args, 0, 'string');
interpreterHandle.pushContent($header);
return getMaybePooled('null', null);
},
function contentAddTable(args, interpreterHandle) {
assertArgsLength(args, 1, Infinity);
const rows = args
.map((_, index) => assertArgType(args, index, 'list'));
rows.forEach((row, rowIndex) => {
if (row.length !== rows[0].length) {
throw new NativeFunctionError(`Row with index = ${rowIndex} has ` +
`incorrect number of items. Expecting ${rows[0].length}, received ` +
`${row.length}`);
}
row.forEach((item, columnIndex) => {
if (item.type !== 'string') {
throw new NativeFunctionError(`Item in row with index = ${rowIndex}` +
`, and column with index = ${columnIndex} is expected to be a ` +
`string, received: ${describe(item)}`);
}
});
});
const $table = document.createElement('table');
const $thead = document.createElement('thead');
const $headTr = document.createElement('tr');
const headerRow = rows.shift()!;
headerRow.forEach(content => {
const $th = document.createElement('th');
$th.innerText = content.value as string;
$headTr.appendChild($th);
});
$thead.appendChild($headTr);
$table.appendChild($thead);
const $tbody = document.createElement('tbody');
rows.forEach(row => {
const $tr = document.createElement('tr');
row.forEach(content => {
const $td = document.createElement('td');
$td.innerText = content.value as string;
$tr.appendChild($td);
});
$tbody.appendChild($tr);
});
$table.appendChild($tbody);
interpreterHandle.pushContent($table);
return getMaybePooled('null', null);
},
function contentAddHorizontalRule(args, interpreterHandle) {
assertArgsLength(args, 0);
interpreterHandle.pushContent(document.createElement('hr'));
return getMaybePooled('null', null);
},
];
|
kink/kat
|
src/wtcd/std/content.ts
|
TypeScript
|
unknown
| 4,045 |
import { getMaybePooled } from '../constantsPool';
import { describe } from '../Interpreter';
import { FunctionInvocationError, invokeFunctionRaw } from '../invokeFunction';
import { NativeFunction } from '../types';
import { WTCDError } from '../WTCDError';
import { assertArgsLength, assertArgType, NativeFunctionError } from './utils';
export const debugStdFunctions: Array<NativeFunction> = [
function print(args) {
console.group('WTCD print call');
args.forEach((arg, index) => console.info(`[${index}] ${describe(arg)}`));
console.groupEnd();
return getMaybePooled('null', null);
},
function assert(args) {
assertArgsLength(args, 1);
const result = assertArgType(args, 0, 'boolean');
if (!result) {
throw new NativeFunctionError('Assertion failed');
}
return getMaybePooled('null', null);
},
function assertError(args, interpreterHandle) {
assertArgsLength(args, 1);
const fn = assertArgType(args, 0, 'function');
try {
invokeFunctionRaw(fn, [], interpreterHandle);
} catch (error) {
if (
(error instanceof WTCDError) ||
(error instanceof FunctionInvocationError)
) {
return getMaybePooled('null', null);
}
throw error;
}
throw new NativeFunctionError('Assertion failed, no error is thrown');
},
function timeStart(args, interpreterHandle) {
assertArgsLength(args, 0, 1);
const name = assertArgType(args, 0, 'string', 'default');
if (interpreterHandle.timers.has(name)) {
throw new NativeFunctionError(`Timer "${name}" already existed.`);
}
interpreterHandle.timers.set(name, Date.now());
return getMaybePooled('null', null);
},
function timeEnd(args, interpreterHandle) {
assertArgsLength(args, 0, 1);
const name = assertArgType(args, 0, 'string', 'default');
if (!interpreterHandle.timers.has(name)) {
throw new NativeFunctionError(`Cannot find timer "${name}".`);
}
const startTime = interpreterHandle.timers.get(name)!;
interpreterHandle.timers.delete(name);
const endTime = Date.now();
console.group('WTCD timeEnd call');
console.info(`Timer : ${name}`);
console.info(`Start time : ${startTime}`);
console.info(`End time : ${endTime}`);
console.info(`Time elapsed : ${endTime - startTime}ms`);
console.groupEnd();
return getMaybePooled('null', null);
},
];
|
kink/kat
|
src/wtcd/std/debug.ts
|
TypeScript
|
unknown
| 2,413 |
import { contentStdFunctions } from './content';
import { debugStdFunctions } from './debug';
import { listStdFunctions } from './list';
import { mathStdFunctions } from './math';
import { randomStdFunctions } from './random';
import { readerStdFunctions } from './reader';
import { stringStdFunctions } from './string';
import { canvasStdFunctions } from './canvas';
export const stdFunctions = [
...contentStdFunctions,
...debugStdFunctions,
...listStdFunctions,
...mathStdFunctions,
...randomStdFunctions,
...readerStdFunctions,
...stringStdFunctions,
...canvasStdFunctions,
];
|
kink/kat
|
src/wtcd/std/index.ts
|
TypeScript
|
unknown
| 598 |
import { getMaybePooled } from '../constantsPool';
import { describe, isEqual, ListValue } from '../Interpreter';
import { FunctionInvocationError, invokeFunctionRaw } from '../invokeFunction';
import { NativeFunction } from '../types';
import { WTCDError } from '../WTCDError';
import { assertArgsLength, assertArgType, NativeFunctionError } from './utils';
export const listStdFunctions: Array<NativeFunction> = [
function listSet(args) {
assertArgsLength(args, 3);
const list = assertArgType(args, 0, 'list');
const index = assertArgType(args, 1, 'number');
const value = args[2];
if (index % 1 !== 0) {
throw new NativeFunctionError(`Index (${index}) has to be an integer`);
}
if (index < 0) {
throw new NativeFunctionError(`Index (${index}) cannot be negative`);
}
if (index >= list.length) {
throw new NativeFunctionError(`Index (${index}) out of bounds. List ` +
`length is ${list.length}`);
}
const newList = list.slice();
newList[index] = value;
return {
type: 'list',
value: newList,
};
},
function listForEach(args, interpreterHandle) {
assertArgsLength(args, 2);
const list = assertArgType(args, 0, 'list');
const fn = assertArgType(args, 1, 'function');
list.forEach((element, index) => {
try {
invokeFunctionRaw(fn, [
element,
getMaybePooled('number', index),
], interpreterHandle);
} catch (error) {
if (error instanceof FunctionInvocationError) {
throw new NativeFunctionError(`Failed to apply function to the ` +
`element with index = ${index} of list: ${error.message}`);
} else if (error instanceof WTCDError) {
error.pushWTCDStack(`listForEach (index = ${index})`);
}
throw error;
}
});
return getMaybePooled('null', null);
},
function listMap(args, interpreterHandle) {
assertArgsLength(args, 2);
const list = assertArgType(args, 0, 'list');
const fn = assertArgType(args, 1, 'function');
const result = list.map((element, index) => {
try {
return invokeFunctionRaw(fn, [
element,
getMaybePooled('number', index),
], interpreterHandle);
} catch (error) {
if (error instanceof FunctionInvocationError) {
throw new NativeFunctionError(`Failed to apply function to the ` +
`element with index = ${index} of list: ${error.message}`);
} else if (error instanceof WTCDError) {
error.pushWTCDStack(`listForMap (index = ${index})`);
}
throw error;
}
});
return {
type: 'list',
value: result,
};
},
function listCreateFilled(args) {
assertArgsLength(args, 1, 2);
const length = assertArgType(args, 0, 'number');
const value = args.length === 1
? getMaybePooled('null', null)
: args[1];
if (length % 1 !== 0) {
throw new NativeFunctionError(`Length (${length}) has to be an integer.`);
}
if (length < 0) {
throw new NativeFunctionError(`Length (${length}) cannot be negative.`);
}
const list = new Array(length).fill(value);
return {
type: 'list',
value: list,
};
},
function listChunk(args) {
assertArgsLength(args, 2);
const list = assertArgType(args, 0, 'list');
const chunkSize = assertArgType(args, 1, 'number');
if (chunkSize % 1 !== 0 || chunkSize < 1) {
throw new NativeFunctionError(`Chunk size (${chunkSize} has to be a ` +
`positive integer.`);
}
const results: Array<ListValue> = [];
for (let i = 0; i < list.length; i += chunkSize) {
results.push({
type: 'list',
value: list.slice(i, i + chunkSize),
});
}
return {
type: 'list',
value: results,
};
},
function listFilter(args, interpreterHandle) {
assertArgsLength(args, 2);
const list = assertArgType(args, 0, 'list');
const fn = assertArgType(args, 1, 'function');
return {
type: 'list',
value: list.filter((item, index) => {
try {
const result = invokeFunctionRaw(fn, [
item,
getMaybePooled('number', index),
], interpreterHandle);
if (result.type !== 'boolean') {
throw new NativeFunctionError(`Predicate is expected to return ` +
`booleans, but ${describe(result)} is returned for element ` +
`with index = ${index}`);
}
return result.value;
} catch (error) {
if (error instanceof FunctionInvocationError) {
throw new NativeFunctionError(`Failed to apply function to the ` +
`element with index = ${index} of list: ${error.message}`);
} else if (error instanceof WTCDError) {
error.pushWTCDStack(`listFilter (index = ${index})`);
}
throw error;
}
}),
};
},
function listSplice(args) {
assertArgsLength(args, 3, 4);
const source = assertArgType(args, 0, 'list');
const start = assertArgType(args, 1, 'number');
const length = assertArgType(args, 2, 'number');
const newItems = assertArgType(args, 3, 'list', []);
if (start % 1 !== 0) {
throw new NativeFunctionError('Start index must be an integer, ' +
`provided: ${start}`);
}
if (start < 0 || start > source.length) {
throw new NativeFunctionError(`Start index must be in the bounds of ` +
`the list given (0 - ${source.length}), provided: ${start}`);
}
if (length % 1 !== 0) {
throw new NativeFunctionError('Start must be an integer.');
}
if (length < 0) {
throw new NativeFunctionError('Length must be nonnegative.');
}
if ((start + length) > source.length) {
throw new NativeFunctionError(`Length is too large and causes overflow.`);
}
const result = source.slice();
result.splice(start, length, ...newItems);
return {
type: 'list',
value: result,
};
},
function listSlice(args) {
assertArgsLength(args, 2, 3);
const source = assertArgType(args, 0, 'list');
const start = assertArgType(args, 1, 'number');
const end = assertArgType(args, 2, 'number', source.length);
if (start % 1 !== 0) {
throw new NativeFunctionError('Start index must be an integer, ' +
`provided: ${start}`);
}
if (start < 0 || start > source.length) {
throw new NativeFunctionError(`Start index must be in the bounds of ` +
`the list given (0 - ${source.length}), provided: ${start}`);
}
if (end % 1 !== 0) {
throw new NativeFunctionError('End index must be an integer, ' +
`provided: ${end}`);
}
if (end < 0 || end > source.length) {
throw new NativeFunctionError(`End index must be in the bounds of ` +
`the list given (0 - ${source.length}), provided: ${end}`);
}
if (end < start) {
throw new NativeFunctionError(`End index must be larger or equal to ` +
`start index. Provided start = ${start}, end = ${end}`);
}
return {
type: 'list',
value: source.slice(start, end),
};
},
function listLength(args) {
assertArgsLength(args, 1);
return getMaybePooled('number', assertArgType(args, 0, 'list').length);
},
function listIndexOf(args) {
assertArgsLength(args, 2);
const list = assertArgType(args, 0, 'list');
for (let i = 0; i < list.length; i++) {
if (isEqual(list[i], args[1])) {
return getMaybePooled('number', i);
}
}
return getMaybePooled('number', -1);
},
function listIncludes(args) {
assertArgsLength(args, 2);
const list = assertArgType(args, 0, 'list');
return getMaybePooled(
'boolean',
list.some(item => isEqual(item, args[1])),
);
},
function listFindIndex(args, interpreterHandle) {
assertArgsLength(args, 2);
const list = assertArgType(args, 0, 'list');
const fn = assertArgType(args, 1, 'function');
for (let i = 0; i < list.length; i++) {
const item = list[i];
try {
const result = invokeFunctionRaw(fn, [
item,
getMaybePooled('number', i),
], interpreterHandle);
if (result.type !== 'boolean') {
throw new NativeFunctionError(`Predicate is expected to return ` +
`booleans, but ${describe(result)} is returned for element ` +
`with index = ${i}`);
}
if (result.value) {
return getMaybePooled('number', i);
}
} catch (error) {
if (error instanceof FunctionInvocationError) {
throw new NativeFunctionError(`Failed to apply function to the ` +
`element with index = ${i} of list: ${error.message}`);
} else if (error instanceof WTCDError) {
error.pushWTCDStack(`listFindIndex (index = ${i})`);
}
throw error;
}
}
return getMaybePooled('number', -1);
},
];
|
kink/kat
|
src/wtcd/std/list.ts
|
TypeScript
|
unknown
| 9,024 |
import { getMaybePooled } from '../constantsPool';
import { NativeFunction } from '../types';
import { assertArgsLength, assertArgType } from './utils';
export const mathStdFunctions: Array<NativeFunction> = [
function mathMin(args) {
assertArgsLength(args, 1, Infinity);
let min = Infinity;
for (let i = 0; i < args.length; i++) {
const value = assertArgType(args, i, 'number');
if (value < min) {
min = value;
}
}
return getMaybePooled('number', min);
},
function mathMax(args) {
assertArgsLength(args, 1, Infinity);
let max = -Infinity;
for (let i = 0; i < args.length; i++) {
const value = assertArgType(args, i, 'number');
if (value > max) {
max = value;
}
}
return getMaybePooled('number', max);
},
function mathFloor(args) {
assertArgsLength(args, 1);
return getMaybePooled(
'number',
Math.floor(assertArgType(args, 0, 'number')),
);
},
function mathCeil(args) {
assertArgsLength(args, 1);
return getMaybePooled(
'number',
Math.ceil(assertArgType(args, 0, 'number')),
);
},
];
|
kink/kat
|
src/wtcd/std/math.ts
|
TypeScript
|
unknown
| 1,141 |
import { getMaybePooled } from '../constantsPool';
import { NativeFunction } from '../types';
import { assertArgsLength, assertArgType, NativeFunctionError } from './utils';
export const randomStdFunctions: Array<NativeFunction> = [
function random(args, interpreterHandle) {
assertArgsLength(args, 0, 2);
const low = assertArgType(args, 0, 'number', 0);
const high = assertArgType(args, 1, 'number', 1);
return {
type: 'number',
value: interpreterHandle.getRandom().next(low, high),
};
},
function randomInt(args, interpreterHandle) {
assertArgsLength(args, 2);
const low = assertArgType(args, 0, 'number');
const high = assertArgType(args, 1, 'number');
return getMaybePooled(
'number',
interpreterHandle.getRandom().nextInt(low, high),
);
},
function randomBoolean(args, interpreterHandle) {
assertArgsLength(args, 0, 1);
const trueChance = assertArgType(args, 0, 'number', 0.5);
return getMaybePooled(
'boolean',
interpreterHandle.getRandom().next() < trueChance,
);
},
function randomBiased(args, interpreterHandle) {
assertArgsLength(args, 0, 4);
const low = assertArgType(args, 0, 'number', 0);
const high = assertArgType(args, 1, 'number', 1);
const bias = assertArgType(args, 2, 'number', (low + high) / 2);
const influence = assertArgType(args, 3, 'number', 4);
if (low >= high) {
throw new NativeFunctionError('Low cannot be larger than or equal to ' +
'high.');
}
if (bias < low || bias > high) {
throw new NativeFunctionError('Bias has to be between low and high.');
}
let norm: number;
do {
// https://stackoverflow.com/questions/25582882/javascript-math-random-normal-distribution-gaussian-bell-curve
norm = bias + (high - low) / influence * Math.sqrt(
(-2) *
Math.log(interpreterHandle.getRandom().next())) *
Math.cos(2 * Math.PI * interpreterHandle.getRandom().next());
} while (norm < low || norm >= high);
return {
type: 'number',
value: norm,
};
},
];
|
kink/kat
|
src/wtcd/std/random.ts
|
TypeScript
|
unknown
| 2,106 |
import { getMaybePooled } from '../constantsPool';
import { FunctionValue } from '../Interpreter';
import { NativeFunction } from '../types';
import { assertArgsLength, assertArgType } from './utils';
export const readerStdFunctions: Array<NativeFunction> = [
function readerSetPinned(args, interpreterHandle) {
assertArgsLength(args, 1);
assertArgType(args, 0, 'function');
interpreterHandle.setPinnedFunction(args[0] as FunctionValue);
return getMaybePooled('null', null);
},
function readerUnsetPinned(args, interpreterHandle) {
assertArgsLength(args, 0);
interpreterHandle.setPinnedFunction(null);
return getMaybePooled('null', null);
},
function readerSetStateDesc(args, interpreterHandle) {
assertArgsLength(args, 1);
const stateDesc = assertArgType(args, 0, 'string');
interpreterHandle.setStateDesc(stateDesc);
return getMaybePooled('null', null);
},
function readerUnsetStateDesc(args, interpreterHandle) {
assertArgsLength(args, 0);
interpreterHandle.setStateDesc(null);
return getMaybePooled('null', null);
},
];
|
kink/kat
|
src/wtcd/std/reader.ts
|
TypeScript
|
unknown
| 1,097 |
import { getMaybePooled } from '../constantsPool';
import { NativeFunction } from '../types';
import { assertArgsLength, assertArgType, NativeFunctionError } from './utils';
export const stringStdFunctions: Array<NativeFunction> = [
function stringLength(args) {
assertArgsLength(args, 1);
const str = assertArgType(args, 0, 'string');
return getMaybePooled('number', str.length);
},
function stringFormatNumberFixed(args) {
assertArgsLength(args, 1, 2);
const num = assertArgType(args, 0, 'number');
const digits = assertArgType(args, 1, 'number', 0);
if (digits < 0 || digits > 100 || digits % 1 !== 0) {
throw new NativeFunctionError('Digits must be an integer between 0 and ' +
`100, received: ${digits}`);
}
return getMaybePooled('string', num.toFixed(digits));
},
function stringFormatNumberPrecision(args) {
assertArgsLength(args, 2);
const num = assertArgType(args, 0, 'number');
const digits = assertArgType(args, 1, 'number');
if (digits < 1 || digits > 100 || digits % 1 !== 0) {
throw new NativeFunctionError('Digits must be an integer between 1 and ' +
`100, received: ${digits}`);
}
return getMaybePooled('string', num.toPrecision(digits));
},
function stringSplit(args) {
assertArgsLength(args, 2);
const str = assertArgType(args, 0, 'string');
const separator = assertArgType(args, 1, 'string');
return getMaybePooled(
'list',
str.split(separator).map(str => getMaybePooled('string', str)),
);
},
function stringSubByLength(args) {
assertArgsLength(args, 2, 3);
const str = assertArgType(args, 0, 'string');
const startIndex = assertArgType(args, 1, 'number');
const length = assertArgType(args, 2, 'number', str.length - startIndex);
if (startIndex < 0 || startIndex % 1 !== 0) {
throw new NativeFunctionError(`Start index must be an nonnegative ` +
`integer, received: ${startIndex}`);
}
if (startIndex > str.length) {
throw new NativeFunctionError(`Start cannot be larger than str length. ` +
`startIndex=${startIndex}, str length=${str.length}`);
}
if (length < 0 || length % 1 !== 0) {
throw new NativeFunctionError(`Length must be an nonnegative integer ` +
`, received: ${length}`);
}
if (startIndex + length > str.length) {
throw new NativeFunctionError(`Index out of bounds. ` +
`startIndex=${startIndex}, length=${length}, ` +
`str length=${str.length}.`);
}
return getMaybePooled('string', str.substr(startIndex, length));
},
function stringSubByIndex(args) {
assertArgsLength(args, 2, 3);
const str = assertArgType(args, 0, 'string');
const startIndex = assertArgType(args, 1, 'number');
const endIndexExclusive = assertArgType(args, 2, 'number', str.length);
if (startIndex < 0 || startIndex % 1 !== 0) {
throw new NativeFunctionError(`Start index must be an nonnegative ` +
`integer, received: ${startIndex}`);
}
if (startIndex > str.length) {
throw new NativeFunctionError(`Start cannot be larger than str length. ` +
`startIndex=${startIndex}, str length=${str.length}`);
}
if (endIndexExclusive < 0 || endIndexExclusive % 1 !== 0) {
throw new NativeFunctionError(`End index must be an nonnegative ` +
`integer, received: ${endIndexExclusive}`);
}
if (endIndexExclusive < startIndex || endIndexExclusive > str.length) {
throw new NativeFunctionError(`End index cannot be smaller than start ` +
`index nor larger than the length of str. ` +
`endIndex=${endIndexExclusive}, startIndex=${startIndex}, ` +
`str length=${str.length}`);
}
return getMaybePooled('string', str.substring(startIndex, endIndexExclusive));
},
];
|
kink/kat
|
src/wtcd/std/string.ts
|
TypeScript
|
unknown
| 3,835 |
import { getMaybePooled } from '../constantsPool';
import {describe, RuntimeValue, RuntimeValueRaw, RuntimeValueType} from '../Interpreter';
export class NativeFunctionError extends Error {
public constructor(message: string) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
export function assertArgsLength(
args: ReadonlyArray<RuntimeValue>,
min: number,
max: number = min,
) {
if (args.length < min) {
throw new NativeFunctionError(`Too few arguments are provided. ` +
`Minimum number of arguments: ${min}, received: ${args.length}`);
}
if (args.length > max) {
throw new NativeFunctionError(`Too many arguments are provided. ` +
`Maximum number of arguments: ${max}, received: ${args.length}`);
}
}
/** Turn undefined to null value */
export function nullify(
args: ReadonlyArray<RuntimeValue>,
index: number,
) {
const value = args[index];
if (value === undefined) {
return getMaybePooled('null', null);
}
return value;
}
export function assertArgType<T extends RuntimeValueType>(
args: ReadonlyArray<RuntimeValue>,
index: number,
type: T,
defaultValue?: RuntimeValueRaw<T>,
): RuntimeValueRaw<T> {
const value = nullify(args, index);
if (value.type === 'null' && defaultValue !== undefined) {
return defaultValue;
}
if (value.type !== type) {
throw new NativeFunctionError(`The argument with index = ${index} of ` +
`invocation has wrong type. Expected: ${type}, received: ` +
`${describe(value)}`);
}
return value.value as any;
}
|
kink/kat
|
src/wtcd/std/utils.ts
|
TypeScript
|
unknown
| 1,563 |
import { InterpreterHandle, RuntimeValue, RuntimeValueType } from './Interpreter';
import { BinaryOperator, UnaryOperator } from './operators';
/**
* Nodes that may include location info (for debugging) when sourceMap is
* enabled can extend this interface.
*/
export interface OptionalLocationInfo {
line?: number;
column?: number;
}
export interface SingleSectionContent {
/** Earliest time this content will be used */
lowerBound?: number;
/** Latest time this content will be used */
upperBound?: number;
/** The compiled html for this content */
html: string;
/** Variables used in the html */
variables: Array<{
elementClass: string,
variableName: string,
}>;
}
/** e.g. 42 */
export interface NumberLiteral extends OptionalLocationInfo {
type: 'numberLiteral';
value: number;
}
/** e.g. true */
export interface BooleanLiteral extends OptionalLocationInfo {
type: 'booleanLiteral';
value: boolean;
}
/** e.g. "Rin <3" */
export interface StringLiteral extends OptionalLocationInfo {
type: 'stringLiteral';
value: string;
}
/** e.g. null */
export interface NullLiteral extends OptionalLocationInfo {
type: 'nullLiteral';
}
/** e.g. choice "do it" goto doIt */
export interface ChoiceExpression extends OptionalLocationInfo {
type: 'choiceExpression';
text: Expression;
action: Expression;
}
/** e.g. 5 + 3, true && false, a += 4 */
export interface BinaryExpression extends OptionalLocationInfo {
type: 'binaryExpression';
operator: BinaryOperator;
arg0: Expression;
arg1: Expression;
}
/** e.g. !false, -100 */
export interface UnaryExpression extends OptionalLocationInfo {
type: 'unaryExpression';
operator: UnaryOperator;
arg: Expression;
}
/** e.g. true ? 1 : 2 */
export interface ConditionalExpression extends OptionalLocationInfo {
type: 'conditionalExpression';
condition: Expression;
then: Expression;
otherwise: Expression;
}
/** e.g. goto eat */
export interface GotoAction extends OptionalLocationInfo {
type: 'gotoAction';
sections: Array<string>;
}
/** e.g. exit */
export interface ExitAction extends OptionalLocationInfo {
type: 'exitAction';
}
/** e.g.
* selection [
* choice "A" goto a
* choice "B" goto b
* ]
*/
export interface SelectionAction extends OptionalLocationInfo {
type: 'selection';
choices: Expression;
}
/** e.g. { a += 3 b -= 10 } */
export interface BlockExpression extends OptionalLocationInfo {
type: 'block';
statements: Array<Statement>;
}
/** e.g. hello */
export interface VariableReference extends OptionalLocationInfo {
type: 'variableReference';
variableName: string;
}
/** e.g.
* declare [
* number a = 100
* boolean b = false
* ]
*/
export interface DeclarationStatement extends OptionalLocationInfo {
type: 'declaration';
declarations: Array<OneVariableDeclaration>;
}
/** return 5 */
export interface ReturnStatement extends OptionalLocationInfo {
type: 'return';
value: Expression;
}
/** return = 5 */
export interface SetReturnStatement extends OptionalLocationInfo {
type: 'setReturn';
value: Expression;
}
export interface YieldStatement extends OptionalLocationInfo {
type: 'yield';
value: Expression;
}
export interface SetYieldStatement extends OptionalLocationInfo {
type: 'setYield';
value: Expression;
}
export interface BreakStatement extends OptionalLocationInfo {
type: 'break';
value: Expression;
}
export interface SetBreakStatement extends OptionalLocationInfo {
type: 'setBreak';
value: Expression;
}
export interface ContinueStatement extends OptionalLocationInfo {
type: 'continue';
}
export interface ExpressionStatement extends OptionalLocationInfo {
type: 'expression';
expression: Expression;
}
export interface FunctionArgument extends OptionalLocationInfo {
name: string;
type: VariableType;
defaultValue: Expression | null;
}
export interface FunctionExpression extends OptionalLocationInfo {
type: 'function';
arguments: Array<FunctionArgument>;
restArgName: string | null;
captures: Array<string>;
expression: Expression;
}
// NOTE: This is not an expression
export interface SpreadExpression extends OptionalLocationInfo {
type: 'spread';
expression: Expression;
}
export interface ListExpression extends OptionalLocationInfo {
type: 'list';
elements: Array<Expression | SpreadExpression>;
}
export interface SwitchCase extends OptionalLocationInfo {
matches: Expression;
returns: Expression;
}
export interface SwitchExpression extends OptionalLocationInfo {
type: 'switch';
expression: Expression;
cases: Array<SwitchCase>;
defaultCase: Expression | null;
}
export interface WhileExpression extends OptionalLocationInfo {
type: 'while';
preExpr: Expression | null;
condition: Expression;
postExpr: Expression | null;
}
export interface IfExpression extends OptionalLocationInfo {
type: 'if';
condition: Expression;
then: Expression;
otherwise: Expression | null;
}
export interface TagExpression extends OptionalLocationInfo {
type: 'tag';
name: string;
}
export type Literal
= NumberLiteral
| BooleanLiteral
| StringLiteral
| NullLiteral;
export type OperatorExpression
= BinaryExpression
| UnaryExpression
| ConditionalExpression;
export type Action
= GotoAction
| ExitAction
| SelectionAction;
type FlowControl
= SwitchExpression
| WhileExpression
| IfExpression;
export type Expression
= Literal
| OperatorExpression
| Action
| BlockExpression
| ChoiceExpression
| VariableReference
| FunctionExpression
| ListExpression
| FlowControl
| TagExpression;
export type Statement
= DeclarationStatement
| ReturnStatement
| SetReturnStatement
| YieldStatement
| SetYieldStatement
| BreakStatement
| SetBreakStatement
| ContinueStatement
| ExpressionStatement;
export interface Section extends OptionalLocationInfo {
name: string;
content: Array<SingleSectionContent>;
executes: Expression | null;
then: Expression;
}
export interface OneVariableDeclaration extends OptionalLocationInfo {
variableName: string;
variableType: VariableType;
initialValue: Expression | null;
}
export interface WTCDRoot {
initStatements: Array<Statement>;
sections: Array<Section>;
}
export type WTCDParseResult = {
error: false;
wtcdRoot: WTCDRoot;
} | {
error: true;
message: string;
internalStack: string;
};
export type RegisterName = 'yield' | 'return' | 'break';
export type NativeFunction = (
args: ReadonlyArray<RuntimeValue>,
interpreterHandle: InterpreterHandle,
) => RuntimeValue;
export type VariableType = null | Array<RuntimeValueType>;
|
kink/kat
|
src/wtcd/types.ts
|
TypeScript
|
unknown
| 6,657 |
export function flat<T>(arr: ReadonlyArray<T | ReadonlyArray<T>>) {
const result: Array<T> = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...item);
} else {
result.push(item);
}
}
return result;
}
export function arrayEquals<T>(
arr0: ReadonlyArray<T>,
arr1: ReadonlyArray<T>,
comparator: (e0: T, e1: T) => boolean = (e0, e1) => e0 === e1,
) {
return (arr0.length === arr1.length) && arr0.every((e0, index) => comparator(e0, arr1[index]));
}
|
kink/kat
|
src/wtcd/utils.ts
|
TypeScript
|
unknown
| 506 |
// A launch configuration that launches the extension inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
]
}
]
}
|
kink/kat
|
src/wtcd/vscode-wtcd/.vscode/launch.json
|
JSON
|
unknown
| 588 |
# vscode-wtcd README
Syntax highlight for Wearable Technology's Conditional Document (WTCD).
|
kink/kat
|
src/wtcd/vscode-wtcd/README.md
|
Markdown
|
unknown
| 93 |
{
"comments": {
"lineComment": "//",
"blockComment": [ "/*", "*/" ]
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""],
["'", "'"],
["`", "`"],
],
"surroundingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""],
["'", "'"],
["`", "`"],
]
}
|
kink/kat
|
src/wtcd/vscode-wtcd/language-configuration.json
|
JSON
|
unknown
| 489 |
{
"name": "vscode-wtcd",
"displayName": "vscode-wtcd",
"publisher": "WTCD",
"description": "",
"version": "1.11.0",
"engines": {
"vscode": "^1.38.0"
},
"categories": [
"Programming Languages"
],
"contributes": {
"languages": [
{
"id": "wtcd",
"aliases": [
"Wearable Technology's Conditional Document (WTCD)",
"wtcd"
],
"extensions": [
".wtcd"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "wtcd",
"scopeName": "source.wtcd",
"path": "./syntaxes/wtcd.tmLanguage.json",
"embeddedLanguages": {
"meta.embedded.block.markdown": "text.html.markdown"
}
}
]
}
}
|
kink/kat
|
src/wtcd/vscode-wtcd/package.json
|
JSON
|
unknown
| 989 |
{
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
"name": "Wearable Technology's Conditional Document (WTCD)",
"patterns": [
{ "include": "#contentSection" },
{ "include": "#logicSection" },
{ "include": "#goto" },
{ "include": "#declare" },
{ "include": "#keywords" },
{ "include": "#languageConstants" },
{ "include": "#comments" },
{ "include": "#braces" },
{ "include": "#blockExpressions" },
{ "include": "#operators" },
{ "include": "#tags" },
{ "include": "#strings" },
{ "include": "#stdFunctions" },
{ "include": "#variables" },
{ "include": "#semicolon" }
],
"repository": {
"contentSection": {
"name": "meta.embedded.block.markdown",
"patterns": [{ "include": "text.html.markdown" }],
"begin": "^(---<<<\\s+)([a-zA-Z_][a-zA-Z_0-9]*)(?:(@)([0-9\\-]+))?(\\s+>>>---)$",
"beginCaptures": {
"1": { "name": "punctuation.definition" },
"2": { "name": "entity.name.type.class" },
"3": { "name": "keyword.operator.wtcd" },
"4": { "name": "constant.numeric.wtcd" },
"5": { "name": "punctuation.definition" }
},
"end": "(?=^---<<<\\s+[a-zA-Z_][a-zA-Z_0-9]*(?:@[0-9\\-]+)?\\s+>>>---$)"
},
"logicSection": {
"name": "storage.type.class.section.wtcd",
"match": "\\bsection\\s+([a-zA-Z_][a-zA-Z_0-9]*)",
"captures": {
"1": { "name": "entity.name.type.class.section.wtcd" }
}
},
"goto": {
"patterns": [{
"name": "keyword.control.wtcd",
"match": "\\bgoto\\s+([a-zA-Z_][a-zA-Z_0-9]*)",
"captures": {
"1": { "name": "entity.name.type.class.section.wtcd" }
}
}, {
"name": "keyword.control.wtcd",
"match": "\\bgoto\\s*(\\[)((?:\\s*[a-zA-Z_][a-zA-Z_0-9]*)*\\s*)(\\])",
"captures": {
"1": { "name": "meta.brace.wtcd" },
"2": { "name": "entity.name.type.class.section.wtcd" },
"3": { "name": "meta.brace.wtcd" }
}
}]
},
"declare": {
"name": "storage.type.class.declare.wtcd",
"match": "\\bdeclare\\b"
},
"keywords": {
"name": "keyword.control.wtcd",
"match": "\\$|\\b(number|boolean|string|action|then|selection|choice|yield|exit|return|function|switch|list|while|do|if|else|continue|break)\\b"
},
"languageConstants": {
"patterns": [{
"name": "constant.language.wtcd",
"match": "\\b(null|true|false)\\b"
}, {
"name": "constant.numeric.wtcd",
"match": "(?:0|[1-9][0-9]*(?:\\.[0-9]*)?)"
}]
},
"comments": {
"name": "comment.line.double-slash.wtcd",
"match": "//.*$"
},
"braces": {
"name": "meta.brace.wtcd",
"match": "\\[|\\]|\\(|\\)"
},
"blockExpressions": {
"name": "punctuation.definition.block",
"match": "{|}"
},
"operators": {
"name": "keyword.operator.wtcd",
"match": "[+\\-*\\/^&|=><!?:%.]+"
},
"tags": {
"name": "variable.other.object.property",
"match": "#[a-zA-Z_][a-zA-Z_0-9]*"
},
"strings": {
"name": "string.quoted.double.wtcd",
"begin": "\"",
"end": "\"",
"patterns": [
{
"name": "constant.character.escape.wtcd",
"match": "\\\\."
}
]
},
"stdFunctions": {
"name": "support.function",
"match": "\\b(?:contentAddParagraph|contentAddImage|contentAddUnorderedList|contentAddOrderedList|contentAddHeader|contentAddTable|contentAddHorizontalRule|print|assert|assertError|timeStart|timeEnd|listSet|listForEach|listMap|listCreateFilled|listChunk|listFilter|listSplice|listSlice|listLength|listIndexOf|listIncludes|listFindIndex|mathMin|mathMax|mathFloor|mathCeil|random|randomInt|randomBoolean|randomBiased|stringLength|stringFormatNumberFixed|stringFormatNumberPrecision|stringSplit|stringSubByLength|stringSubByIndex|readerSetPinned|readerUnsetPinned|readerSetStateDesc|readerUnsetStateDesc|canvasCreate|canvasPutImage|canvasPutImagePart|canvasOutput|canvasClear|canvasSetFont|canvasSetFillStyle|canvasFillText|canvasFillRect|canvasSetStrokeStyle|canvasSetLineWidth|canvasStrokeText)\\b"
},
"variables": {
"name": "variable.other.readwrite.wtcd",
"match": "\\b[a-zA-Z_][a-zA-Z_0-9]*\\b"
},
"semicolon": {
"name": "invalid.illegal",
"match": ";"
}
},
"scopeName": "source.wtcd"
}
|
kink/kat
|
src/wtcd/vscode-wtcd/syntaxes/wtcd.tmLanguage.json
|
JSON
|
unknown
| 4,149 |
#!/usr/bin/env node
const glob = require('glob');
const fs = require('fs');
const obfuscateExtension = '.obfs';
function showSyntaxAndExit() {
console.info(`Syntax: wtobfs <o[bfuscate]|d[eobfuscate]> <files> [...other files]`);
process.exit(1);
}
function involute(buffer) {
let mask = 233;
for (let i = 0; i < buffer.length; i++) {
buffer[i] ^= mask;
mask = (mask * 29) % 256;
}
}
const startTime = Date.now();
if (process.argv.length < 3) {
showSyntaxAndExit();
}
const modeSpecifier = process.argv[2];
let obfuscateMode;
if ('obfuscate'.startsWith(modeSpecifier)) {
obfuscateMode = true;
} else if ('deobfuscate'.startsWith(modeSpecifier)) {
obfuscateMode = false;
} else {
showSyntaxAndExit();
}
const files = process.argv.slice(3).flatMap(pattern => glob.sync(pattern, {
nodir: true,
})).filter(path => path.endsWith(obfuscateExtension) ^ obfuscateMode);
if (files.length === 0) {
console.info(`No ${obfuscateMode ? 'unobfuscated' : 'obfuscated'} file matched pattern${process.argv.length > 3 ? 's' : ''}: ${process.argv.slice(3).map(pattern => `"${pattern}"`).join(', ')}.`);
process.exit(2);
}
console.info(`Found ${files.length} matching file${files.length !== 1 ? 's' : ''}.`);
const sequenceDigits = Math.floor(Math.log10(files.length)) + 1;
for (let i = 0; i < files.length; i++) {
const filePath = files[i];
console.info(`[${String(i + 1).padStart(sequenceDigits, ' ')}/${files.length}] ${obfuscateMode ? 'Obfuscating' : 'Deobfuscating'} ${filePath}.`);
const fileContent = fs.readFileSync(filePath);
involute(fileContent);
fs.writeFileSync(
obfuscateMode
? (filePath + obfuscateExtension)
: filePath.substr(0, filePath.length - obfuscateExtension.length),
fileContent,
);
}
console.info(`Successfully ${obfuscateMode ? 'obfuscated' : 'deobfuscated'} ${files.length} file${files.length !== 1 ? 's' : ''} in ${Date.now() - startTime}ms.`);
|
kink/kat
|
src/wtobfs.js
|
JavaScript
|
unknown
| 1,928 |
{
"compilerOptions": {
"downlevelIteration": true,
"lib": [ "es2020", "dom" ],
"module": "commonjs",
"noImplicitAny": true,
"outDir": "ts-out",
"rootDir": "src",
"strict": true,
"target": "es2016",
"jsx": "react",
"jsxFactory": "$e"
}
}
|
kink/kat
|
tsconfig.json
|
JSON
|
unknown
| 293 |
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {},
"rules": {
"quotemark": [true, "single"],
"semicolon": [true, "always"],
"max-classes-per-file": false,
"array-type": [true, "generic"],
"member-ordering": false,
"no-eval": false,
"no-console": false,
"ban-types": false,
"arrow-parens": false,
"no-var-requires": false,
"prefer-for-of": false,
"object-literal-sort-keys": false,
"interface-name": false,
"no-shadowed-variable": false,
"no-conditional-assignment": false,
"max-line-length": false,
"no-bitwise": false,
"triple-equals": true
},
"rulesDirectory": []
}
|
kink/kat
|
tslint.json
|
JSON
|
unknown
| 715 |
kink/kat
|
workers-site/.cargo-ok
|
none
|
unknown
| 0 |
|
node_modules
worker
|
kink/kat
|
workers-site/.gitignore
|
Git
|
unknown
| 20 |
import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'
/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = false
addEventListener('fetch', event => {
try {
event.respondWith(handleEvent(event))
} catch (e) {
if (DEBUG) {
return event.respondWith(
new Response(e.message || e.toString(), {
status: 500,
}),
)
}
event.respondWith(new Response('Internal Error', { status: 500 }))
}
})
async function handleEvent(event) {
const url = new URL(event.request.url)
let options = {}
/**
* You can add custom logic to how we fetch your assets
* by configuring the function `mapRequestToAsset`
*/
// options.mapRequestToAsset = handlePrefix(/^\/docs/)
try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
}
}
return await getAssetFromKV(event, options)
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
})
return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
} catch (e) {}
}
return new Response(e.message || e.toString(), { status: 500 })
}
}
/**
* Here's one example of how to modify a request to
* remove a specific prefix, in this case `/docs` from
* the url. This can be useful if you are deploying to a
* route on a zone, or if you only want your static content
* to exist at a specific path.
*/
function handlePrefix(prefix) {
return request => {
// compute the default (e.g. / -> index.html)
let defaultAssetKey = mapRequestToAsset(request)
let url = new URL(defaultAssetKey.url)
// strip the prefix from the path for lookup
url.pathname = url.pathname.replace(prefix, '/')
// inherit all other props from the default request
return new Request(url.toString(), defaultAssetKey)
}
}
|
kink/kat
|
workers-site/index.js
|
JavaScript
|
unknown
| 2,303 |
{
"name": "worker",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@cloudflare/kv-asset-handler": {
"version": "0.0.11",
"resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.0.11.tgz",
"integrity": "sha512-D2kGr8NF2Er//Mx0c4+8FtOHuLrnwOlpC48TbtyxRSegG/Js15OKoqxxlG9BMUj3V/YSqtN8bUU6pjaRlsoSqg==",
"requires": {
"@cloudflare/workers-types": "^2.0.0",
"@types/mime": "^2.0.2",
"mime": "^2.4.6"
}
},
"@cloudflare/workers-types": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-2.0.0.tgz",
"integrity": "sha512-SFUPQzR5aV2TBLP4Re+xNX5KfAGArcRGA44OLulBDnfblEf3J+6kFvdJAQwFhFpqru3wImwT1cX0wahk6EeWTw=="
},
"@types/mime": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@types/mime/-/mime-2.0.2.tgz",
"integrity": "sha512-4kPlzbljFcsttWEq6aBW0OZe6BDajAmyvr2xknBG92tejQnvdGtT9+kXSZ580DqpxY9qG2xeQVF9Dq0ymUTo5Q=="
},
"mime": {
"version": "2.4.6",
"resolved": "https://registry.npmjs.org/mime/-/mime-2.4.6.tgz",
"integrity": "sha512-RZKhC3EmpBchfTGBVb8fb+RL2cWyw/32lshnsETttkBAyAUXSGHxbEJWWRXc751DrIxG1q04b8QwMbAwkRPpUA=="
}
}
}
|
kink/kat
|
workers-site/package-lock.json
|
JSON
|
unknown
| 1,310 |
{
"private": true,
"name": "worker",
"version": "1.0.0",
"description": "A template for kick starting a Cloudflare Workers project",
"main": "index.js",
"author": "Ashley Lewis <[email protected]>",
"license": "MIT",
"dependencies": {
"@cloudflare/kv-asset-handler": "~0.0.11"
}
}
|
kink/kat
|
workers-site/package.json
|
JSON
|
unknown
| 308 |
name = "wearable_technology"
type = "webpack"
account_id = "!AccountID"
workers_dev = false
route = "wt.0w0.bid/*"
zone_id = "!ZoneID"
[site]
bucket = "./public"
entry-point = "workers-site"
|
kink/kat
|
wrangler.toml
|
TOML
|
unknown
| 192 |
*.bat text eol=crlf
*.tw text eol=lf
*.sh text eol=lf
*.py text eol=lf
*.txt text eol=lf
compile text eol=lf
compile-git text eol=lf
sanityCheck text eol=lf
|
DankWolf/fc
|
.gitattributes
|
Git
|
bsd-3-clause
| 157 |
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
*.swp
*.swo
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
# Start.tw
src/config/start.tw
|
DankWolf/fc
|
.gitignore
|
Git
|
bsd-3-clause
| 1,091 |
{
"browser": true,
"esversion": 6,
"eqeqeq": true,
"nocomma": true,
"undef": true,
"maxerr": 150
}
|
DankWolf/fc
|
.jshintrc
|
none
|
bsd-3-clause
| 105 |
further development:
-specialized slave schools
-fortifications
-more levels for militia edict (further militarize society)
-conquering other arcologies?
Events:
-famous criminal escapes to the arcology, followed by another arcology police force
Bugs:
-sometimes troop counts breaks
-sometimes rebel numbers have fractionary parts
Rules Assistant:
- find a way for the new intense drugs to fit in
- everything mentioned in https://gitgud.io/pregmodfan/fc-pregmod/issues/81
main.tw porting:
- slaveart
- createsimpletabs
- displaybuilding
- optionssortasappearsonmain
- resetassignmentfilter
- mainlinks
- arcology description
- office description
- slave summary
- use guard
- toychest
- walk past
|
DankWolf/fc
|
TODO.txt
|
Text
|
bsd-3-clause
| 702 |
# How to vector art
Please read the whole document before starting to work.
Some aspects are not obvious right away.
Note: This does not actually describe how to be an artist.
## TL;DR
killall inkscape
artTools/vector_layer_split.py artTools/vector_source.svg tw src/art/vector/layers/
compile
python3 artTools/normalize_svg.py artTools/vector_source.svg
git commit -a
## 1. Be an artist
Make changes to the vector_source.svg.
Inkscape was thoroughly tested.
Adobe Illustrator might work decently, too.
## 2. Respect the structure
While editing, keep the Layers in mind.
* In Inkscape, Layers are special "Inkscape groups".
* In Illustrator, Layers are groups with user-definded IDs.
* All Layers should have an ID that is globally unique
(not just within their subtree).
* Please use anonymous groups only for the ease of editing. Remove all "helper" groups before finally saving the file.
* Anonymous groups can be used for continous scaling (of e.g. boobs).
* Every asset that should go into a separate file needs to be in a labelled group
(even if that is a group with only one shape).
* There are some globally available styles defined as CSS classes (e.g. skin, hair).
Use them if your asset should be changed upon display.
Do not set the style directly in the object.
## 3. Normalise the document (before committing)
**THIS IS IMPORTANT**
The various editors out there (Inkscape, Illustrator) may use different variants of formatting the SVG XML.
Use
python3 normalize_svg.py vector_source.svg
before committing to normalise the format so git will not freak out about the changed indentation.
If you use Inkscape, please use in Edit → Settings → Input/Output → SVG-Output → Path Data → Optimized. This is the default.
In case your Editor uses another path data style which cannot be changed, please contact the other artists and developers via the issue tracker to find a new common ground.
What it does:
* Formats the SVG XML according to Pythons lxml module, regardless of editor.
* Adobe Illustrator uses group IDs as layer labels.
Inkscape however uses layer labels and a separate, auto-generated group ID.
normalize_svg.py overwrites the group ID with the Inkscape layer label
so they are synchronised with Inkscape layer labels.
* Inkscape copies the global style definition into the object *every time*
the object is edited. If an object references a CSS class AND at the same time
has a local style, the local style is removed
so global dynamic styling is possible later on.
Note: Behaviour of Adobe Illustrator is untested.
## 4. Split the layers
For NoX original, deepurk extensions, execute
python3 vector_layer_split.py vector_source_ndmain.svg tw ../src/art/vector/layers/
For faraen revamped art (based on NoX original)
python3 vector_revamp_layer_split.py vector_revamp_source.svg tw ../src/art/vector_revamp/layers/
. This application reads all groups in `vector_source.svg`.
Each group is stored in a separate file in the target directory `/src/art/vector/layers/`.
The group ID sets the file name. Therefore, the group ID **must not** contain spaces or any other weird characters.
Also consider:
* A group with ID ending in _ is ignored. Use Layers ending in _ to keep overview.
* A group with ID starting with "g" (Inkscape) or "XMLID" (Illustrator) is also ignored.
* Existing files are overwritten **without enquiry**.
* The target directory is not emptied. If a file is no longer needed, you should remove it manually.
* This procedure removes global definitions. This means, SVG filters are currently not supported.
Available output formats are `svg` and `tw`.
`svg` output exists for debug reasons.
`tw` embeds the SVG data into Twine files, but removes the global style definitions so they can be set during display.
## 5. Edit the code
`/src/art/` contains Twine code which shows the assets in the story.
There are many helpful comments in `/src/art/artWidgets.tw`.
The code also generates the previously removed global style definitions on the fly and per display.
## 6. Compile the story
Use the provided compile script (Windows batch or shell) for compiling.
## 7. Advanced usage
You can define multiple CSS classes to one element, e.g. "skin torso". When procedurally generating CSS, you can then set a global "skin" style, and a different one for "torso".
You can put variable text into the image using single quotes, e.g. "'+_tattooText+'". The single quotes *break* the quoting in Twine so the content of the Twine variable `_tattooText` is shown upon display. You can even align text on paths.
An anonymous group can be used for dynamic transformation. However, finding the correct parameters for the affine transformation matrix can be cumbersome. Use any method you see fit. See `src/art/vector/Boob.tw` for one example of the result.
|
DankWolf/fc
|
artTools/README.md
|
Markdown
|
bsd-3-clause
| 4,898 |
Apron
AttractiveLingerie
AttractiveLingerieForAPregnantWoman
BallGown
Battledress
BodyOil
Bunny
Chains
ChattelHabit
Cheerleader
ClubslutNetting
ComfortableBodysuit
Conservative
Cutoffs
Cybersuit
FallenNunsHabit
FuckdollSuit
HalterTopDress
HaremGauze
Hijab
Huipil
Kimono
LatexCatsuit
Leotard
LongQipao
MaternityDress
MilitaryUniform
MiniDress
Monokini
NiceBusinessAttire
NiceMaid
NiceNurse
No
PenitentNunsHabit
RedArmyUniform
RestrictiveLatex
ScalemailBikini
SchoolgirlUniform
SchutzstaffelUniform
ShibariRopes
SlaveGown
Slutty
SluttyBusinessAttire
SluttyJewelry
SluttyMaid
SluttyNurse
SluttyQipao
SluttySchutzstaffelUniform
Spats
StretchPants
StringBikini
Succubus
Toga
UncomfortableStraps
Western
|
DankWolf/fc
|
artTools/game_suffixes.txt
|
Text
|
bsd-3-clause
| 698 |
#!/bin/bash
# This script reads all possible values of $slave.clothes as mentioned by the documentation.
# This script uses the actual implementation of the JS clothing2artSuffix function as defined in src/art/vector/Helper_Functions.tw
# This script outputs suffixes to be used in the SVG naming scheme
# This script is meant to be executed at the project root directory.
# This script depends on bash, grep, sed, paste and nodejs (so best executed on Linux, I guess)
# grep -Porh '(?<=\.clothes = )"[^"]+"' src/ | sort | uniq # searches sources for all clothes strings actually used in the game, even undocumented ones
(
echo 'var window = {};'
grep -v '^:' src/art/vector/Helper_Functions.tw
echo -n 'Array('
sed '/^clothes:/,/:/!d' "slave variables documentation - Pregmod.txt" | grep '"' | paste -sd,
echo ').forEach(v => {console.log(window.clothing2artSuffix(v));});'
) | nodejs | sort
|
DankWolf/fc
|
artTools/generate_game_suffixes.sh
|
Shell
|
bsd-3-clause
| 908 |
#!/usr/bin/env python3
'''
Application for "normalizing" SVGs
These problems are addressed:
* Inkscape notoriously copies class styles into the object definitions.
https://bugs.launchpad.net/inkscape/+bug/167937
* Inkscape uses labels on layers. Layers are basically named groups.
Inkscape does not sync the group id with the layer label.
Usage Example:
python3 inkscape_svg_fixup.py vector_source.svg
'''
import lxml.etree as etree
import sys
def fix(tree):
# know namespaces
ns = {
'svg' : 'http://www.w3.org/2000/svg',
'inkscape' : 'http://www.inkscape.org/namespaces/inkscape'
}
# find document global style definition
# mangle it and interpret as python dictionary
style_element = tree.find('./svg:style',namespaces=ns)
style_definitions = style_element.text
pythonic_style_definitions = '{'+style_definitions.\
replace('\t.','"').replace('{','":"').replace('}','",').\
replace('/*','#')+'}'
styles = eval(pythonic_style_definitions)
# go through all SVG elements
for elem in tree.iter():
if (elem.tag == etree.QName(ns['svg'], 'g')):
# compare inkscape label with group element ID
l = elem.get(etree.QName(ns['inkscape'], 'label'))
if l:
i = elem.get('id')
if (i != l):
print("Overwriting ID %s with Label %s..."%(i, l))
elem.set('id', l)
# clean styles (for easier manual merging)
style_string = elem.get('style')
if style_string:
split_styles = style_string.strip('; ').split(';')
styles_pairs = [s.strip('; ').split(':') for s in split_styles]
filtered_pairs = [ (k,v) for k,v in styles_pairs if not (
k.startswith('font-') or
k.startswith('text-') or
k.endswith('-spacing') or
k in ["line-height", " direction", " writing", " baseline-shift", " white-space", " writing-mode"]
)]
split_styles = [':'.join(p) for p in filtered_pairs]
style_string = ';'.join(sorted(split_styles))
elem.attrib["style"] = style_string
# remove all style attributes offending class styles
s = elem.get('style')
c = elem.get('class')
if (c and s):
s = s.lower()
c = c.split(' ')[0] # regard main style only
cs = ''
if c in styles:
cs = styles[c].strip('; ').lower()
if (c not in styles):
print("Object id %s references unknown style class %s."%(i,c))
else:
if (cs != s.strip('; ')):
print("Style %s removed from object id %s differed from class %s style %s."%(s,i,c,cs))
del elem.attrib["style"]
if __name__ == "__main__":
input_file = sys.argv[1]
tree = etree.parse(input_file)
fix(tree)
# store SVG into file (input file is overwritten)
svg = etree.tostring(tree, pretty_print=True)
with open(input_file, 'wb') as f:
f.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n'.encode("utf-8"))
f.write(svg)
|
DankWolf/fc
|
artTools/normalize_svg.py
|
Python
|
bsd-3-clause
| 2,914 |
#!/usr/bin/env python3
'''
Application for procedural content adaption
*THIS IS VERY EXPERIMENTAL*
Contains a very poor man's implementation of spline mesh warping.
This application parses SVG path data of an outfit sample aligned to a body part.
The outfit is then replicated for other shapes of the same body part.
Example data is geared towards generating a strap outfit for boobs and torso
for all sizes of boobs and all shapes of torsos based on a single outfit for
boobs of size 2 and a hourglass torso respectively.
Limitations:
* handles paths only
* only svg.path Line and CubicBezier are tested
* only the aforementioned examples are tested
Usage:
python3 vector_clothing_replicator.py infile clothing bodypart destinationfile
Usage Example:
python3 vector_clothing_replicator.py vector_source.svg Straps Boob vector_destination.svg
python3 vector_clothing_replicator.py vector_source.svg Straps Torso vector_destination.svg
'''
from svg.path import parse_path
import copy
import lxml.etree as etree
import sys
REFERENCE_PATH_SAMPLES = 200
EMBED_REPLICATIONS = True # wether to embed all replications into the input file or output separate files
input_file = sys.argv[1]
clothing = sys.argv[2]
bodypart = sys.argv[3]
output_file_embed = sys.argv[4]
# TODO: make these configurable
output_file_pattern = '%s_%s_%s.svg' #bodypart, target_id, clothing
if ('Torso' == bodypart):
xpath_shape = './svg:g[@id="Torso_"]/svg:g[@id="Torso_%s"]/svg:path[@class="skin torso"]/@d' # TODO: formulate more general, independent of style
xpath_outfit_container = '//svg:g[@id="Torso_Outfit_%s_"]'%(clothing)
xpath_outfit = '//svg:g[@id="Torso_Outfit_%s_%s"]'%(clothing,'%s')
target_ids = "Unnatural,Hourglass,Normal".split(",")
reference_id = "Hourglass"
else:
raise RuntimeError("Please specify a bodypart for clothing to replicate.")
tree = etree.parse(input_file)
ns = {'svg' : 'http://www.w3.org/2000/svg'}
canvas = copy.deepcopy(tree)
for e in canvas.xpath('./svg:g',namespaces=ns)+canvas.xpath('./svg:path',namespaces=ns):
# TODO: this should be "remove all objects, preserve document properties"
e.getparent().remove(e)
def get_points(xpath_shape):
'''
This funciton extracts reference paths by the given xpath selector.
Each path is used to sample a fixed number of points.
'''
paths_data = tree.xpath(xpath_shape,namespaces=ns)
points = []
path_length = None
for path_data in paths_data:
p = parse_path(path_data)
points += [
p.point(1.0/float(REFERENCE_PATH_SAMPLES)*i)
for i in range(REFERENCE_PATH_SAMPLES)
]
if (not points):
raise RuntimeError(
'No paths for reference points found by selector "%s".'%(xpath_shape)
)
return points
def point_movement(point, reference_points, target_points):
'''
For a given point, finds the nearest point in the reference path.
Gives distance vector from the nearest reference point to the
respective target reference point.
'''
distances = [abs(point-reference_point) for reference_point in reference_points]
min_ref_dist_idx = min(enumerate(distances), key=lambda x:x[1])[0]
movement = target_points[min_ref_dist_idx] - reference_points[min_ref_dist_idx]
return movement
reference_points = get_points(xpath_shape%(reference_id))
container = tree.xpath(xpath_outfit_container,namespaces=ns)
if (len(container) != 1):
raise RuntimeError('Outfit container selector "%s" does not yield exactly one layer.'%(xpath_outfit_container))
container = container[0]
outfit_source = container.xpath(xpath_outfit%(reference_id),namespaces=ns)
if (len(outfit_source) != 1):
raise RuntimeError('Outfit source selector "%s" does not yield exactly one outfit layer in container selected by "%s".'%(xpath_outfit%(reference_id), xpath_outfit_container))
outfit_source = outfit_source[0]
for target_id in target_ids:
print(
'Generating variant "%s" of clothing "%s" for bodypart "%s"...'%
(target_id, clothing, bodypart)
)
outfit = copy.deepcopy(outfit_source)
paths = outfit.xpath('./svg:path',namespaces=ns)
if target_id == reference_id:
print("This is the source variant. Skipping...")
else:
layerid = outfit.get('id').replace('_%s'%(reference_id),'_%s'%(target_id))
outfit.set('id', layerid)
outfit.set(etree.QName('http://www.inkscape.org/namespaces/inkscape', 'label'), layerid) # for the Inkscape-users
target_points = get_points(xpath_shape%(target_id))
if (len(reference_points) != len(target_points)):
raise RuntimeError(
('Different amounts of sampled points in reference "%s" and target "%s" paths. '+
'Selector "%s" probably matches different number of paths in the two layers.')%
(reference_id, target_id, xpath_shape)
)
for path in paths:
path_data = path.get("d")
p = parse_path(path_data)
for segment in p:
original_distance = abs(segment.end-segment.start)
start_movement = point_movement(segment.start, reference_points, target_points)
segment.start += start_movement
end_movement = point_movement(segment.end, reference_points, target_points)
segment.end += end_movement
distance = abs(segment.end-segment.start)
try:
# enhance position of CubicBezier control points
# amplification is relative to the distance gained by movement
segment.control1 += start_movement
segment.control1 += (segment.control1-segment.start)*(distance/original_distance-1.0)
segment.control2 += end_movement
segment.control2 += (segment.control2-segment.end)*(distance/original_distance-1.0)
except AttributeError as ae:
# segment is not a CubicBezier
pass
path.set("d", p.d())
if EMBED_REPLICATIONS:
container.append(outfit)
if not EMBED_REPLICATIONS:
container = copy.deepcopy(canvas).xpath('.',namespaces=ns)[0]
container.append(outfit)
if not EMBED_REPLICATIONS:
svg = etree.tostring(container, pretty_print=True)
with open((output_file_pattern%(bodypart, target_id, clothing)).lower(), 'wb') as f:
f.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n'.encode("utf-8"))
f.write(svg)
if EMBED_REPLICATIONS:
svg = etree.tostring(tree, pretty_print=True)
with open(output_file_embed, 'wb') as f:
f.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n'.encode("utf-8"))
f.write(svg)
|
DankWolf/fc
|
artTools/vector_clothing_replicator.py
|
Python
|
bsd-3-clause
| 6,444 |
#!/usr/bin/env python3
'''
Application for splitting groups from one SVG file into separate files
Usage:
python3 vector_layer_split.py infile format outdir
Usage Example:
python3 vector_layer_split.py vector_source.svg tw ../src/art/vector/layers/
'''
import lxml.etree as etree
import sys
import os
import copy
import re
import normalize_svg
input_file = sys.argv[1]
output_format = sys.argv[2]
output_directory = sys.argv[3]
if not os.path.exists(output_directory):
os.makedirs(output_directory)
ns = {
'svg' : 'http://www.w3.org/2000/svg',
'inkscape' : 'http://www.inkscape.org/namespaces/inkscape',
'sodipodi':"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd",
}
tree = etree.parse(input_file)
normalize_svg.fix(tree)
# prepare output template
template = copy.deepcopy(tree)
root = template.getroot()
# remove all svg root attributes except document size
for a in root.attrib:
if (a != "viewBox"):
del root.attrib[a]
# add placeholder for CSS class (needed for workaround for non HTML 5.1 compliant browser)
if output_format == 'tw':
root.attrib["class"] = "'+_art_display_class+'"
# remove all content, including metadata
# for twine output, style definitions are removed, too
defs = None
for e in root:
if (e.tag == etree.QName(ns['svg'], 'defs')):
defs = e
if (e.tag == etree.QName(ns['svg'], 'g') or
e.tag == etree.QName(ns['svg'], 'metadata') or
e.tag == etree.QName(ns['svg'], 'defs') or
e.tag == etree.QName(ns['sodipodi'], 'namedview') or
(output_format == 'tw' and e.tag == etree.QName(ns['svg'], 'style'))
):
root.remove(e)
# template preparation finished
# prepare regex for later use
regex_xmlns = re.compile(' xmlns[^ ]+',)
regex_space = re.compile('[>][ ]+[<]',)
# find all groups
layers = tree.xpath('//svg:g',namespaces=ns)
for layer in layers:
i = layer.get('id')
if ( # disregard non-content groups
i.endswith("_") or # manually suppressed with underscore
i.startswith("XMLID") or # Illustrator generated group
i.startswith("g") # Inkscape generated group
):
continue
# create new canvas
output = copy.deepcopy(template)
# copy all shapes into template
canvas = output.getroot()
for e in layer:
canvas.append(e)
# represent template as SVG (binary string)
svg = etree.tostring(output, pretty_print=False)
# poor man's conditional defs insertion
# TODO: extract only referenced defs (filters, gradients, ...)
# TODO: detect necessity by traversing the elements. do not stupidly search in the string representation
if ("filter:" in svg.decode('utf-8')):
# it seems there is a filter referenced in the generated SVG, re-insert defs from main document
canvas.insert(0,defs)
# re-generate output
svg = etree.tostring(output, pretty_print=False)
if (output_format == 'tw'):
# remove unnecessary attributes
# TODO: never generate unnecessary attributes in the first place
svg = svg.decode('utf-8')
svg = regex_xmlns.sub('',svg)
svg = svg.replace(' inkscape:connector-curvature="0"','') # this just saves space
svg = svg.replace('\n','').replace('\r','') # print cannot be multi-line
svg = regex_space.sub('><',svg) # remove indentaion
svg = svg.replace('svg:','') # svg namespace was removed
svg = svg.replace('<g ','<g transform="\'+_art_transform+\'"') # internal groups are used for scaling
svg = svg.encode('utf-8')
# save SVG string to file
i = layer.get('id')
output_path = os.path.join(output_directory,i+'.'+output_format)
with open(output_path, 'wb') as f:
if (output_format == 'svg'):
# Header for normal SVG (XML)
f.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n'.encode("utf-8"))
f.write(svg)
elif (output_format == 'tw'):
# Header for SVG in Twine file (SugarCube print statement)
f.write((':: Art_Vector_%s [nobr]\n\n'%(i)).encode("utf-8"))
f.write("<<print '<html>".encode("utf-8"))
f.write(svg)
f.write("</html>' >>".encode("utf-8"))
|
DankWolf/fc
|
artTools/vector_layer_split.py
|
Python
|
bsd-3-clause
| 4,035 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.