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
作者:王木木 # 已弃坑 # 第五章 冲洗了一下自己的身体,随后浸泡在整个浴池里面,果然一整天的疲劳也随之而去,发情的身体也渐渐平静了下来,虽然今天从L的口中知道了还有秋博士这么一号人物的存在,但是我并不知道任何有关于秋博士长相以及特征的信息,而且就算找到了秋博士,也不清楚以现在秋博士的情况是否能帮助我脱下这装置,但秋博士已经是我唯一的救命稻草了,我也只能从秋博士这个点去碰碰运气了,毕竟我知道L肯定是不会轻易脱掉这个用来限制我行动的装置。 虽然现在身体上已经没有之前的贞操带装置,取而代之的是时刻都让乳头及阴蒂强制勃起的装置,受这个影响我的乳头及阴蒂都敏感得不行,小心翼翼的擦拭着身体尽量不去触碰到乳头及阴蒂,毕竟刚才冲洗身体的时候险些就被淋浴头喷出来的水带进了高潮。 既然已经洗完澡了,那么也该干点正事了,再次来到平时工作的秘密房间打开了设备,开始搜集着有关于秋镜悬的个人信息,不过就算我在怎么搜索,都查不到任何一丝信息,那么只有两种可能了,第一就是**秋镜悬**这个名字是个假名,不过我看L说话的神情并不像在说谎,那么只有另外一种可能了,某人让秋镜悬的信息就这么从外界消失了,看来一般的情报来源是获取不到秋博士的信息了,虽然觉得警方内部的资料应该还留有秋镜悬的信息,不过这得需要向上面申请一下许可才能调用里面的资料,但留下的搜索记录也会让上面知道秋博士与此事的联系,我也不清楚这时把秋博士卷进来是好是坏,只好先观望一段时间了,既然搜索不到秋镜悬的信息,那就只能找机会看看能不能从L的口中套话了。 看了眼时间比较晚了,才想起来好像还没吃过晚饭,来到客厅看见餐桌上摆放好的简餐,心中暗自庆幸终于不用在喝那**特质牛奶**了,看来L好像没打算在我的饮食上进行管理,吃着晚饭突然想起之前L好像有说送了我份**礼物**,双眼巡视了一下四周,发现并没有什么特别的变化,我也就没放在心上了。 “阿...嚏...” 也是,毕竟洗完澡之后就这么只裹了件浴巾,难免到现在是有点冷,回到卧室看见镜中那白色的过肘手套及过膝袜,除此之外仅有胸部和私处上的心形贴,不敢相信这就是眼中的自己打扮得如此的色情,下体也开始逐渐湿润起来,克制住自己的双手不去抚摸私处免得等会又一发不可收拾,穿好了睡衣刚走两步乳头及阴蒂就传来了布料的摩擦感,瞬间袭来的快感让我的双腿发软一下就跪坐在了地面上,在这乳头及阴蒂都强制勃起还特别敏感的状态下只能脱掉里面的内衣了,转过身看见的画面倒是让我有些意外,原本在右侧墙角的柜子已经被替换成了一个高大的展示柜,展示柜里面摆放了一个同人大小的手办保持着坐姿坐在某个东西上面,然而那东西被这手办的长裙给遮挡住了,让我看不见里面的内容,虽然不知道是哪个动漫里面的女角色,不过还挺好看的我很喜欢,这可能就是L之前说的那份**礼物**吧,没想到L居然还有这种爱好,倒是让我挺吃惊的,仔细观察了一下展示柜,并没有发现锁孔便又触摸了一下展示柜的四周,确认了自己没办法打开这展示柜我便没有继续观察这同人大小的手办就这么睡觉去了。 睡梦中的我突然就被胸部传来的胀痛感给吵醒了,看来是乳房里面的乳汁已经是饱和状态了,稍微挤了挤不过一切都是徒劳,正如L所说真的是一滴都不会流出来,虽然不会因随时可能会流出乳汁让我安心不少,但现在排不出乳汁的胸部所带来的胀痛感也是让人感到许多不适,看了眼时间也不早了,只能晚上再去找一趟L看看有没有商量的余地了,做好日常的准备便开始朝着学院移动,还好有了之前穿戴贞操带装置的经历,这胀痛感不一会我便适应了,今天只要留意一下裙底别被他人看见里面的真空状态就行了。 走在半路上除了胸部上那胀痛感隐约的能感受到一丝丝沉重,也不知是不是因为里面充满了乳汁的缘故,低头看了眼有一种变大了的错觉,不过街上还有一些行人也不方便用手估量一下,还好来到教室里用课桌当支撑点把胸放在上面,我如重释放的松了一口气,人生中第一次觉得胸太大了好像也不是什么好事,顺便趁着没人注意的时候用手抚摸了一圈胸部,果然是比昨天大了那么一点,看来不把胸部里面的乳汁给挤干净是变不回以前的大小,而且还因为害怕敏感的乳头与胸罩所产生摩擦而带来强烈的刺激感,没穿内衣的我就这么在座位上度过了一整天,期间除了来自同学的问候外都被我以身体不适为由糊弄走了,好像并没有引起其他的关注。 离开学院我便直接就朝着L的庄园移动,穿过几条小巷便看见几名男子追逐着一名女性,虽然不知道什么原由,不过心中还是想帮帮那名女性,看了眼逃跑的路线,我从另外一侧的巷子赶了过去在这必经之路的转角处早已等待就绪,不一会便听见嘈杂的脚步声,紧贴着墙壁朝里面望去,果然是她朝着我这方向奔跑身后的几名男性也紧追不舍,等待着女性与我擦肩而过的瞬间我便已经出手,虽然我的出现惊吓了这名女性使她摔倒在地,不过身后的几名男性已经被我击晕在原地。 我:“没事吧?” 她接过我向她递过去的手站立了起来。 女:“呼~~~呼~~,好久都没这样子跑过了,多谢了啊!你身手挺不错的啊,一下子就把他们给撩到了。” 我:“没什么,学过一些防身术罢了,还有他们为什么在追你呢?” 她看了我几眼,好像神情有一些微妙的变化,便拉着我的手继续朝着巷子里面移动。 女:“这个等会再说,这里不方便说话,你跟着我走就是。” 跟随着她又穿过了几条巷子,确认了四处没人她便停下了脚步。 女:“我先确认一下,你不是那边的人吧?” 我:“那边的人?那是什么?” 随后她指了下我的脖子处,我用手摸了摸,除了依旧紧锁在脖子上的金属圆环以外,并没有什么东西。 我:“你看得见这个?” 她点了点头。 我:“这个啊,不小心被人戴上之后,自己怎么也取不下来。” 女:“取不下来正常,毕竟当初就是这样设计的。” 我:“嗯?!” 随后她观察着我膀子上的金属圆环,还时不时的用手摸了摸,看她这专心的样子我也不好意思打断。 女:“这东西比起之前改进了不少啊,看你的样子好像不是那边的人,那你知道给你带上这个项圈的人吗?” 我:“他说他叫L,真名我也不知道。” 女:“啧,是他!” 我:“怎么?你认识他吗?” 女:“之前相处了一段时间,投过来的简历上面姓名一栏倒是写着**李梭**,后面查了查完全没有这个人的存在,恐怕之前的那份简历怕是伪造出来的,反正到现在我也只知道他是一个很有才华的人,至于其他的方面我也摸不透。” 从她的话语中在结合之前的经历我大概猜到了她的身份,不过既然她不愿意告诉我,我也不好再去过问。 我:“那你能取下这个项圈吗?” 女:“这要是以前的型号我倒是能帮你取下来,不过你现在这个已经被L改进了不少,解析花的时间恐怕早是被L察觉到了,到时候你我都有危险,我是不建议这样做。” 我:“哪还有别的方法吗?” 女:“你可以让这个项圈的所有者帮你取下。” 我:“我觉得L不会那样做。” 女:“我也这么觉得。” ...... 女:“哎呀,别这么失落嘛,跟你开个玩笑罢了,让你去找L不是没有道理的,这项圈除了能限制你的行动以外,还有展示是某人所有物的标志,既然所有者是L,那就说明他对你还是有兴趣的,不妨你假装顺从L降低他的防范心,等着哪天找到了这装置的中枢系统破坏掉就能取下来了。” 我:“这项圈还有自行防范功能吧,之前我也试过自行破解,结果瞬间就失去了意识,那我怎么还能破坏掉中枢系统呢?” 女:“这个我早就想到了,你转过身去,背对着我就行。” 照她所说我转身过去,虽然能感觉到她在我背后做了些什么,但也不方便回头观望,不一会便听见她继续说道。 女:“好了,我在你项圈里面增加了个芯片,它可以暂时切断与中枢系统的联系,让你不受它的影响,不过时限只有三分钟,还有当你确认找到承载着这中枢系统的设备时,你轻拍后颈处方位的项圈三下,它能入侵中枢系统帮你解除项圈,还能使整个系统瘫痪一段时间,那个时候凭你的身手L肯定不是你的对手,只是这范围很小,要距离设备五米才有作用,还有我提醒你一点,这两个功能都只能使用一次,所以你一定要有十足的把握在动手。” 我:“怎么当初设计的时候没有添加多次使用功能呢?” 女:“......,因为没什么好处,你第一次要是失败了,L怎会给你使用第二次的机会,而且增加了使用次数不管是放入的时刻,还是像现在这样待机的时候,都会提高被发现的概率,因为只有一次所以伪装的工作做得很好。” 我:“那我要怎么才能激活第一个切断功能,还有我要怎么确定是否找到了承载着中枢系统的设备呢?” 女:“前者你心里产生这种想法就行,后者只能靠你自己的判断了,我也就只能帮你到这里了,因为我也不清楚L会把这设备建立在哪里,说不准哪天他心情不错会带你参观一下他的研究设备,今天能跟你相遇也算一种缘分,不知不觉说了这么多,时间也不早了我得尽快赶去隔壁的市区了。” 我:“是因为身份被发现了吗?” 女:“并不是,在外界使用的另外一个身份把我隐藏的很好,这次来这座城市只是为了买点东西,没想到被几个黑市的人给盯上了,恐怕看我不是本地人想把我卖到某个地方去吧。” 我:“那你怎么没报警求助呢?” 女:“没有用的,这座城市早已经被L给腐化了,像我这种伪造出来的身份没权没势,恐怕只是自讨苦吃,那么有缘再见了,梦真小姐。” 我:“??,我不记得我有说过我的名字,你是怎么知道的。” 只见她一边背对着我远去,一边慢慢说道。 女:“这也是项圈的另外一个功能罢了,如果是圈子里的人,恐怕不仅知道你的名字怕是也知道你是L的所有物,看你的样子不也猜到了我是谁吗?那么今天的事情一定要保密了,走漏了风声你我都没好处。” 虽然之前有点不太确定,不过听她这么一说更加证实了我的想法,今天偶遇秋博士这件事恐怕是一波转折点,后面只需照秋博士所说帮L办事,等待着下手的时机即可。 随后我便朝着L的庄园移动,没想到这次推开别墅的大门,居然看见一名穿着正装的男子坐在客厅里优雅的品味着什么东西一眼望去十分的帅气,仔细一看这不就是L吗,看着我的到来他放下了手里的杯子,指了下对面的沙发,随后向我问道。 L:“你要来杯咖啡吗?” 我:“不用了。” 看着我坐在了对面,他喝了两口咖啡随后又说道。 L:“那么梦真小姐今天来又有何事呢?” 我:“两件事,第一件能不能帮我把乳头和阴蒂上面的装置给取下来,每时每刻都强制勃起特别敏感连内衣都没办法穿。” L:“怎么梦真小姐没打算多享受几天吗?这种敏感度,不是随便刺激刺激就能高潮了吗?而且取下来不是随时都有可能会流出乳汁,当初不也是你让我帮你装上去的吗?” 我:“......,那我这随时都会产生乳汁的体质要持续多久?” L:“我也不清楚,毕竟是第一次测试。” 听到这里我整个人脸色都不好了。 L:“好了,梦真小姐也别生气,这装置除了能在饱和状态下不继续产生乳汁以外,其实还在测量,等什么时候效果消失了,我这边自然会知道的,到时候再帮你取下即可,而且刚装上去再取下来,对身体不好。” 我:“你不会在骗我吧?” L:“我骗你又没有什么好处。” 我:“那我这因为乳头敏感没办法穿戴胸罩来支撑这充满乳汁而变得沉重的胸部怎么办?我现在站立都有点不适应。” L:“这个好办,你等我几分钟。” 随后只见L朝着二楼的阶梯行走,不到一分钟手里便拿着个精美的商品袋出现在我的视野内随后便递给了我,放眼望去里面摆放了一套内衣。 L:“你穿穿看。” 我:“在这里?” L盯着我点了点头。 我:“你能不能把头转过去。” L:“怎么?梦真小姐还没习惯?不是早就被我看了个遍。” 没办法,又一次在L的注视下把能脱掉的衣物全都脱掉了。 L:“嗯~~,不管怎么看,还是梦真小姐的身体好看,而且这个打扮真是让人欲罢不能啊!” 我:“你能不能好好看着就行别说话。” 虽然我也知道这打扮挺色情的,但是仅留在身体上的白色过肘手套及过膝袜还有那三处的心形贴都是我没办法自己能脱下来的。 刚戴上胸罩我就发现不太对劲,这和普通的完全不一样,胸部的以上完全就是镂空的仅仅只起了个支撑作用,而这内裤就更夸张了,V型的设计使阴蒂完全暴露在外面,稍微在外上面提一下完全就能陷进我的缝里面了,这不就是一套情趣内衣吗,不过好像挺合身的,完全就是照着我的身体比例而做出来的。 L:“穿上了这套内衣,梦真小姐比之前更加诱人了呢!这样没办法穿内衣的问题也解决了,那么你的第二件事呢?” 虽然不想承认,但是好像L从另外一个角度把这件事给解决了,随后我穿好了衣物坐下来继续和他交谈。 我:“你之前说的事情我准备答应你了” L:“哦?什么事。” 我:“你让我去抓秋镜悬这件事。” 听到我的回答,L先喝了两口咖啡随后便用凌人的目光注视着我,突然整个人的气场都变了。 L:“梦真小姐是遇见了什么事情吗?怎么突然就改变主意愿意为我去抓秋镜悬了。” 还好我也不是吃素的,在他这凌人的气场前,我淡淡的回道到,并没有漏出什么破绽。 我:“没什么,只是突然想明白了,好像我现在这个处境答应你这件事才是明智之举吧。” 看着我的神情不像在说谎,L随后又恢复了之前的样子。 L:“不愧是我心仪的梦真小姐,这么快就做出了明智的决定,虽然说是让你去抓捕秋镜悬,其实是想让你帮我办事罢了,毕竟我到现在一丝秋镜悬的情报都没弄到,完全不知道她在哪呢。” 听完他所说,我也帮秋博士松了一口气,果然如同秋博士之前说的一样在外界伪装的挺好。 我:“那我帮你办事又有什么好处呢,你会帮我解开脖子上的项圈吗?” 突然L的目光又变得凌人起来。 L:“项圈,你从哪听来的这个词!” 坏了好像L并没有告诉我这东西是项圈的象征,还好我灵机一动镇定自若的回答。 我:“刚才穿过巷子遇见几个黑市的人准备对我动手,看见我脖子上的东西突然停手,我于是便问了下。” L:“那他们还有说过什么吗?” 我:“没什么,只是还说了这项圈是某人所有物的象征罢了。” L:“那你应该明白男人一旦得手的东西是不会再放手了,至于好处吧,我看你家庭条件也不像缺钱的,放你走又是不可能的事,所以我只能再给你一些更高的权限。” 我:“权限?那是什么。” L:“比如这研究室的一些操作权限。” 我:“那我应该做些什么呢?” L:“嗯,这个嘛~~多数都是来当我的研究测试对象,好像平时也没事可干,对了!今天刚出门做了一笔交易,你帮我照看好这个商品,过段时间有人会上你家来取的。” 随后只见L对着桌子操作了几下,他背后的墙壁便打开了一扇门,没想到连这桌子都暗藏玄机,大约过了几分钟从里面走出了一名少女,给人的第一印象应该是某个家庭的千金把,虽然穿着的挺普通但还是稍微散发了一些气质,看似年龄应该和我差不多,仔细观察了一下,一米六左右的身高,乌黑而又亮丽的长发披在了她的后背看似每天都护理的很好,虽然脸上戴着某种特制的口罩但也掩盖不了她那俊俏的面容,双手穿戴者一双白色棉手套握着两边的肩带看似背后应该背了一些东西,至于衣着上倒是没什么特别在意的地方,透过脖子上的围巾隐约的能看见棕色外套里面穿戴着一件白色衬衣,裙底下那没过膝盖的黑色厚长袜把少女包裹的严严实实,给人一种体弱多病的感觉。 我:“她就是你说的商品吗?” L:“没错,那就需要梦真小姐帮我照看一段时间了,另外之前送你的礼物你还满意吗?” 我:“礼物?哦,你说那个同人大小的手办,我还挺喜欢的。” L:“呵呵,手办吗?不过梦真小姐喜欢就行。” 我:“话说怎么把柜子打开,把它从里面取出来,我还想仔细地观察一下!” L:“毕竟梦真小姐又不会使用她,所以就没告诉你打开柜子的方法,毕竟拆装都是一个很复杂的过程,而且每天都必须在柜子里面进行日常的保养,不过既然梦真小姐想知道打开柜子的方法,我也可以告诉你。” 我:“不必了。” 听他这么说我也没有想在取出来的打算,虽然第一眼就知道这手办价格不菲,没想到居然还需要每天都在柜子里进行保养,不过他所说的**使用**是什么我倒是没明白。 我:“那日常保养需要我做些什么呢?” L:“你什么都不用做,我早就设置好了,交给AI就行了,对了你回家把这两件东西带上。” 随后只见L拿出了一对心形的耳坠,那特别的材质让我明白这东西即使在上流的社会也是很难见到的,至于另外一件便是和手机差不多一样的物体,整个机身上面仅仅只有右侧一个按钮略有一丝奇怪。 L:“这对耳坠是带有通话功能的,你有什么事情想联系我的时候,用手轻轻敲击随意一侧的心形三次便可以和我产生通话,这样就不用再麻烦跑一趟了,这个功能需要戴在耳朵上才有作用,而且戴上了就不要随意取下来,至于另外一件东西最主要的功能就是当她不听话的时候你按一下旁边的侧键就行了,那么其他的功能你回家慢慢研究即可,还有学院那边你也暂时不用去了,我已经帮你请好病假了,你只需要帮我照看好她等待着顾客上门提货就行,那么后面几天时间还请梦真小姐和她度过一段美好的时光。” 我:“你......” 没想到L居然擅自就帮我请了病假,但现在大局已定我也只能接过这两件物品,随后准备离开。 L:“梦真小姐现在不戴上这耳坠吗?” 我:“我没穿过耳洞!” 随后L又递给了我一张黑卡。 L:“那梦真小姐拿着这个明天去一趟这上面的地址,顺便再买几件你现在身上穿着的同款内衣吧。” 同款内衣那不就是情趣内衣吗,听到这里有些气愤,接过黑卡放进衣包里,随后少女便和我一同离开了L的别墅,跟随着我朝着家里移动。
kink/kat
chapters/9 - 女高调查员/5.md
Markdown
unknown
20,632
{ "name": "wearable-technology", "version": "1.0.0", "description": "《可穿戴科技》网页构建脚本", "main": "builder/index.js", "scripts": { "compileTypeScriptOnce": "tsc", "buildChaptersProduction": "node ts-out/builder/index.js --production", "buildWebScript": "browserify ts-out/web/index.js -o dist/bundle.max.js", "minifyWebScript": "terser dist/bundle.max.js --compress --mangle --keep-fnames -o dist/bundle.js", "buildStyle": "lessc src/style/index.less dist/index.css", "build": "run-s compileTypeScriptOnce buildStyle buildWebScript minifyWebScript buildChaptersProduction", "buildChaptersDev": "node ts-out/builder/index.js", "dev-watch-staticServer": "cd dist && static-server -p 2333 -o --no-cache", "dev-watch-staticFileCopier": "fucking-fixed-sync-files --watch --no-delete static dist", "dev-watch-typescript": "tsc --watch --preserveWatchOutput", "dev-watch-browserify": "watchify ts-out/web/index.js -o dist/bundle.js", "dev-watch-chapterRebuilder": "node ./ts-out/builder/index.js --watch", "dev-watch-styleRebuilder": "chokidar \"./src/style/**/*\" -c \"npm run buildStyle\"", "buildWebScriptOnceForDevelopment": "browserify ts-out/web/index.js -o dist/bundle.js", "watch": "run-s compileTypeScriptOnce buildStyle buildWebScriptOnceForDevelopment && concurrently -n --kill-others npm:dev-watch-*", "lint": "tslint --project ./", "vscode-problems": "tsc --watch --noEmit", "deobfuscate-resources": "node src/wtobfs.js deobfuscate \"chapters/**/*.obfs\"", "obfuscate-images": "node src/wtobfs.js obfuscate \"chapters/1.4 - 插图/*.jpg\" \"chapters/1.4 - 插图/*.png\"", "generate-readme": "tsc && node ts-out/generateReadme.js" }, "bin": { "wtobfs": "src/wtobfs.js" }, "author": "SCLeo", "license": "CC-BY-NC-ND-4.0", "repository": "github:SCLeoX/Wearable-Technology", "dependencies": { "@types/fs-extra": "^9.0.11", "@types/markdown-it": "12.0.1", "@types/node": "^15.0.2", "browserify": "^17.0.0", "colorworks": "^1.1.1", "fs-extra": "^10.0.0", "hyperscript": "^2.0.2", "javascript-stringify": "^2.1.0", "markdown-it": "^12.0.6", "markdown-it-replace-link": "^1.1.0", "markdown-it-ruby": "^0.1.1", "sharp": "^0.28.3", "terser": "^5.7.0", "typescript": "^4.2.4", "unistring": "github:akahuku/unistring#master", "yargs": "^17.0.1" }, "devDependencies": { "@types/hyperscript": "0.0.4", "@types/sharp": "^0.28.3", "@types/yargs": "^16.0.1", "chokidar-cli": "^2.1.0", "concurrently": "^6.1.0", "csscomb": "^4.3.0", "fucking-fixed-sync-files": "^1.0.1", "less": "^4.1.1", "npm-run-all": "^4.1.5", "open-cli": "^6.0.1", "static-server": "^2.2.1", "tslint": "^6.1.3", "watchify": "^4.0.0" } }
kink/kat
package.json
JSON
unknown
3,078
>《可穿戴科技》是一部重口味色情小说。因其中含有大量露骨的非常规性行为描写,本小说可能不适合所有年龄段,亦不宜在工作期间访问。 # 可穿戴科技 [![pipeline status](https://gitgud.io/RinTepis/wearable-technology/badges/master/pipeline.svg)](https://gitgud.io/RinTepis/wearable-technology/-/commits/master) 《可穿戴科技》是一部关于一名社会恐惧症美少女和某智能贞操带斗智斗勇的色情小说。 ## [点此在线阅读 (GitLab Pages)](https://wt.tepis.me/) ☆☆☆☆☆【占位:镜像站列表】☆☆☆☆☆ ### 其他链接:[投稿](https://wt.tepis.me/#META/%E6%92%B0%E7%A8%BF%E9%A1%BB%E7%9F%A5%E5%8F%8A%E7%AE%80%E6%98%93-Markdown-%E6%95%99%E7%A8%8B.html) | [龙套](https://wt.tepis.me/#META/%E4%BA%BA%E5%90%8D%E8%AF%B7%E6%B1%82.html) | [WTCD 语言](https://wt.tepis.me/#META/WTCD/1.-%E6%A6%82%E8%BF%B0.html) 本小说[原先是放在 Google Docs 上](https://docs.google.com/document/d/1Pp5CtO8c77DnWGqbXg-3e7w9Q3t88P35FOl6iIJvMfo/edit?usp=sharing)的,但是由于篇幅变长,Google Docs 越来越卡,因此转移到 GitHub。然后 GitHub 又因为我们违反 ToS,[把我们的仓库封了](https://github.com/SCLeoX/Wearable-Technology)。 更新推送频道:https://t.me/joinchat/AAAAAEpkRVwZ-3s5V3YHjA 讨论组:https://t.me/joinchat/Dt8_WlJnmEwYNbjzlnLyNA ## 鸣谢 特别感谢以下小伙伴提供的建议与帮助,排名不分先后: ☆☆☆☆☆【占位:鸣谢列表】☆☆☆☆☆ 如果你想加入鸣谢列表里,你可以在讨论组或者在和作者的私聊里提提意见/脑洞啥的。哪怕你说的没有被采纳,我也十分愿意把你的名字加进来(一般情况下,如果我意识到了你在提意见,我就会主动来问你要不要加鸣谢列表。如果我没有意识到,我十分欢迎你主动来跟我说你要加鸣谢列表,热热闹闹的多好 √)。
kink/kat
readmeTemplate.md
Markdown
unknown
1,953
export type DisplayIndex = Array<number>; export interface NodeBase { type: NodeType; displayName: string; displayIndex: DisplayIndex; sourceRelativePath: string; charsCount: number | null; } export type NodeType = | 'folder' // Folder | 'Markdown' // Markdown based static chapter | 'WTCD'; // WTCD based interactive chapter export interface ChapterFlagsMapped { isEarlyAccess?: true; hidden?: true; abandoned?: true; } export type ChapterFlags = keyof ChapterFlagsMapped; export interface AuthorRole { name: string; role: string; } export interface ChapterBase extends NodeBase, ChapterFlagsMapped { htmlRelativePath: string; creationTime: number; authors: Array<AuthorRole>; tags?: Array<string>; } export interface MarkdownChapter extends ChapterBase { type: 'Markdown'; } export type WTCDReader = | 'flow' | 'game'; export interface WTCDChapterBase extends ChapterBase { type: 'WTCD'; preferredReader: WTCDReader; } export interface WTCDChapterFlow extends WTCDChapterBase { preferredReader: 'flow'; } export interface WTCDChapterGame extends WTCDChapterBase { preferredReader: 'game'; slideAnimation: boolean; } export type WTCDChapter = WTCDChapterFlow | WTCDChapterGame; export type Chapter = MarkdownChapter | WTCDChapter; export interface FolderMeta { showIndex?: boolean; } export interface Folder extends NodeBase, FolderMeta { type: 'folder'; children: Array<Node>; } export type Node = Folder | Chapter; export interface AuthorInfo { name: string; avatar: string; description?: string; } export interface Data { chapterTree: Folder; charsCount: number | null; paragraphsCount: number; keywordsCount: Array<[string, number]>; buildNumber: string; authorsInfo: Array<AuthorInfo>; buildError: boolean; tags: Array<[tag: string, variants: Array<string> | null]>; tagAliases: Array<[alias: string, tag: string]>; }
kink/kat
src/Data.ts
TypeScript
unknown
1,927
export type TagSpecDescLineSegment = { type: 'text', content: string, } | { type: 'reference', tag: string, }; interface TagSpecDescLine { isPrerequisite: boolean; segments: Array<TagSpecDescLineSegment>; } export interface TagSpec { tag: string; variants: Array<string> | null; priority: number; desc: Array<TagSpecDescLine>; aliases: Array<string>; } export type TagsSpec = Array<TagSpec>;
kink/kat
src/TagsSpec.ts
TypeScript
unknown
417
import { log } from './indentConsole'; export interface ReportableError { print(): void; } class SimpleReportableError implements ReportableError { public constructor( private message: string, private error: Error, ) {} public print(): void { log(`[[red|${this.message}]]`); console.info(this.error); } } export class ErrorReporter { private errors: Array<ReportableError> = []; public printAll() { this.errors.forEach((error, index) => { log(`[[bgRed|[[white|Error ${index + 1}/${this.errors.length}]]]]`); error.print(); log(); }); } public reportError(error: ReportableError) { this.errors.push(error as ReportableError); } public wrapAndReportError(message: string, error: Error) { this.reportError(new SimpleReportableError(message, error)); } public hasError() { return this.errors.length >= 1; } }
kink/kat
src/builder/ErrorReporter.ts
TypeScript
unknown
890
import { readFile, stat } from 'fs-extra'; import * as MDI from 'markdown-it'; import * as mdiReplaceLinkPlugin from 'markdown-it-replace-link'; import * as mdiRubyPlugin from 'markdown-it-ruby'; import { dirname, posix, resolve } from 'path'; import { isCompressibleImage, isDocument, isResource } from '../fileExtensions'; import { TagSpec } from '../TagsSpec'; import { Node } from './../Data'; import { destructPath } from './destructPath'; import { distChaptersDir } from './dirs'; import { ErrorReporter, ReportableError } from './ErrorReporter'; import { getCreationTime } from './getCreationTime'; import { fPath, log } from './indentConsole'; import { Stats } from './Stats'; const { join } = posix; export class LoaderError implements ReportableError { public constructor( private loaderName: string, private path: string, private error: any, ) {} public print(): void { log(`[[red|Error caused by loader [[cyan|${this.loaderName}]] on file [[yellow|${fPath(this.path)}]]:]]`); console.info(this.error); } } export class LoaderContext { public constructor( public readonly isDirectory: boolean, public readonly path: string, public readonly parentDistRelativePath: string, public readonly stats: Stats, public readonly production: boolean, private readonly errorReporter: ErrorReporter, private readonly tagsMap: ReadonlyMap<string, TagSpec> | null, public readonly buildFiles: Array<string> | null, public readonly nodeCache: Map<string, Node>, ) {} private distRelativePath: string | null = null; public updateCache(node: Node) { this.nodeCache.set(this.path, node); } public removeCache() { this.nodeCache.delete(this.path); } public getLastSuccess() { return this.nodeCache.get(this.path) ?? null; } public setDistFileName(fileName: string) { this.distRelativePath = (this.parentDistRelativePath === '' ? fileName : (this.parentDistRelativePath + '/' + fileName)) .split(' ') .join('-'); } public getNode() { return destructPath(this.path); } public getDistRelativePath() { if (this.distRelativePath === null) { throw new Error('A prior call to #setDistFileName() is required.'); } return this.distRelativePath; } public getDistFullPath() { return resolve(distChaptersDir, this.getDistRelativePath()); } public getCreationTime() { if (this.production) { return getCreationTime(this.path); } else { return 0; } } public readFile(): Promise<string> { return readFile(this.path, 'utf8'); } public createMDI() { const htmlRelativePath = this.getDistRelativePath(); return new MDI({ replaceLink(link: string) { if (!link.startsWith('./')) { return link; } if (isResource(link) || isCompressibleImage(link)) { return join('./chapters', dirname(htmlRelativePath), link); } if (isDocument(link)) { return '#/chapter/' + join(dirname(htmlRelativePath), link); } }, } as MDI.Options) .use(mdiReplaceLinkPlugin) .use(mdiRubyPlugin); } public async derive(subPath: string) { return new LoaderContext( (await stat(subPath)).isDirectory(), subPath, this.getDistRelativePath(), this.stats, this.production, this.errorReporter, this.tagsMap, this.buildFiles, this.nodeCache, ); } public pushError(error: LoaderError) { this.errorReporter.reportError(error); } public isTagValid(tag: string) { const match = tag.match(/^(.+?)(?:((.+)))?$/); if (match === null) { return false; } if (this.tagsMap === null) { return true; } const tagSpec = this.tagsMap.get(match[1]); if (tagSpec === undefined) { return false; } if (match[2] === undefined) { return tagSpec.variants === null; } else { return tagSpec.variants !== null && tagSpec.variants.includes(match[2]); } } }
kink/kat
src/builder/LoaderContext.ts
TypeScript
unknown
4,040
import { countCertainWord } from './countCertainWord'; import { countChars } from './countChars'; import { countParagraphs } from './countParagraphs'; import { keywords } from './keywords'; export class Stats { private charsCount = 0; private paragraphsCount = 0; private keywordsCount: Map<string, number> = new Map(); public constructor( private isProduction: boolean, ) { keywords.forEach(keyword => { this.keywordsCount.set(keyword, 0); }); } public processMarkdown(markdown: string): number | null { keywords.forEach(keyword => { const count = countCertainWord(markdown, keyword); if (count !== 0) { this.keywordsCount.set(keyword, this.keywordsCount.get(keyword)! + count); } }); if (this.isProduction) { const deltaChars = countChars(markdown); this.charsCount += deltaChars; return deltaChars; } else { return null; } } public processHtml(html: string) { this.paragraphsCount += countParagraphs(html); } public getCharsCount() { return this.charsCount; } public getParagraphCount() { return this.paragraphsCount; } public getKeywordsCount() { return this.keywordsCount; } }
kink/kat
src/builder/Stats.ts
TypeScript
unknown
1,219
export function countCertainWord(markdown: string, word: string) { let count = 0; let pointer = 0; while ((pointer = markdown.indexOf(word, pointer)) !== -1) { count++; pointer += word.length; } return count; }
kink/kat
src/builder/countCertainWord.ts
TypeScript
unknown
238
import * as Unistring from 'unistring'; const ignoredTypes = new Set([6, 7, 26]); export function countChars(markdown: string) { // JavaScript 的 string 其实是 UTF-16 序列,并且无法正常处理 Grapheme Cluster。 // 因此我们使用 Unistring 这个库来做能够正确处理 Unicode 的字数统计。 // // 在中文中,字数统计统计的是汉字的数量,而在英文中,统计的是词的数量。 // 因为《可穿戴科技》同时含有英文和中文,我们需要能够同时正确处理中文和英文。 // 因此,我们使用 Unistring 提供的 getWords 方法。这个方法会把输入的字符串根据 // Unicode 规定的分词方案分割成一个词语数组。需要注意的是,Unicode 的分词方案 // 并不会处理中文的分词,而是将每一个中文汉字当成一个单独的词语。恰好,这正是 // 我们需要的。 return Unistring.getWords(markdown) // 这里过滤掉空格和换行 .filter((word: any) => !ignoredTypes.has(word.type)) .length; }
kink/kat
src/builder/countChars.ts
TypeScript
unknown
1,079
export function countParagraphs(html: string) { let i = 0; let n = 0; while ((i = html.indexOf('<p>', i)) !== -1) { i += 3; n++; } return n; }
kink/kat
src/builder/countParagraphs.ts
TypeScript
unknown
170
import { basename, relative } from 'path'; import { DisplayIndex } from '../Data'; import { chaptersDir } from './dirs'; function removeExtension(name: string) { if (name.includes('.')) { name = name.substr(0, name.lastIndexOf('.')); } return name; } const displayIndexRegex = /^(?:[1-9][0-9]*|0)(?:\.(?:[1-9][0-9]*|0))*$/; function parseDisplayIndex(specifier: string): DisplayIndex { if (!displayIndexRegex.test(specifier)) { throw new Error(`Invalid display index specifier: "${specifier}".`); } return specifier.split('.').map(segment => { const num = +segment; if (num > Number.MAX_SAFE_INTEGER) { throw new Error(`The segment "${segment}" is too large.`); } return num; }); } // Get basic displayName, displayIndex, name, relativePath from a full path export function destructPath(fullPath: string): { displayName: string, displayIndex: DisplayIndex, sourceRelativePath: string, } { const relativePath = relative(chaptersDir, fullPath); if (relativePath === '') { // Root return { displayName: '', displayIndex: [0], sourceRelativePath: relativePath, }; } const name = basename(relativePath); let displayName; let displayIndex; const separatorIndex = name.indexOf(' - '); if (separatorIndex === -1) { displayIndex = parseDisplayIndex(removeExtension(name)); displayName = `第 ${displayIndex} 章`; } else { displayIndex = parseDisplayIndex(name.substr(0, separatorIndex)); displayName = removeExtension(name.substr(separatorIndex + 3)); } return { displayName, displayIndex, sourceRelativePath: relativePath, }; }
kink/kat
src/builder/destructPath.ts
TypeScript
unknown
1,661
import { resolve } from 'path'; export const rootDir = resolve(__dirname, '../..'); export const staticDir = resolve(rootDir, 'static'); export const chaptersDir = resolve(rootDir, 'chapters'); export const distDir = resolve(rootDir, 'dist'); export const distChaptersDir = resolve(distDir, 'chapters'); export const tagsSpec = resolve(rootDir, 'TagsSpec.txt');
kink/kat
src/builder/dirs.ts
TypeScript
unknown
362
import { execAsync } from './getCreationTime'; export async function execAsyncWithRetry(command: string) { let lastError: any; for (let retry = 1; retry <= 3; retry++) { try { return await execAsync(command); } catch (error) { lastError = error; } } throw lastError; }
kink/kat
src/builder/execAsyncWithRetry.ts
TypeScript
unknown
302
import { exec } from 'child_process'; import { promisify } from 'util'; import { execAsyncWithRetry } from './execAsyncWithRetry'; export const execAsync = promisify(exec); function getTimestamp(stdout: string) { const trimmed = stdout.trim(); if (trimmed === '') { return undefined; } return +trimmed.substr(trimmed.lastIndexOf('\n') + 1); } export async function getCreationTime(path: string) { // We first find the last merge commit that incorporates this file const mergeTime = getTimestamp( (await execAsyncWithRetry(`git log --merges --full-history --first-parent --format=%at "${path}"`)).stdout ); if (mergeTime !== undefined) { return mergeTime; } // If such merge commit does not exist, we will simply use the file creation time const creationTime = getTimestamp( (await execAsyncWithRetry(`git log --format=%at --follow "${path}"`)).stdout ); if (creationTime !== undefined) { return creationTime; } return 0; }
kink/kat
src/builder/getCreationTime.ts
TypeScript
unknown
976
import { relative } from 'path'; import { rootDir } from './dirs'; import * as colorworks from 'colorworks'; const cw = colorworks.create(); const notLastIndent = cw.compile('[[gray| │ ]]'); const lastIndent = cw.compile('[[gray| ├─╴]]'); let indentation = 0; export function indent() { indentation++; } export function dedent() { indentation--; } export function log(msg?: string) { if (msg === undefined) { console.info(); return; } console.info(notLastIndent.repeat(Math.max(0, indentation - 1)) + (indentation > 0 ? lastIndent : '') + cw.compile(msg)); } /** Format path */ export function fPath(path: string) { return relative(rootDir, path).replace(/\\/g, '/'); }
kink/kat
src/builder/indentConsole.ts
TypeScript
unknown
706
import { createHash } from 'crypto'; import { readFileSync } from 'fs'; import { copy, ensureDir, readFile, writeFile } from 'fs-extra'; import { stringify } from 'javascript-stringify'; import { join, resolve } from 'path'; import { Data, Folder, Node } from '../Data'; import { TagSpec, TagsSpec } from '../TagsSpec'; import { chaptersDir, distChaptersDir, distDir, rootDir, staticDir, tagsSpec } from './dirs'; import { ErrorReporter } from './ErrorReporter'; import { log } from './indentConsole'; import { LoaderContext } from './LoaderContext'; import { load } from './loaders/Loader'; import { Stats } from './Stats'; import { loadTagsSpec, validateAndBuildTagMap } from './tagsSpecParser'; import {execAsyncWithRetry} from './execAsyncWithRetry'; import chokidar = require('chokidar'); import yargs = require('yargs'); const argv = yargs.options({ production: { type: 'boolean', default: false }, suppressError: { type: 'boolean', default: false, alias: 'suppress-error' }, watch: { type: 'boolean', default: false, alias: 'w' }, }).argv; if (!argv.watch) { build(null).catch(error => console.error(error)); } else { const watcher = chokidar.watch([chaptersDir, tagsSpec], { awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 60, }, }); let building = false; const buildFiles = new Set<string>(); const scheduleBuild = (path: string) => { buildFiles.add(path); if (building) { return; } building = true; (async () => { while (buildFiles.size > 0) { const toBeBuilt = [...buildFiles]; buildFiles.clear(); log(`[[green|Building [[yellow|${toBeBuilt.length}]] changed files...]]`); await build(toBeBuilt); } building = false; })().catch(error => console.error(error)); }; watcher.on('add', scheduleBuild); watcher.on('change', scheduleBuild); watcher.on('unlink', scheduleBuild); } const nodeCache = new Map<string, Node>(); async function readBuildNumber() { try { return (await execAsyncWithRetry(`git rev-list --count HEAD`)).stdout; } catch (error: any) { log(error); return 'Unknown'; } } async function build(buildFiles: Array<string> | null) { const errorReporter = new ErrorReporter(); const startTime = Date.now(); await ensureDir(distChaptersDir); // Load tags spec let tagsSpec: null | TagsSpec = null; let tagsMap: null | ReadonlyMap<string, TagSpec> = null; let tagAliasMap: null | ReadonlyMap<string, string> = null; try { tagsSpec = await loadTagsSpec(); ({ tagAliasMap, tagsMap } = await validateAndBuildTagMap(tagsSpec)); } catch (error) { errorReporter.wrapAndReportError('Failed to load tags spec.', error as Error); } if (tagsSpec !== null) { await writeFile( resolve(distDir, 'tagsSpec.json'), JSON.stringify(tagsSpec, null, argv.production ? 0 : 2), ); } const stats = new Stats(argv.production); const rootLoaderCtx = new LoaderContext( true, chaptersDir, '', stats, argv.production, errorReporter, tagsMap, buildFiles, nodeCache, ); const data: Data = { chapterTree: await load(rootLoaderCtx)! as Folder, charsCount: argv.production ? stats.getCharsCount() : null, paragraphsCount: stats.getParagraphCount(), keywordsCount: [...stats.getKeywordsCount()].sort((a, b) => b[1] - a[1]), buildNumber: await readBuildNumber(), authorsInfo: JSON.parse(await readFile(join(rootDir, 'authors.json'), 'utf8')), buildError: errorReporter.hasError(), tags: tagsSpec === null ? [] : tagsSpec .sort((a, b) => b.priority - a.priority) .map(tagSpec => [ tagSpec.tag, tagSpec.variants, ]), tagAliases: Array.from(tagAliasMap ?? []), }; await writeFile( resolve(distDir, 'data.js'), `window.DATA=${stringify(data, null, argv.production ? 0 : 2, { skipUndefinedProperties: true })};`, ); log('[[green|data.js created.]]'); // Copy static await copy(staticDir, distDir); const indexPath = resolve(distDir, 'index.html'); let result = await readFile(indexPath, 'utf8'); const hash = (path: string) => createHash('sha256') .update(readFileSync(resolve(distDir, path))) .digest('hex') .substr(0, 12); result = result.replace(/<script src="(.*?)" defer><\/script>/g, (_, path) => { return `<script src="${path}?hash=${hash(path)}" defer></script>`; }); result = result.replace(/<link rel="stylesheet" type="text\/css" href="(.*?)">/g, (_, path) => { return `<link rel="stylesheet" type="text/css" href="${path}?hash=${hash(path)}">`; }); await writeFile(indexPath, result, 'utf8'); log('[[green|Static copied.]]'); log(`[[green|Time spent: [[cyan|${Date.now() - startTime}ms]].]]`); if (errorReporter.hasError()) { log(); errorReporter.printAll(); if (!argv.suppressError) { process.exit(1); } } }
kink/kat
src/builder/index.ts
TypeScript
unknown
5,079
export const keywords: Array<string> = [ '姓陈的', '老陈', '陈傻子', '陈变态', '陈同学', '陈好人', '陈志鹏', '陈智障', '陈沙雕', '陈绅士', '陈色狼', '陈骗子', '高潮', '按摩棒', '按摩器', '仙女棒', '贞操带', 'WTCD', '微积分', ];
kink/kat
src/builder/keywords.ts
TypeScript
unknown
345
import { Node } from '../../Data'; import { dedent, indent, log, fPath } from '../indentConsole'; import { LoaderContext, LoaderError } from '../LoaderContext'; import { folderLoader } from './folderLoader'; import { imageLoader } from './imageLoader'; import { markdownLoader } from './markdownLoader'; import { resourceLoader } from './resourceLoader'; import { wtcdLoader } from './wtcdLoader'; export interface Loader { name: string; canLoad(ctx: LoaderContext): Promise<boolean>; isInBuildFiles(ctx: LoaderContext, buildFiles: Array<string>): boolean; load(ctx: LoaderContext): Promise<Node | null>; } const loaders: Array<Loader> = [ folderLoader, markdownLoader, wtcdLoader, resourceLoader, imageLoader, ]; export async function load(ctx: LoaderContext) { for (const loader of loaders) { if (await loader.canLoad(ctx)) { if (ctx.buildFiles !== null && !loader.isInBuildFiles(ctx, ctx.buildFiles)) { return ctx.getLastSuccess(); } log(`[[green|Load [[yellow|${fPath(ctx.path)}]] with [[cyan|${loader.name}]].]]`); let result; indent(); try { result = await loader.load(ctx); } catch (error) { ctx.pushError(new LoaderError(loader.name, ctx.path, error)); result = null; } finally { dedent(); } if (result === null) { ctx.removeCache(); } else { ctx.updateCache(result); } return result; } } return null; }
kink/kat
src/builder/loaders/Loader.ts
TypeScript
unknown
1,481
import { readdir, readFile } from 'fs-extra'; import { resolve } from 'path'; import { FolderMeta, Node } from '../../Data'; import { LoaderContext } from '../LoaderContext'; import { load, Loader } from './Loader'; function byDisplayIndex(a: Node, b: Node) { const largestCommonIndex = Math.min(a.displayIndex.length, b.displayIndex.length); for (let i = 0; i < largestCommonIndex; i++) { const diff = a.displayIndex[i] - b.displayIndex[i]; if (diff !== 0) { return diff; } } return a.displayIndex.length - b.displayIndex.length; } export const folderLoader: Loader = { name: 'Folder Loader', async canLoad(ctx: LoaderContext) { return ctx.isDirectory; }, isInBuildFiles(ctx: LoaderContext, buildFiles: Array<string>) { return buildFiles.some(path => path.startsWith(ctx.path)); }, async load(ctx: LoaderContext): Promise<Node | null> { const node = ctx.getNode(); ctx.setDistFileName(node.displayName); const names = await readdir(ctx.path); const children: Array<Node> = []; let meta: FolderMeta = {}; for (const name of names) { if (name === 'meta.json') { meta = JSON.parse(await readFile(resolve(ctx.path, name), 'utf8')); } else { const child = await load(await ctx.derive(resolve(ctx.path, name))); if (child !== null) { children.push(child); } } } children.sort(byDisplayIndex); let charsCount: number | null = 0; for (const child of children) { if (child.charsCount === null) { charsCount = null; break; } charsCount += child.charsCount; } return { ...meta, ...node, type: 'folder', children, charsCount, }; }, };
kink/kat
src/builder/loaders/folderLoader.ts
TypeScript
unknown
1,750
import { copyFile, mkdirp } from 'fs-extra'; import { basename, dirname, resolve } from 'path'; import { distChaptersDir } from '../dirs'; import { isCompressibleImage } from '../../fileExtensions'; import { fPath, log } from '../indentConsole'; import { LoaderContext } from '../LoaderContext'; import { Loader } from './Loader'; import sharp = require('sharp'); const LOW_RESOLUTION_WIDTH = 720; export const imageLoader: Loader = { name: 'Image Loader', async canLoad(ctx: LoaderContext) { return !ctx.isDirectory && isCompressibleImage(ctx.path); }, isInBuildFiles(ctx: LoaderContext, buildFiles: Array<string>) { return buildFiles.includes(ctx.path); }, async load(ctx: LoaderContext): Promise<null> { ctx.setDistFileName(basename(ctx.path)); const targetRelativePath = ctx.getDistRelativePath(); const targetPath = resolve(distChaptersDir, targetRelativePath); await mkdirp(dirname(targetPath)); const fullResolutionPath = targetPath.replace(/\.([^.]+)$/, '.full.$1'); await copyFile(ctx.path, fullResolutionPath); log(`[[green|Copied to [[yellow|${fPath(fullResolutionPath)}]].]]`); if ((await sharp(ctx.path).metadata()).width! <= LOW_RESOLUTION_WIDTH) { await copyFile(ctx.path, targetPath); log(`[[green|Copied to [[yellow|${fPath(targetPath)}]].]]`); } else { await sharp(ctx.path).resize(LOW_RESOLUTION_WIDTH).toFile(targetPath); log(`[[green|Resized to [[yellow|${fPath(targetPath)}]].]]`); } return null; }, };
kink/kat
src/builder/loaders/imageLoader.ts
TypeScript
unknown
1,520
import { mkdirp, writeFile } from 'fs-extra'; import { dirname } from 'path'; import { AuthorRole, ChapterFlags, ChapterFlagsMapped, MarkdownChapter } from '../../Data'; import { fPath, log } from '../indentConsole'; import { LoaderContext } from '../LoaderContext'; import { Loader } from './Loader'; import { parseAuthorSpecifier } from './parseAuthorSpecifier'; import { parseTagSpecifier } from './parseTagSpecifier'; const markdownFlags = new Map<string, ChapterFlags>([ ['# 编写中', 'isEarlyAccess'], ['# 隐藏', 'hidden'], ['# 已弃坑', 'abandoned'], ]); function readMarkdownFlags(markdown: string): [string, ChapterFlagsMapped] { const flagsMapped: ChapterFlagsMapped = {}; let changed; do { changed = false; markdown = markdown.trimLeft(); for (const [keyword, flag] of markdownFlags) { if (markdown.startsWith(keyword)) { changed = true; flagsMapped[flag] = true; markdown = markdown.substr(keyword.length); } } } while (changed); return [markdown, flagsMapped]; } function loadProperty(markdown: string, key: string) { markdown = markdown.trimLeft(); if (markdown.startsWith('- ')) { markdown = markdown.substr(2).trimLeft(); } if (!markdown.startsWith(`${key}:`)) { return { markdown, value: null }; } const lineBreakIndex = markdown.indexOf('\n'); const value = markdown.substring(key.length + 1, lineBreakIndex).trim(); markdown = markdown.substr(lineBreakIndex).trimLeft(); return { markdown, value }; } export const markdownLoader: Loader = { name: 'Markdown Loader', async canLoad(ctx: LoaderContext) { return !ctx.isDirectory && ctx.path.endsWith('.md'); }, isInBuildFiles(ctx: LoaderContext, buildFiles: Array<string>) { return buildFiles.includes(ctx.path); }, async load(ctx: LoaderContext): Promise<MarkdownChapter> { let markdown = (await ctx.readFile()).trimLeft(); let authors: Array<AuthorRole> = []; let authorSpecifier: string | null; ({ markdown, value: authorSpecifier } = loadProperty(markdown, '作者')); if (authorSpecifier !== null) { authors = parseAuthorSpecifier(authorSpecifier); } let tags: Array<string> | undefined; let tagSpecifier: string | null; ({ markdown, value: tagSpecifier } = loadProperty(markdown, '标签')); if (tagSpecifier !== null) { tags = parseTagSpecifier(tagSpecifier, tag => ctx.isTagValid(tag)); } let chapterFlagsMapped: ChapterFlagsMapped; [markdown, chapterFlagsMapped] = readMarkdownFlags(markdown); const chapterCharCount = ctx.stats.processMarkdown(markdown); const node = ctx.getNode(); log(`[[green|Use display name [[yellow|${fPath(node.displayName)}]].]]`); ctx.setDistFileName(node.displayName + '.html'); const mdi = ctx.createMDI(); const output = mdi.render(markdown); const creationTime = await ctx.getCreationTime(); ctx.stats.processHtml(output); const htmlPath = ctx.getDistFullPath(); await mkdirp(dirname(htmlPath)); await writeFile(htmlPath, output); log(`[[green|Rendered to [[yellow|${fPath(htmlPath)}]].]]`); return { ...node, ...chapterFlagsMapped, type: 'Markdown', creationTime, htmlRelativePath: ctx.getDistRelativePath(), authors, tags, charsCount: chapterCharCount, }; } };
kink/kat
src/builder/loaders/markdownLoader.ts
TypeScript
unknown
3,374
import { AuthorRole } from '../../Data'; export function parseAuthorSpecifier(specifier: string): Array<AuthorRole> { return [...specifier.matchAll(/(?<=,|^)(.+?)(?:((.+?)))?(?=$|,)/g)] .map(match => ({ name: match[1], role: match[2] ?? '作者' })); }
kink/kat
src/builder/loaders/parseAuthorSpecifier.ts
TypeScript
unknown
268
export function parseTagSpecifier(tagSpecifier: string, tagVariantValidator: (tag: string) => boolean): Array<string> { const tagVariants = tagSpecifier.split(','); for (const tagVariant of tagVariants) { if (!tagVariantValidator(tagVariant)) { throw new Error(`Invalid tag: "${tagVariant}".`); } } return tagVariants; }
kink/kat
src/builder/loaders/parseTagSpecifier.ts
TypeScript
unknown
345
import { copyFile, mkdirp } from 'fs-extra'; import { basename, dirname, resolve } from 'path'; import { distChaptersDir } from '../dirs'; import { isResource } from '../../fileExtensions'; import { fPath, log } from '../indentConsole'; import { LoaderContext } from '../LoaderContext'; import { Loader } from './Loader'; export const resourceLoader: Loader = { name: 'Resource Loader', async canLoad(ctx: LoaderContext) { return !ctx.isDirectory && isResource(ctx.path); }, isInBuildFiles(ctx: LoaderContext, buildFiles: Array<string>) { return buildFiles.includes(ctx.path); }, async load(ctx: LoaderContext): Promise<null> { ctx.setDistFileName(basename(ctx.path)); const targetRelativePath = ctx.getDistRelativePath(); const targetPath = resolve(distChaptersDir, targetRelativePath); await mkdirp(dirname(targetPath)); await copyFile(ctx.path, targetPath); log(`[[green|Copied to [[yellow|${fPath(targetPath)}]].]]`); return null; }, };
kink/kat
src/builder/loaders/resourceLoader.ts
TypeScript
unknown
993
import { mkdirp, pathExists, readFile, writeFile } from 'fs-extra'; import { dirname, parse as parsePath, resolve } from 'path'; import { Chapter } from '../../Data'; import { parse } from '../../wtcd/parse'; import { WTCDParseResult } from '../../wtcd/types'; import { dedent, fPath, indent, log } from '../indentConsole'; import { LoaderContext, LoaderError } from '../LoaderContext'; import { Loader } from './Loader'; import { parseAuthorSpecifier } from './parseAuthorSpecifier'; export const wtcdLoader: Loader = { name: 'WTCD Loader', async canLoad(ctx: LoaderContext) { return !ctx.isDirectory && ctx.path.endsWith('.wtcd'); }, isInBuildFiles(ctx: LoaderContext, buildFiles: Array<string>) { return buildFiles.includes(ctx.path); }, async load(ctx: LoaderContext): Promise<Chapter> { const parsedPath = parsePath(ctx.path); const metaPath = resolve(parsedPath.dir, parsedPath.name + '.meta.json'); const meta: any = { isEarlyAccess: false, hidden: false, authors: [], preferredReader: 'flow', }; if (await pathExists(metaPath)) { const content = JSON.parse(await readFile(metaPath, 'utf8')); if (typeof content.isEarlyAccess === 'boolean') { meta.isEarlyAccess = content.isEarlyAccess; } if (typeof content.hidden === 'boolean') { meta.hidden = content.hidden; } if (typeof content.preferredReader === 'string') { if (content.preferredReader === 'game') { if (typeof content.slideAnimation === 'boolean') { meta.slideAnimation = content.slideAnimation; } else { meta.slideAnimation = true; } } else if (content.preferredReader !== 'flow') { throw new Error(`Unknown reader type: ${content.preferredReader}.`); } meta.preferredReader = content.preferredReader; } if (typeof content.authors === 'string') { meta.authors = parseAuthorSpecifier(content.authors); } } const source = await ctx.readFile(); const node = ctx.getNode(); log(`[[green|Use display name [[yellow|${fPath(node.displayName)}]].]]`); ctx.setDistFileName(node.displayName + '.html'); const mdi = ctx.createMDI(); const creationTime = await ctx.getCreationTime(); const htmlPath = ctx.getDistFullPath(); await mkdirp(dirname(htmlPath)); let chapterCharCount: number | null = 0; log(`[[green|Start parsing WTCD for [[yellow|${fPath(ctx.path)}]].]]`); const logger = { info(msg: string): void { log(`[[green|${msg}]]`); }, error(msg: string): void { log(`[[red|this.prefix ${msg}]]`); }, warn(msg: string): void { log(`[[yellow|this.prefix ${msg}]]`); } }; let wtcdParseResult: WTCDParseResult; indent(); try { wtcdParseResult = parse({ source, mdi, logger, sourceMap: !ctx.production, markdownPreProcessor: markdown => { const deltaChars = ctx.stats.processMarkdown(markdown); if (deltaChars !== null && chapterCharCount !== null) { chapterCharCount += deltaChars; } else { chapterCharCount = null; } return markdown; }, htmlPostProcessor: html => { ctx.stats.processHtml(html); return html; }}); } finally { dedent(); } if (wtcdParseResult.error) { log(`[[red|WTCD parsing has errored: [[cyan|${wtcdParseResult.message}]].]]`); ctx.pushError(new LoaderError(wtcdLoader.name, ctx.path, wtcdParseResult.internalStack)); } await writeFile(htmlPath, JSON.stringify(wtcdParseResult)); log(`[[green|Parsed result written to [[yellow|${fPath(htmlPath)}]].]]`); return { ...node, ...meta, type: 'WTCD', creationTime, htmlRelativePath: ctx.getDistRelativePath(), charsCount: chapterCharCount, }; }, };
kink/kat
src/builder/loaders/wtcdLoader.ts
TypeScript
unknown
3,921
import { readFile } from 'fs-extra'; import { TagSpec, TagSpecDescLineSegment, TagsSpec } from '../TagsSpec'; import { tagsSpec } from './dirs'; function parseTagsSpec(content: string): TagsSpec { // Replace all line breaks with \n content = content.replace(/\r\n|\r|\n/g, '\n'); // Extract all tags // Group 1: tag // Group 2: variants // Group 3: exclamation marks // Group 4: desc block return Array.from(content.matchAll(/([^\n]+?)(?:(([^\n]+?)))?(!*)\n((?:[^\n]+\n)*)/g)) .map(tagMatch => { const tag = tagMatch[1]; const variants = (tagMatch[2] === undefined) ? null : tagMatch[2].split('/'); const priority = tagMatch[3].length; const aliases: Array<string> = []; const desc = tagMatch[4] .split('\n') .map(line => line.trim()) .filter(line => line !== '') .map(line => { let isPrerequisite = false; if (line.startsWith('+')) { isPrerequisite = true; line = line.substr(1); } if (line.startsWith('=')) { aliases.push(...line.substr(1).split(',')); return { isPrerequisite: false, segments: [{ type: 'text' as 'text', content: `同义词:${line.substr(1)}`, }], }; } // Group 1: text // Group 2: reference const segments: Array<TagSpecDescLineSegment> = Array.from(line.matchAll(/([^【]+)|【(.+?)】/g)) .map(segmentMatch => { if (segmentMatch[1] !== undefined) { // text return { type: 'text', content: segmentMatch[1], }; } else { return { type: 'reference', tag: segmentMatch[2], }; } }); return { isPrerequisite, segments, }; }); return { variants, tag, priority, desc, aliases, }; }); } export async function loadTagsSpec() { const content = await readFile(tagsSpec, 'utf8'); return parseTagsSpec(content); } export function validateAndBuildTagMap(tagsSpec: TagsSpec) { const tagAliasMap = new Map<string, string>(); const tagsMap = new Map<string, TagSpec>(); tagsSpec.forEach(tagSpec => { if (tagsMap.has(tagSpec.tag)) { throw new Error(`Duplicated tag specification for tag "${tagSpec.tag}".`); } tagsMap.set(tagSpec.tag, tagSpec); }); // Reference check tagsSpec.forEach(tagSpec => { tagSpec.desc.forEach(descLine => { descLine.segments.forEach(segment => { if (segment.type === 'reference') { if (!tagsMap.has(segment.tag)) { throw new Error(`Invalid tag reference to "${segment.tag}" from tag "${tagSpec.tag}".`); } const referencedTag = tagsMap.get(segment.tag)!; if (descLine.isPrerequisite && tagSpec.variants !== null && referencedTag.variants !== null) { // This tag and its prerequisite has variants. for (const variant of tagSpec.variants) { if (!referencedTag.variants.includes(variant)) { throw new Error(`Tag "${tagSpec.tag}"'s prerequisite "${referencedTag.tag}" lacks variant "${variant}".`); } } } } }); }); tagSpec.aliases.forEach(alias => { if (/\s/.test(alias)) { throw new Error(`Tag "${tagSpec.tag}" has invalid alias "${alias}".`); } if (tagAliasMap.has(alias)) { throw new Error(`Tag "${tagSpec.tag}" tries to define alias "${alias}", but the same alias was already defined by tag "${tagAliasMap.get(alias)}".`); } tagAliasMap.set(alias, tagSpec.tag); }); }); return { tagAliasMap, tagsMap }; }
kink/kat
src/builder/tagsSpecParser.ts
TypeScript
unknown
3,940
const resourceExtensions = ['.pdf', '.svg']; export function isResource(path: string) { return resourceExtensions.some(extension => path.endsWith(extension)); } const compressibleImageExtensions = ['.png', '.jpg']; export function isCompressibleImage(path: string) { return compressibleImageExtensions.some(extension => path.endsWith(extension)); } const documentExtensions = ['html']; export function isDocument(path: string) { return documentExtensions.some(extension => path.endsWith(extension)); }
kink/kat
src/fileExtensions.ts
TypeScript
unknown
510
import { readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; import { mirrorSites } from './web/constant/mirrorSites'; import { thanks } from './web/constant/thanks'; import { padName } from './web/util/padName'; let content = readFileSync(join(__dirname, '..', 'readmeTemplate.md'), 'utf8'); content = content.replace( '☆☆☆☆☆【占位:镜像站列表】☆☆☆☆☆', mirrorSites.map(({ origin, provider }, index) => `- [镜像站 ${index + 1} | ${/^https?:\/\/(.*)$/.exec(origin)![1]}(感谢${padName(provider)}提供)](${origin})`).join('\n') ); content = content.replace( '☆☆☆☆☆【占位:鸣谢列表】☆☆☆☆☆', thanks.map(({ name, link }) => (link === undefined) ? `- ${name}` : `- [${name}](${link})` ).join('\n'), ); writeFileSync(join(__dirname, '..', 'Readme.md'), content, 'utf8');
kink/kat
src/generateReadme.ts
TypeScript
unknown
872
declare module 'markdown-it-replace-link'; declare module 'markdown-it-ruby'; declare module 'colorworks'; declare module 'unistring'; interface ArrayConstructor { isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any> } type Remap<TElement> = { [TKey in keyof TElement]?: TElement[TKey] extends string ? (string | Array<string>) : TElement[TKey] extends CSSStyleDeclaration ? Partial<CSSStyleDeclaration> : TElement[TKey]; } declare namespace JSX { type Element = HTMLElement; type IntrinsicElements = { [K in keyof HTMLElementTagNameMap]: Remap<HTMLElementTagNameMap[K]>; } & { [K in keyof HTMLElementDeprecatedTagNameMap]: Remap<HTMLElementDeprecatedTagNameMap[K]>; } }
kink/kat
src/global.d.ts
TypeScript
unknown
730
@import (reference) 'common/button.less'; .content-container>.content .authors { >.outer-container { display: flex; flex-wrap: wrap; margin: -0.5em -0.5em 0.3em -0.5em; >div:extend(#common.button all) { display: flex; margin: 0.5em !important; padding: 1em !important; @media (min-width: 1651px) { flex: 1 0 calc(100% - 1em); } @media (min-width: 801px) and (max-width: 1650px) { flex: 1 0 calc((100% - 3em) / 3); max-width: calc((100% - 3em) / 3); } @media (min-width: 501px) and (max-width: 800px) { flex: 1 0 calc((100% - 2em) / 2); max-width: calc((100% - 2em) / 2); } @media (max-width: 500px) { flex: 0 1 100%; } } >.author-container { text-align: left; >.avatar { flex: 0 0; width: 44px; height: 44px; margin-right: 1em; border-radius: 3px; } >.author-role-container { flex: 1; >.role { pointer-events: none; opacity: 0.6; font-size: 0.8em; } >.name { margin-top: 0.1em; font-size: 1.2em; } } } >.reprint { display: flex; align-items: center; justify-content: center; >div { font-size: 1.5em; } } } }
kink/kat
src/style/authors.less
CSS
unknown
1,374
body { overflow: hidden; margin: 0; } ::-webkit-scrollbar-thumb { background-color: var(--paper-bg-color); } .rect { background-color: var(--rect-bg-color); }
kink/kat
src/style/body.less
CSS
unknown
168
@import (reference) 'common/button.less'; .button-container { >div:extend(#common.button all), >a:extend(#common.button all) { flex-grow: 1; margin: 0.4em !important; word-break: keep-all; &.rich { body.animation-enabled & { transition: background-color 0.3s, box-shadow 0.3s, color 0.3s; } &.disabled { color: var(--key-opacity-05); background-color: var(--key-opacity-004); box-shadow: none; } &.selected { border: white 0.2em; background-color: var(--button-color); box-shadow: rgba(0,0,0,0) 0 0 0, 0 0 0 2px var(--key) inset; } } } & { display: flex; flex-wrap: wrap; margin: -0.4em; } }
kink/kat
src/style/buttonContainer.less
CSS
unknown
729
@import (reference) 'common/layerCard.less'; @import (reference) 'common/button.less'; .content-container>.content .content-block.comments { >p { margin-bottom: 0; } >.create-comment:extend(#common.button all) { margin-top: 2vh; font-size: 2em; line-height: 1em; } >.comment:extend(#common.layer-card all) { position: relative; margin-top: 2vh; >.avatar { width: 44px; height: 44px; border-radius: 3px; } >.author { position: absolute; top: 3vh; left: calc(44px + 4.5vh); font-size: 1.15em; } >.time { position: absolute; top: calc(3vh + 2.3em); left: calc(44px + 4.5vh); font-size: 0.7em; } >p { margin-bottom: 0; } body.animation-enabled &>.action { transition: background-color 0.12s linear, opacity 0.12s linear; } >.action { float: right; padding: 5px 10px; cursor: pointer; opacity: 0.8; border-radius: 3px; } >.action:hover { background-color: var(--key-opacity-01); } >.action:active { background-color: var(--key-opacity-05); } } }
kink/kat
src/style/comment.less
CSS
unknown
1,172
@import (reference) 'common/layerCard.less'; #common.button:extend(#common.layer-card all) { position: relative; padding: 1em 1.2em !important; user-select: none; text-align: center; &::before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; content: ''; cursor: pointer; opacity: 0; background-color: var(--key); body.animation-enabled & { transition: opacity 0.12s; } } &:hover::before { opacity: 0.06; } &:active::before { opacity: 0.04; } &.disabled::before { cursor: default; opacity: 0; } }
kink/kat
src/style/common/button.less
CSS
unknown
614
#common.layer-card { overflow: hidden; padding: 3vh; border-radius: 5px; background-color: var(--comment-color); box-shadow: rgba(0,0,0,0.24) 0 1.01372px 2.32903px; }
kink/kat
src/style/common/layerCard.less
CSS
unknown
179
@import './variables.less'; #common.material-content { color: var(--key); background-color: var(--paper-bg-color); font-family: var(--font-family); >:first-child, >:first-child>:first-child, >:first-child>:first-child>:first-child { margin-top: 0; } >:last-child, >:last-child>:last-child, >:last-child>:last-child>:last-child { margin-bottom: 0; } @media (min-width: 901px) { padding: @material-content-regular-padding; } @media (max-width: 900px) { padding: 1em; } code { cursor: text; font-family: var(--font-family-mono); font-size: 1em; } :not(pre)>code { margin: 0; padding: 0.12em 0.3em; word-break: break-all; border-radius: 3px; background-color: var(--key-opacity-007); } pre { overflow-x: auto; padding: 2em; border-radius: 0.8em; background-color: var(--key-opacity-007); } pre.wrapping { white-space: normal; } blockquote { margin: 0; opacity: 0.6; font-style: italic; } a.regular, span.anchor-style { cursor: pointer; color: var(--link-color); &:hover { color: var(--link-hover-color); } &:active { color: var(--link-active-color); } } a.dimmed { margin-top: 2em; opacity: 0.45; body.animation-enabled & { transition: opacity 0.12s; } &:hover { opacity: 0.75; } } }
kink/kat
src/style/common/materialContent.less
CSS
unknown
1,395
@import (reference) 'common/materialContent.less'; @import (reference) 'common/button.less'; @import 'variables.less'; .content-container>.content { .content-block:extend(#common.material-content all) { body.animation-enabled & { transition: max-width 0.5s, background-color 0.3s, color 0.3s; } @media (min-width: 901px) { border-radius: 6px; box-shadow: rgba(0,0,0,0.12) 0 0.55009px 2.4261px, rgba(0,0,0,0.24) 0 1.01372px 2.32903px; } &.warning { background-color: var(--content-block-warning-color); } .page-switcher { display: flex; margin-top: 2vh; >a:extend(#common.button all) { flex: 1; text-align: center; } a+a { margin-left: 0.8em; } } } >.left-side-container, >.right-side-container { @media (min-width: 1651px) { position: absolute; top: 0; width: @side-block-width; &.left-side-container { left: calc((100vw - @content-block-width) / 2 - @side-block-width - @block-spacing); } &.right-side-container { right: calc((100vw - @content-block-width) / 2 - @side-block-width - @block-spacing); } .content-block { padding: @side-block-padding; } } @media (min-width: 901px) { .content-block { margin-bottom: 1.7vw; } } } >div { @media (min-width: 901px) { width: @content-block-width; max-width: 100%; margin: 1.7vw auto @block-spacing auto; body.layout-side & { max-width: calc(100vw - 50vh - 6vw); } body.layout-main & { max-width: calc(100vw - 6vw); } } @media (max-width: 900px) { width: 100vw; } } >.slide-container { position: relative; >.height-holder { body.animation-enabled & { transition: height 0.5s; } } &.in-transition>.content-block { position: absolute; left: 0; } >.content-block { width: 100%; body.animation-enabled & { transition: left 0.5s; }; &.left { left: -100vw !important; } &.right { left: 100vw !important; } } } }
kink/kat
src/style/content.less
CSS
unknown
2,206
@import 'variables.less'; .content-container { position: fixed; z-index: 2; overflow-x: hidden; height: 100%; outline: none; body.animation-enabled & { transition: width 0.5s, left 0.5s, top 0.5s; } body.layout-off & { top: 100vh; left: 0; width: 100%; } body.layout-main & { top: @navbar-height; left: 0; width: 100%; height: calc(100% - @navbar-height); } body.layout-side & { @media (min-width: 901px) { top: 0; left: 50vh; width: calc(100vw - 50vh); } @media (max-width: 900px) { top: 100vh; } } >.content { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; width: 100%; height: 100%; outline: none; body.animation-enabled & { // transition: transform 5s linear; transition: left 0.5s; } &.left { // transform: translateX(-1000px); left: -100vw; } &.right { // transform: translateX(1000px); left: 100vw; } } }
kink/kat
src/style/contentContainer.less
CSS
unknown
1,034
div { box-sizing: border-box; } a { text-decoration: none; color: inherit; } p { line-height: 1.6em; } li { line-height: 1.6em; } @media (max-width: 900px) { li { margin-left: -0.8em; } } img { width: 100%; border-radius: 6px; } h1 { font-size: 2.2em; } h2 { font-size: 1.8em; } h3 { font-size: 1.55em; } h4 { font-size: 1.4em; } h5 { font-size: 1.25em; } h6 { font-size: 1.1em; } @less-margin: 0.6em; @more-margin: 0.8em; h1, h2, h3, h4, h5, h6 { margin-top: @more-margin; margin-bottom: @less-margin; } p, :not(li)>ul, :not(li)>ol { margin-top: @less-margin; margin-bottom: @more-margin; }
kink/kat
src/style/generic.less
CSS
unknown
637
.hint { position: fixed; z-index: 4; top: 10%; left: 50%; padding: 0.7em 0.9em; transform: translateX(-50%); text-align: center; opacity: 1; color: white; border-radius: 8px; background-color: rgba(0, 0, 0, 0.5); font-size: 1.2em; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); ; body.animation-enabled & { transition: opacity 0.3s; } }
kink/kat
src/style/hint.less
CSS
unknown
407
@import 'legacy.less'; @import 'menu.less'; @import 'rect.less'; @import 'body.less'; @import 'contentContainer.less'; @import 'content.less'; @import 'comment.less'; @import 'nsfwWarning.less'; @import 'modal.less'; @import 'buttonContainer.less'; @import 'wtcdGame.less'; @import 'hint.less'; @import 'input.less'; @import 'table.less'; @import 'generic.less'; @import 'visitCount.less'; @import 'authors.less'; @import 'wtcup.less'; @import 'navbar.less'; @import 'title.less'; @import 'mirrorSite.less'; @import 'taggingTool.less'; @import 'tag.less'; @import 'recommendedChapters.less'; @import 'preloader.less'; @import 'common/button.less'; @import 'common/layerCard.less'; @import 'common/materialContent.less';
kink/kat
src/style/index.less
CSS
unknown
721
.input-group { display: flex; margin-top: 0.6em; margin-bottom: 0.6em; >span { flex: 0; white-space: nowrap; } >input { flex: 1; min-width: 0; padding: 0.2em; color: var(--key); border: none; border-radius: 4px; outline: none; background-color: transparent; background-color: var(--comment-color); box-shadow: 0 1px 3px rgba(0,0,0,0.2) inset, 0 1px 2px rgba(0,0,0,0.3) inset; font-size: 1em; } } textarea.general { overflow-y: hidden; width: 100%; padding: 0.6em; resize: none; color: var(--key); border: none; border-radius: 4px; outline: none; background-color: var(--comment-color); box-shadow: 0 1px 3px rgba(0,0,0,0.2) inset, 0 1px 2px rgba(0,0,0,0.3) inset; font-family: var(--font-family); font-size: 1em; &.large { height: 120px; } &.small { height: 40px; } }
kink/kat
src/style/input.less
CSS
unknown
885
body.animation-enabled { transition: background-color 0.3s; } .display-none { display: none !important; } @keyframes moving-strips { 0% { transform: translateX(-283px); } 100% { transform: translateX(283px); } } // body.animation-enabled .rect { // transition: background-color 0.3s, width 0.5s, height 0.5s, top 0.5s, left 0.5s, transform 0.5s; // } // .rect { // position: fixed; // top: -50vmax; // left: 35vmax; // overflow: hidden; // width: 75vh; // height: 200vmax; // transform: rotate(40deg); // outline: none; // background-color: #555; // } // .rect.reading { // z-index: 1; // overflow-y: scroll; // -webkit-overflow-scrolling: touch; // } // body.animation-enabled .rect>div { // transition: background-color 0.3s, color 0.3s, opacity 0.5s; // } // .rect>div { // opacity: 0; // font-family: var(--font-family); // } @media (min-width: 901px) { // .rect.reading { // top: 0; // height: 100%; // transform: rotate(0); // } // .rect.reading.side { // left: 50vh; // width: calc(100vw - 50vh); // } // .rect.reading.main { // left: 0; // width: 100vw; // } .rect>div { margin: 2vw auto; padding: calc(1.8em + 1.2vw); border-radius: 6px; box-shadow: rgba(0,0,0,0.12) 0 0.55009px 2.4261px, rgba(0,0,0,0.24) 0 1.01372px 2.32903px; } .rect.side>div { width: 800px; max-width: calc(100vw - 50vh - 6vw); } .rect.main>div { width: 800px; max-width: calc(100vw - 6vw); } .rect.reading>div { opacity: 1; } } @media (max-width: 900px) { // .rect { // top: -30vmax; // width: 90vh; // transform: rotate(60deg); // } // .rect.reading:not(.side) { // top: 0; // left: 0; // width: 100vw; // height: 100%; // transform: none; // } .rect>div { width: 100vw; padding: 1em; } .rect.reading:not(.side)>div { opacity: 1; } } // .rect>div>:first-child, .rect>div>:first-child>:first-child, .rect>div>:first-child>:first-child>:first-child { // margin-top: 0; // } // .rect>div>:last-child, .rect>div>:last-child>:last-child, .rect>div>:last-child>:last-child>:last-child { // margin-bottom: 0; // } // .rect>.content code { // cursor: text; // font-family: var(--font-family-mono); // font-size: 1em; // } // .rect>.content :not(pre)>code { // margin: 0; // padding: 0.12em 0.3em; // word-break: break-all; // border-radius: 3px; // background-color: var(--key-opacity-007); // } // .rect>.content pre { // overflow-x: auto; // padding: 2em; // border-radius: 0.8em; // background-color: var(--key-opacity-007); // } // .rect>.content blockquote { // margin: 0; // opacity: 0.6; // font-style: italic; // } // .rect>.content blockquote>p { // margin-top: 0; // } // .rect>.comments>p { // margin-bottom: 0; // } // .rect>.comments>div { // margin-top: 2vh; // box-shadow: rgba(0,0,0,0.24) 0 1.01372px 2.32903px; // } // .rect>.comments>.create-comment { // user-select: none; // text-align: center; // font-size: 2em; // line-height: 1em; // } // body.animation-enabled .rect>.comments>.create-comment::before { // transition: opacity 0.12s; // } // .rect>.comments>.create-comment::before { // position: absolute; // top: 0; // left: 0; // width: 100%; // height: 100%; // content: ''; // cursor: pointer; // opacity: 0; // } // .rect>.comments>.create-comment:hover::before { // opacity: 0.1; // } // .rect>.comments>.create-comment:active::before { // opacity: 0.04; // } // .rect>.comments>div { // position: relative; // overflow: hidden; // padding: 3vh; // border-radius: 5px; // } // .rect>.comments>.comment>.avatar { // width: 44px; // height: 44px; // border-radius: 3px; // } // .rect>.comments>.comment>.author { // position: absolute; // top: 3vh; // left: calc(44px + 4.5vh); // font-size: 1.15em; // } // .rect>.comments>.comment>.time { // position: absolute; // top: calc(3vh + 2.3em); // left: calc(44px + 4.5vh); // font-size: 0.7em; // } // .rect>.comments>.comment>p { // margin-bottom: 0; // } .button { position: relative; display: inline-block; cursor: pointer; user-select: none; } .button:active { opacity: 0.6; } .button:active::after { opacity: 0.6; body.animation-enabled & { transition: background-color 0.3s; } } body.animation-enabled .button::after { transition: background-color 0.3s, transform 0.2s, transform-origin 0.2s; } .button::after { position: absolute; top: 102%; left: 0; width: 100%; height: 0.06em; content: ''; transform: scaleX(0); transform-origin: 20%; border-radius: 0.03em; will-change: transform; } .button:hover::after { transform: scaleX(1); transform-origin: 0; } @media (min-width: 901px) { ::-webkit-scrollbar { width: 18px; height: 18px; } ::-webkit-scrollbar-thumb { transition: border-width 0.5s; border: 5px solid rgba(0, 0, 0, 0); border-radius: 0.8em; background-clip: padding-box; } ::-webkit-scrollbar-thumb:hover { border-width: 3px; } } .wtcd-group-container+.wtcd-group-container::before { display: block; width: 100%; height: 1px; margin: 1.6em 0; content: ''; background-color: var(--key-opacity-05); } body.animation-enabled .wtcd-button.candidate::before, body.animation-enabled .wtcd-button.selected::before { transition: opacity 0.12s; } .wtcd-button.candidate::before, .wtcd-button.selected::before { position: absolute; top: 0; left: 0; width: 100%; height: 100%; content: ''; pointer-events: none; opacity: 0; background-color: var(--key); } .wtcd-button.candidate:hover::before, .wtcd-button.selected:hover::before { opacity: 0.1; } .wtcd-button.candidate:active::before, .wtcd-button.selected:active::before { opacity: 0.04; } body.animation-enabled .wtcd-button { transition: background-color 0.3s, box-shadow 0.3s, color 0.3s; } .wtcd-button { position: relative; overflow: hidden; margin: 0.8em 0; padding: 1em 1.2em; border-radius: 0.5em; } .wtcd-button.disabled { color: var(--key-opacity-05); background: repeating-linear-gradient(45deg, var(--key-opacity-004), var(--key-opacity-004) 15px, rgba(0,0,0,0) 15px, rgba(0,0,0,0) 30px); box-shadow: none; } .wtcd-button.candidate { cursor: pointer; background-color: var(--button-color); box-shadow: rgba(0,0,0,0.24) 0 1.01372px 2.32903px, 0 0 0 0 rgba(255,255,255,0) inset; } .wtcd-button.selected { cursor: pointer; border: white 0.2em; background-color: var(--button-color); box-shadow: rgba(0,0,0,0) 0 0 0, 0 0 0 2px var(--key) inset; } .wtcd-button.unselected { color: var(--key-opacity-05); background-color: var(--key-opacity-004); box-shadow: none; }
kink/kat
src/style/legacy.less
CSS
unknown
6,816
.menu-control, .menu { padding-left: 5vh; opacity: 1; color: var(--key); font-family: 'ZCOOL QingKe HuangYou', sans-serif; body.animation-enabled & { transition: color 0.3s, opacity 0.3s, transform 0.3s; } &.hidden { transform: translateX(-5vh); pointer-events: none; opacity: 0; } } .menu-control { position: fixed; top: 26vh; right: 0; left: 0; >.path, >.back { transform: scaleX(1.2); transform-origin: 0; } >.path { position: relative; height: 2vh; margin-bottom: 0.3vh; padding-left: 3.5vh; font-size: 2vh; line-height: 2vh; svg { position: absolute; width: 1vh; height: 1vh; transform: scale(2.6) translate(-0.8vh, 0.2vh); path { fill: var(--key); body.animation-enabled & { transition: fill 0.3s; } } } >span { display: inline-block; transform: translateX(0); body.animation-enabled & { transition: opacity 0.3s, transform 0.3s, left 0.3s; } span { opacity: 0.3; } span, a { margin-right: 0.4vh; } &.pre-entering { transform: translateX(10px); opacity: 0; } &.exiting { position: absolute; opacity: 0; &.first { body.animation-enabled & { transition: opacity 0.05s, transform 0.3s, left 0.3s; transition-delay: 5s, 0s, 0s; } } } } } >.back { margin: 0.8vh 0 0.8vh 0.5vh; font-size: 5vh; line-height: 5vh; &::before { position: absolute; top: 1vh; right: calc(100% + 0.8vh); content: '\25C0\FE0E'; font-size: 3vh; line-height: 3vh; } } } .menu { position: fixed; top: 35vh; right: 0; bottom: 2vh; left: 0; display: flex; align-content: flex-start; flex-direction: column; &.main { top: 28vh; >.flex { >div:not(.force-small), >a:not(.force-small) { margin: 0.4vh 0 0.8vh 0.5vh; font-size: 5vh; line-height: 5vh; &.button { .main.menu &::before { top: 1vh; right: calc(100% + 0.8vh); font-size: 3vh; line-height: 3vh; } } } } } @media (max-width: 900px) { overflow-y: auto; } @media (min-width: 901px) { overflow-x: auto; overflow-y: hidden; flex-wrap: wrap; } >.flex { transform: scaleX(1.2); transform-origin: 0; @media (max-width: 900px) { width: calc((100vw - 8vh) / 1.2); } @media (min-width: 901px) { max-width: 380px; margin-right: 120px; padding-right: 30px; } >div, >a { margin: 0.2vh 0 0.2vh 0.5vh; font-size: 3vh; line-height: 3.2vh; &.button { &::before { position: absolute; top: 0.5vh; right: calc(100% + 0.8vh); font-size: 2vh; line-height: 2vh; } } } .button.icon { &::before { transform: translate(0.4vh, 0.03em) scaleX(0.833); font-family: 'Material Icons'; font-size: 1.1em !important; } &.link::before { content: 'link'; } &.equalizer::before { content: 'equalizer'; } &.folder::before { content: 'folder_open'; } &.folder:hover::before { content: 'folder'; } &.file::before { content: 'insert_drive_file'; } &.game::before { content: 'games'; } &.notification::before { content: 'notifications_active'; } &.list::before { content: 'list'; } &.calender::before { content: 'today'; } &.history::before { content: 'history'; } &.clear::before { content: 'clear'; } &.person::before { content: 'person'; } &.icon-tag::before { content: 'sell'; } } .button.selectable::before { content: '>'; transform: translateX(-50%); opacity: 0; body.animation-enabled & { transition: opacity 0.3s, transform 0.3s; } } .button.selectable.selected::before { transform: none; opacity: 1; } .item-side { display: inline-block; opacity: 0.6; } .prepend .item-side { padding-right: 5px; } .append .item-side { padding-left: 5px; } } }
kink/kat
src/style/menu.less
CSS
unknown
4,535
.mirror-site-modal>.button-container>a { width: 100%; text-align: left; >h2 { margin: 0 0 0.2em 0; } p { margin: 0; line-height: 1.4em; } } .mirror-hint { position: fixed; right: 0.4em; bottom: 0.4em; opacity: 0.6; color: var(--key); >span { cursor: pointer; text-decoration: underline; } }
kink/kat
src/style/mirrorSite.less
CSS
unknown
341
@import (reference) 'common/materialContent.less'; // 所有和 Modal 相关的 CSS .modal-holder { >.modal-container { position: fixed; z-index: 3; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; opacity: 1; background-color: var(--key-opacity-01); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); body.animation-enabled & { transition: background-color 0.3s, opacity 0.3s; } >.modal:extend(#common.material-content all) { overflow-y: auto; width: 600px; max-width: 92vw; max-height: calc(100% - 8vw); transform: scale(1); border-radius: 6px; box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22); body.animation-enabled & { transition: transform 0.3s; } @media (max-width: 900px) { padding: 6vw !important; } &::-webkit-scrollbar-thumb { background-color: var(--rect-bg-color); } } &.closed { pointer-events: none; opacity: 0; >.modal { transform: scale(0); } } } }
kink/kat
src/style/modal.less
CSS
unknown
1,172
@import 'variables.less'; .navbar { position: fixed; z-index: 3; left: -10px; display: flex; overflow-y: hidden; align-items: center; width: calc(100% + 20px); height: @navbar-height; transform: translateY(calc(-@navbar-height - 10px)); white-space: pre; color: var(--key); background-color: var(--paper-bg-color); box-shadow: 0 2px 6px 2px rgba(0, 0, 0, 0.4); font-size: 1.2em; >.progress-indicator { position: absolute; left: 10px; width: calc(100% - 20px); height: @navbar-height; transform: scaleX(0); transform-origin: 0; pointer-events: none; opacity: 0.08; background-color: var(--key); body.animation-enabled & { transition: transform 0.2s, opacity 0.3s; } &.hidden { opacity: 0; } } &.flat { box-shadow: rgba(0,0,0,0.12) 0 0.55009px 2.4261px, rgba(0,0,0,0.24) 0 1.01372px 2.32903px; } >svg { flex-shrink: 0; width: 1.4em; height: 1.4em; margin-right: calc(0.3em); cursor: pointer; @media (min-width: 901px) { margin-left: calc(1rem + 1.2vw + 10px); } @media (max-width: 900px) { margin-left: calc(1rem + 10px); } path { fill: var(--key); } } >.title { margin-right: 0.3em; font-weight: bold; } .navbar-path-container-scroll { flex: 1; margin-left: -0.3em; @media (pointer: coarse) { overflow-x: auto; &::-webkit-scrollbar { width: 0; height: 0; } } @media (pointer: fine) { overflow-x: hidden; } .navbar-path-container { display: flex; >.arrow, >.anchor { transform: translateY(0); body.animation-enabled & { transition: transform 0.3s; } &.exiting { position: absolute; transform: translateY(-@navbar-height); } &.entering { transform: translateY(@navbar-height); } &:last-child { @media (min-width: 901px) { padding-right: calc(1rem + 1.2vw + 10px); } @media (max-width: 900px) { padding-right: calc(1rem + 10px); } } } >.arrow { padding-right: 0.3em; padding-left: 0.3em; opacity: 0.3; } } } body.animation-enabled & { transition: transform 0.5s, box-shadow 0.3s; } body.layout-main & { transform: translateY(0); } }
kink/kat
src/style/navbar.less
CSS
unknown
2,451
.nsfw-warning { position: fixed; z-index: 5; width: 100vw; height: 100%; cursor: pointer; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); body.animation-enabled & { transition: opacity 0.3s; } .warning-backdrop { position: fixed; left: -300px; width: calc(100vw + 600px); height: 100%; background: repeating-linear-gradient( 45deg, rgba(58, 58, 0, 0.85), rgba(58, 58, 0, 0.85) 200px, rgba(0, 0, 0, 0.85) 200px, rgba(0, 0, 0, 0.85) 400px ); body.animation-enabled & { animation: moving-strips 4s linear infinite; } } .warning-container { position: fixed; top: 50%; left: 50%; width: 800px; max-width: 85vw; margin: 0 auto; transform: translate(-50%, -50%); font-family: 'ZCOOL QingKe HuangYou', sans-serif; .title { margin-bottom: 2vh; text-align: center; color: yellow; font-size: 7vh; line-height: 7vh; } .content { margin-bottom: 2vh; text-align: center; color: white; font-size: 4vh; line-height: 1.2em; } .disable { text-align: center; color: #BBB; font-size: 3vh; line-height: 3vh; } } }
kink/kat
src/style/nsfwWarning.less
CSS
unknown
1,267
.preloader { >.preloader-paragraph, >.preloader-title { margin-top: 0.6em; margin-bottom: 1.2em; } >.preloader-title { .flash { height: 3.5em; } } >.preloader-paragraph { .flash { height: 1em; } } .flash-container { overflow-x: hidden; width: 100%; margin-bottom: 0.4em; >.flash { body.animation-enabled & { animation: flash 2s linear infinite; } width: 200%; background: linear-gradient( 90deg, var(--key-opacity-014) 0%, var(--key-opacity-023) 5%, var(--key-opacity-023) 8%, var(--key-opacity-014) 13%, var(--key-opacity-014) 50%, var(--key-opacity-023) 55%, var(--key-opacity-023) 58%, var(--key-opacity-014) 63% ); } } } @keyframes flash { 0% { transform: translateX(-50%); } 100% { transform: translateX(0); } }
kink/kat
src/style/preloader.less
CSS
unknown
916
@import (reference) 'common/button.less'; .recommended-chapters { li { margin-bottom: 0.4em; line-height: 1.4em; @media (min-width: 1651px) { margin-left: -0.8em; } } }
kink/kat
src/style/recommendedChapters.less
CSS
unknown
196
.rect-off-mobile() { top: -30vmax; left: 35vmax; width: 90vh; height: 200vmax; transform: rotate(60deg); } .rect { position: fixed; body.animation-enabled & { transition: background-color 0.3s, width 0.5s, height 0.5s, top 0.5s, left 0.5s, transform 0.5s; } body.layout-off & { @media (min-width: 901px) { top: -50vmax; left: 35vmax; width: 75vh; height: 200vmax; transform: rotate(40deg); } @media (max-width: 900px) { .rect-off-mobile(); } } body.layout-main & { top: 0; left: 0; width: 100vw; height: 100%; transform: rotate(0); } body.layout-side & { @media (min-width: 901px) { top: 0; left: 50vh; width: calc(100vw - 50vh); height: 100%; transform: rotate(0); } @media (max-width: 900px) { .rect-off-mobile(); } } }
kink/kat
src/style/rect.less
CSS
unknown
886
table { position: relative; margin: 1em 0; border-spacing: 0; color: inherit; } tbody>tr:nth-child(odd) { background-color: var(--key-opacity-01); } td, th { line-height: 1.6em; } th { position: sticky; top: 0; white-space: nowrap; background-color: var(--paper-bg-color); line-height: 2.0; } @media (min-width: 901px) { td, th { padding: 0 1em; } } @media (max-width: 900px) { table { width: 100%; } td, th { padding: 0 0.2em; } }
kink/kat
src/style/table.less
CSS
unknown
484
.tag-div { display: inline-block; &.active .tag { color: var(--comment-color); background-color: var(--key); box-shadow: rgba(0,0,0,0.24) 0 1.01372px 2.32903px, inset 0 0 0 0 var(--key) !important; font-weight: bold; .count { opacity: 0.5; color: var(--comment-color); } &:hover { background-color: var(--key-opacity-07); } } .tag { position: relative; margin-right: 0.3em; padding: 0.3em 0.6em; cursor: pointer; user-select: none; white-space: nowrap; border-radius: 0.4em; background-color: var(--comment-color); box-shadow: rgba(0,0,0,0.24) 0 1.01372px 2.32903px, inset 0 0 0 0 var(--key); line-height: 2.2em; &.empty { opacity: 0.2; } .text { padding-right: 0.5em; &.parentheses-ending { padding-right: 0; } } .count { color: var(--key-opacity-05); } body.animation-enabled & { transition: background-color 0.3s, color 0.3s, box-shadow 0.3s; } &:hover { box-shadow: rgba(0,0,0,0.24) 0 1.01372px 2.32903px, inset 0 0 0 0.1em var(--key); } &:active { color: var(--key-opacity-07); } // &::before { // position: absolute; // top: 0.4em; // left: 0.4em; // display: block; // width: 0.7em; // height: 0.7em; // content: ''; // border-radius: 50%; // background-color: var(--paper-bg-color); // box-shadow: inset rgba(0,0,0,0.24) 0 1.01372px 2.32903px, 0 0 0 0 var(--key); // body.animation-enabled & { // transition: box-shadow 0.3s; // } // } } } .content-container>.content .tags { padding-right: calc(0.8em + 0.8vw) !important; } .tag-search-chapter { .chapter-title { margin-top: 0; >a:hover { text-decoration: underline; } } .match-ratio { margin-bottom: 0; opacity: 0.7; } }
kink/kat
src/style/tag.less
CSS
unknown
1,920
.tagging-tool { .desc-line { margin-left: -0.4em; border-radius: 0.4em; body.animation-enabled & { transition: background-color 0.3s; } &.errored { background-color: rgba(237, 67, 55, 0.3); } } .tagging-tool-tag-variant, .tagging-tool-variant { padding: 0.2em 0.4em; cursor: pointer; user-select: none; } .tagging-tool-tag { padding: 0.2em 0 0.2em 0.4em; >.tagging-tool-tag-variant { margin-right: 0; margin-left: 0.2em; } &.has-available-variant>.no-available-variants { display: none; } >.no-available-variants { padding: 0 0.4em; cursor: not-allowed; color: var(--key-opacity-07); font-weight: normal; } } .tagging-tool-variant:hover { box-shadow: inset 0 0 0 0.1em var(--key); } .tagging-tool-variant.selected:hover { background-color: var(--key-opacity-07); } .tagging-tool-tag-variant, .tagging-tool-tag, .tagging-tool-variant { margin: 0 0.2em; border-radius: 0.4em; background-color: var(--comment-color); box-shadow: inset 0 0 0 0 var(--key); font-weight: bold; body.animation-enabled & { transition: background-color 0.3s, color 0.3s, box-shadow 0.3s; } &.errored { color: white !important; background-color: #ED4337 !important; } &.selected { color: var(--comment-color); background-color: var(--key); box-shadow: inset 0 0 0 0 var(--key) !important; &.hovered { background-color: var(--key-opacity-07); } } &.hovered { box-shadow: inset 0 0 0 0.1em var(--key); } >input { position: relative; top: 0.1em; margin: 0 0.5em 0 0; cursor: pointer; } } p.tag-title { margin-bottom: 0; } >ul { margin-top: 0; } }
kink/kat
src/style/taggingTool.less
CSS
unknown
1,838
.title-container { position: fixed; top: 5vh; left: 5vh; transform: translateX(0); opacity: 1; color: var(--key); &.hidden { transform: translateX(-5vh); pointer-events: none; opacity: 0; } body.animation-enabled & { transition: transform 0.3s, opacity 0.3s, color 0.3s; } @media (max-width: 900px) { & { left: 50%; width: 38.3vh; transform: translateX(-50%); white-space: nowrap; } } .english-title { font-family: 'ZCOOL QingKe HuangYou', cursive; font-size: 5.2vh; line-height: 5.2vh; } .title { font-family: 'ZCOOL QingKe HuangYou', cursive; font-size: 10vh; line-height: 10vh; } .build-author-container { display: flex; padding-right: 0.5vh; padding-left: 0.5vh; } .build-author-container .build { flex: 1; padding-top: 0.2vh; text-align: left; font-family: 'ZCOOL QingKe HuangYou', cursive; font-size: 2.6vh; } .build-author-container .author { flex: 1; text-align: right; font-size: 2vh; } }
kink/kat
src/style/title.less
CSS
unknown
1,069
@navbar-height: 2.6rem; @material-content-regular-padding: 50px; @content-block-width: 820px; @content-width: 720px; @block-spacing: 2vw; @side-block-width: 380px; @side-block-padding: 40px;
kink/kat
src/style/variables.less
CSS
unknown
193
.visit-count-holder { >a { display: block; overflow-x: visible; margin: 0.2em 0; padding: 0.15em 0.3em; cursor: pointer; white-space: nowrap; border-top-right-radius: 0.4em; border-bottom-right-radius: 0.4em; background-color: var(--key-opacity-01); body.animation-enabled & { transition: background-color 0.12s; } &:hover { background-color: var(--key-opacity-015) !important; } &:active { background-color: var(--key-opacity-01) !important; } } &:hover>a { background-color: var(--key-opacity-007); } }
kink/kat
src/style/visitCount.less
CSS
unknown
599
@import (reference) 'common/button.less'; .wtcd-save-button-list { >div:extend(#common.button all) { margin-top: 2vh; &.save { display: flex; text-align: left; >.id { margin-right: 0.5em; margin-left: 0.1em; font-size: 2.6em; font-weight: bold; &.small { font-size: 2.2em; } } >.info { >.state-desc { margin-top: 0.4em; } >.date { margin-top: 0.2em; margin-bottom: 0.2em; opacity: 0.7; font-size: 0.8em; } } } } }
kink/kat
src/style/wtcdGame.less
CSS
unknown
611
.content-container>.content .content-block.wtcup-vote { .stars-container { display: flex; justify-content: center; margin-bottom: 1em; .choice { cursor: pointer; user-select: none; font-family: 'Material Icons'; font-size: 3em; &.clear { margin-right: 0.3em; &.dimmed { cursor: not-allowed; } } &.star { padding-right: 0.05em; padding-left: 0.05em; } &.dimmed { opacity: 0.3; } &.less-dimmed { opacity: 0.6; } } } }
kink/kat
src/style/wtcup.less
CSS
unknown
580
# 使用的 z-index - rect:1 - content container:2 - modal:3 - hint:4 - NSFW:5
kink/kat
src/style/zIndex.md
Markdown
unknown
89
function appendChildren($element: HTMLElement, children: any) { if (children === undefined || children === null || children === false) { return; } if (Array.isArray(children)) { children.forEach(child => appendChildren($element, child)); } else { $element.append(children); } } export function $e( tag: string, attributes: { [key: string]: any } | null, ...children: Array<any> ) { const $element = document.createElement(tag); if (attributes !== null) { for (const [key, value] of Object.entries(attributes)) { if (value === null) { continue; } if (key === 'style') { for (const [cssKey, cssValue] of Object.entries(value)) { ($element.style as any)[cssKey] = cssValue; } } else { if (Array.isArray(value)) { ($element as any)[key] = value.join(' '); } else { ($element as any)[key] = value; } } } } appendChildren($element, children); return $element; }
kink/kat
src/web/$e.tsx
TypeScript
unknown
1,012
import { materialDarkColors } from './constant/materialDarkColors'; import { developerMode } from './data/settings'; import { stringHash } from './util/stringHash'; export class DebugLogger { private prefix: string; private css: string; public constructor( name: string, ) { this.prefix = '%c' + name; this.css = `background-color: #` + materialDarkColors[ Math.abs(stringHash(name)) % materialDarkColors.length ] + '; border-radius: 0.3em; padding: 0 0.3em; color: white'; } public log(...stuff: any) { if (!developerMode.getValue()) { return; } console.info(this.prefix, this.css, ...stuff); } public warn(...stuff: any) { console.warn(this.prefix, this.css, ...stuff); } public error(...stuff: any) { console.error(this.prefix, this.css, ...stuff); } }
kink/kat
src/web/DebugLogger.ts
TypeScript
unknown
843
type Listener<T> = (arg: T, listener: Listener<T>) => void; export class Event<T = void> { private listeners: Set<Listener<T>> | null = null; private onceListeners: Set<Listener<T>> | null = null; private isEmitting: boolean = false; private queue: Array<() => void> = []; private runWhenNotEmitting(fn: () => void) { if (this.isEmitting) { this.queue.push(fn); } else { fn(); } } public on(listener: Listener<T>) { this.runWhenNotEmitting(() => { if (this.listeners === null) { this.listeners = new Set(); } this.listeners.add(listener); }); return listener; } public onUntil(listener: Listener<T>, event: Event<any>) { this.runWhenNotEmitting(() => { this.on(listener); event.once(() => this.off(listener)); }); } public off(listener: Listener<T>) { this.runWhenNotEmitting(() => { if (this.listeners !== null) { this.listeners.delete(listener); } if (this.onceListeners !== null) { this.onceListeners.delete(listener); } }); } public once(onceListener: (arg: T) => void) { this.runWhenNotEmitting(() => { if (this.onceListeners === null) { this.onceListeners = new Set(); } this.onceListeners.add(onceListener); }); return onceListener; } public onceUntil(listener: (arg: T) => void, event: Event<any>) { this.runWhenNotEmitting(() => { this.once(listener); event.once(() => this.off(listener)); }); } public expect(filter?: (arg: T) => boolean): Promise<T> { if (this.isEmitting) { return new Promise(resolve => { this.queue.push(() => { this.expect(filter).then(resolve); }); }); } if (filter === undefined) { return new Promise(resolve => this.once(resolve)); } return new Promise(resolve => { const listener = this.on(arg => { if (!filter(arg)) { return; } this.off(listener); resolve(arg); }); }); } public emit(arg: T) { this.runWhenNotEmitting(() => { this.isEmitting = true; if (this.listeners !== null) { this.listeners.forEach(listener => listener(arg, listener)); } if (this.onceListeners !== null) { this.onceListeners.forEach(onceListener => onceListener(arg, onceListener)); this.onceListeners = new Set(); } this.isEmitting = false; this.queue.forEach(task => task()); this.queue.length = 0; }); } }
kink/kat
src/web/Event.ts
TypeScript
unknown
2,552
import { Layout, setLayout } from './control/layoutControl'; import { DebugLogger } from './DebugLogger'; import { h } from './hs'; import { forceReflow } from './util/DOM'; export enum ItemDecoration { SELECTABLE, BACK, ICON_FOLDER, ICON_LINK, ICON_EQUALIZER, ICON_FILE, ICON_GAME, ICON_NOTIFICATION, ICON_LIST, ICON_CALENDER, ICON_HISTORY, ICON_CLEAR, ICON_PERSON, ICON_TAG, } export enum ItemLocation { BEFORE, AFTER, } type ItemOptions = { location?: ItemLocation, hidden?: boolean; } & ({ button?: false; } | { button: true; link?: string; decoration?: ItemDecoration; }); function createSpan(text: string, ...classNames: Array<string>) { const $span = document.createElement('span'); $span.innerText = text; $span.classList.add(...classNames); return $span; } export class ItemHandle { private $prependSpan: HTMLSpanElement | null = null; private $appendSpan: HTMLSpanElement | null = null; public constructor( private menu: Menu, public $flexElement: HTMLDivElement, public $innerElement: HTMLDivElement | HTMLAnchorElement, ) { } public setSelected(selected: boolean) { this.$innerElement.classList.toggle('selected', selected); return this; } public onClick(handler: (element: ItemHandle) => void) { this.$innerElement.addEventListener('click', () => { handler(this); }); return this; } public setInnerText(innerText: string) { this.$innerElement.innerText = innerText; return this; } public addClass(className: string) { this.$innerElement.classList.add(className); return this; } public removeClass(className: string) { this.$innerElement.classList.remove(className); return this; } public prepend(text: string, className?: string) { if (this.$prependSpan === null) { this.$prependSpan = createSpan('', 'prepend'); this.$innerElement.prepend(this.$prependSpan); } const $span = createSpan(text, 'item-side'); if (className !== undefined) { $span.classList.add(className); } this.$prependSpan.prepend($span); return $span; } public append(text: string, className?: string) { if (this.$appendSpan === null) { this.$appendSpan = createSpan('', 'append'); this.$innerElement.appendChild(this.$appendSpan); } const $span = createSpan(text, 'item-side'); if (className !== undefined) { $span.classList.add(className); } this.$appendSpan.appendChild($span); return $span; } public remove() { this.$flexElement.remove(); } } export class Menu { public readonly subMenus: Map<string, { name: string, factory: () => Menu, }> = new Map(); protected container: HTMLDivElement; private debugLogger: DebugLogger; public constructor( public readonly urlBase: string, public readonly layout: Layout = Layout.OFF, ) { this.debugLogger = new DebugLogger(`Menu (${urlBase})`); this.container = h('.menu.hidden'); document.body.appendChild(this.container); // if (this.fullPath.length >= 1) { // const path = document.createElement('div'); // path.classList.add('path'); // path.innerText = this.fullPath.join(' > '); // this.container.appendChild(path); // } // if (parent !== null) { // this.addItem('返回', { button: true, decoration: ItemDecoration.BACK, unclearable: true }) // .linkTo(parent); // } } public destroy() { this.container.classList.add('hidden'); setTimeout(() => this.container.remove(), 1000); } public hide() { this.container.classList.add('hidden'); } public show() { setLayout(this.layout); forceReflow(this.container); this.container.classList.remove('hidden'); } public addItem(title: string, options: ItemOptions = {}): ItemHandle { let $innerElement: HTMLDivElement | HTMLAnchorElement; if (options.button && options.link !== undefined) { $innerElement = document.createElement('a'); $innerElement.href = options.link; $innerElement.rel = 'noopener noreferrer'; if (!options.link.startsWith('#')) { $innerElement.target = '_blank'; } } else { $innerElement = document.createElement('div'); } $innerElement.innerText = title; if (options.hidden) { $innerElement.classList.add('display-none'); } if (options.button) { $innerElement.classList.add('button'); switch (options.decoration) { case ItemDecoration.BACK: $innerElement.classList.add('back'); break; case ItemDecoration.SELECTABLE: $innerElement.classList.add('selectable'); break; case ItemDecoration.ICON_FOLDER: $innerElement.classList.add('icon', 'folder'); break; case ItemDecoration.ICON_LINK: $innerElement.classList.add('icon', 'link'); break; case ItemDecoration.ICON_EQUALIZER: $innerElement.classList.add('icon', 'equalizer'); break; case ItemDecoration.ICON_FILE: $innerElement.classList.add('icon', 'file'); break; case ItemDecoration.ICON_GAME: $innerElement.classList.add('icon', 'game'); break; case ItemDecoration.ICON_NOTIFICATION: $innerElement.classList.add('icon', 'notification'); break; case ItemDecoration.ICON_LIST: $innerElement.classList.add('icon', 'list'); break; case ItemDecoration.ICON_CALENDER: $innerElement.classList.add('icon', 'calender'); break; case ItemDecoration.ICON_HISTORY: $innerElement.classList.add('icon', 'history'); break; case ItemDecoration.ICON_CLEAR: $innerElement.classList.add('icon', 'clear'); break; case ItemDecoration.ICON_PERSON: $innerElement.classList.add('icon', 'person'); break; case ItemDecoration.ICON_TAG: $innerElement.classList.add('icon', 'icon-tag'); break; } } const $flexElement = h('.flex') as HTMLDivElement; $flexElement.appendChild($innerElement); if (options.location === ItemLocation.BEFORE) { this.container.prepend($flexElement); } else { this.container.appendChild($flexElement); } return new ItemHandle(this, $flexElement, $innerElement); } protected buildSubMenu<TAdditionalArgs extends Array<unknown>>( name: string, MenuConstructor: (new (urlBase: string, ...args: TAdditionalArgs) => Menu), ...args: TAdditionalArgs ) { return new SubMenuBuilder(this, name, urlSegment => new MenuConstructor(`${this.urlBase}/${urlSegment}`, ...args)); } public registerSubMenu(name: string, urlSegment: string, menuFactory: () => Menu) { if (this.subMenus.has(urlSegment)) { this.debugLogger.error(`Duplicated url segment: ${urlSegment}.`); } this.subMenus.set(urlSegment, { name, factory: menuFactory, }); } } class SubMenuBuilder { /** Used in URL */ private urlSegment: string; private displayName: string; private decoration: ItemDecoration | undefined = undefined; private hidden = false; public constructor( private readonly parentMenu: Menu, /** Displayed in the parent menu */ private readonly name: string, private readonly subMenuFactory: (urlSegment: string) => Menu, ) { this.urlSegment = name; this.displayName = name; } /** * Used for constructing menu url */ public setUrlSegment(urlSegment: string) { this.urlSegment = urlSegment; return this; } public setDecoration(decoration: ItemDecoration) { this.decoration = decoration; return this; } /** * Shown in the menu (initially); Defaults to name */ public setDisplayName(displayName: string) { this.displayName = displayName; return this; } public setHidden(hidden: boolean = true) { this.hidden = hidden; return this; } public build() { this.parentMenu.registerSubMenu( this.name, this.urlSegment, () => this.subMenuFactory(this.urlSegment), ); return this.parentMenu.addItem(this.displayName, { button: true, link: `${this.parentMenu.urlBase}/${this.urlSegment}`, decoration: this.decoration, hidden: this.hidden, }); } }
kink/kat
src/web/Menu.ts
TypeScript
unknown
8,682
// https://material.io/resources/color/ export const materialDarkColors = [ 'b71c1c', '880e4f', '4a148c', '311b92', '1a237e', '0d47a1', '01579b', '006064', '004d40', '1b5e20', '33691e', '827717', 'bf360c', '3e2723', '795548', '5d4037', '1976d2', '303f9f', '3f51b5', '673ab7', '9c27b0', 'c2185b', 'd32f2f', '263238', '455a64', '616161', '212121', ];
kink/kat
src/web/constant/materialDarkColors.ts
TypeScript
unknown
403
export const PREVIOUS_CHAPTER = 'Previous Chapter'; export const GO_TO_MENU = 'Menu'; export const NEXT_CHAPTER = 'Next Chapter'; export const CHAPTER_LOADING = 'Loading Chapter...'; export const CHAPTER_FAILED = 'Chapter failed to load, please check network connection'; export const BUILD_FAILED_TITLE = 'Build Failed'; export const BUILD_FAILED_DESC = '《WEARABLE TECHNOLGOY》build scripts encountered an exception during the build process. Please check the console for more information' export const BUILD_FAILED_OK = 'OK'; export const BROKEN_LINK_TITLE = 'Broken Link'; export const BROKEN_LINK_DESC = 'The address provided was unable to be resolved. You will be returned to the main menu shortly.'; export const BROKEN_LINK_OK = 'OK'; export const COMMENTS_SECTION = 'Comments Section'; export const COMMENTS_LOADING = 'Loading comments...'; export const COMMENTS_UNAVAILABLE = 'Comments are unavailble for this article.'; export const COMMENTS_SEND = '+ Post Comment'; export const COMMENTS_LOADED = 'Below is the comments section of this article.'; export const COMMENTS_FAILED = 'Comments failed to load, please check network connection.'; export const COMMENTS_RECENT_SECTION = 'Latest comments'; export const COMMENTS_RECENT_LOADED = 'Below are the latest 50 comments'; export const COMMENTS_MENTION_SECTION = 'Latest Replies'; export const COMMENTS_MENTION_LOADED = 'Below are the latest replies to your commentts'; export const COMMENTS_MENTION_NO_TOKEN_TITLE = 'Latest replies are unavailable'; export const COMMENTS_MENTION_NO_TOKEN_DESC = 'Please send at least one '; export const COMMENTS_MENTION_REPLIED_TITLE = 'Successfully Replied'; export const COMMENTS_MENTION_REPLIED_OK = 'Ok'; export const COMMENTS_SUBMIT_BY = 'Posted by $'; export const COMMENTS_MODIFIED_DATE = '(Edited at $)'; export const COMMENTS_SENDING = 'Sending comment...'; export const COMMENTS_DELETING = 'Deleting comment...'; export const COMMENTS_SEND_DISPLAY_NAME_0 = 'will be'; export const COMMENTS_SEND_DISPLAY_NAME_1 = '的身份发表评论。'; // ? export const COMMENTS_SEND_DISPLAY_NAME_EDIT = '点此修改'; // click to change name ? export const COMMENTS_DELETE = 'Delete Commend'; export const COMMENTS_REPLY = 'Reply'; export const COMMENTS_DELETE_CONFIRMATION = 'Are you sure you want to delete this reply'; export const COMMENTS_SEND_TITLE = 'Post a comment'; export const COMMENTS_SEND_CONFIRM = 'Post'; export const COMMENTS_LOSE_EDITED_TITLE = 'Are you sure you want to disgard what you wrote '; export const COMMENTS_LOSE_EDITED_CONFIRM = 'Confirm'; export const COMMENTS_LOSE_EDITED_CANCEL = 'Cancel'; export const COMMENTS_SEND_HINT = 'Please add content to comment.'; export const COMMENTS_SEND_DISPLAY_NAME_PREFIX = 'Display-name(Required):'; export const COMMENTS_SEND_EMAIL_INPUT_PREFIX = 'Email(Required):'; export const VISIT_COUNT_TITLE = 'View Statistics'; export const VISIT_COUNT_DESC_0 = 'Visititation statistics are provided by the 《WEARABLE TECHNOLOGY》access system. 《WEARABLE TECHNOLOGY》 prioritizes your user information, this data can not be used to correlate any information wtih you. It\'s privacy policy can be found '; export const VISIT_COUNT_DESC_1 = 'here '; export const VISIT_COUNT_DESC_2 = 'found.'; export const VISIT_COUNT_LOADING = 'Loading visitation information...'; export const VISIT_COUNT_FAILED = 'The visitation information failed to load, please check network connection.'; export const VISIT_COUNT_LOAD_MORE = 'Load more'; export const VISIT_COUNT_LOAD_MORE_LOADING = 'Loading...'; export const VISIT_COUNT_LOAD_MORE_FAILED = 'Request faileld, please try again'; export const VISIT_COUNT_TIME_FRAME_ALL = 'All'; export const VISIT_COUNT_TIME_FRAME_HOUR = '1 hour'; export const VISIT_COUNT_TIME_FRAME_DAY = '24 hours'; export const VISIT_COUNT_TIME_FRAME_WEEK = '7 days'; export const VISIT_COUNT_TIME_FRAME_MONTH = '30 days'; export const VISIT_COUNT_TIME_FRAME_YEAR = '365 days'; export const VISIT_COUNT_DISPLAYING = 'The number of visits in $:'; export const VISIT_COUNT_TIMES = ' times'; export const NO_BLOCKED_USERS = 'No users are currently blocked'; export const CLICK_TO_UNBLOCK = '(Click to unblock user)'; export const WTCD_GAME_RESTART = '重置游戏'; export const WTCD_GAME_RESTART_TITLE = '是否重置游戏种子'; export const WTCD_GAME_RESTART_DESC = '游戏种子会决定游戏的随机因素。'; export const WTCD_GAME_RESTART_ALL_DESC = '若选择【重置游戏种子与进度】,那么新游戏中的所有随机因素和本游戏不一致。'; export const WTCD_GAME_RESTART_DECISION_ONLY_DESC = '若选择【仅重置进度】,那么新游戏中的随机因素将与本游戏完全一致。'; export const WTCD_GAME_RESTART_ALL = '重置游戏种子与进度'; export const WTCD_GAME_RESTART_DECISION_ONLY = '仅重置进度'; export const WTCD_GAME_RESTART_CANCEL = '不重置任何内容'; export const WTCD_GAME_RESTART_OK = '游戏重置成功'; export const WTCD_GAME_SAVE = '存储'; export const WTCD_GAME_SAVE_TITLE = '请选择要存储的位置'; export const WTCD_GAME_SAVE_CANCEL = '取消'; export const WTCD_GAME_SAVE_NEW = '- 新存档 -'; export const WTCD_GAME_SAVE_OVERWRITE_TITLE = '是否覆盖?'; export const WTCD_GAME_SAVE_OVERWRITE_CONFIRM = '确认覆盖'; export const WTCD_GAME_SAVE_OVERWRITE_CANCEL = '取消'; export const WTCD_GAME_SAVE_OK = '存储成功'; export const WTCD_GAME_LOAD = '读取'; export const WTCD_GAME_LOAD_TITLE = '请选择要读取的存档'; export const WTCD_GAME_LOAD_CANCEL = '取消'; export const WTCD_GAME_LOAD_QUICK = '快'; export const WTCD_GAME_LOAD_OK = '读取成功'; export const WTCD_GAME_QUICK_SAVE = '快速存储'; export const WTCD_GAME_QUICK_SAVE_OK = '快速存储成功'; export const WTCD_GAME_QUICK_LOAD = '快速读取'; export const WTCD_GAME_QUICK_LOAD_OK = '快速读取成功'; export const WTCD_GAME_QUICK_LOAD_NOT_EXIST = '没有可用的快速存档,请先使用【快速存储】来创建快速存档。'; export const WTCD_GAME_QUICK_LOAD_CONFIRM_TITLE = '是否快速读取?'; export const WTCD_GAME_QUICK_LOAD_CONFIRM_DESC = '这会丢失当前未保存的数据。(可在【设置】中禁用此确认)'; export const WTCD_GAME_QUICK_LOAD_CONFIRM_CONFIRM = '确认读取'; export const WTCD_GAME_QUICK_LOAD_CONFIRM_CANCEL = '取消'; export const WTCD_GAME_NO_DESC = '无描述文本'; export const WTCD_ERROR_COMPILE_TITLE = 'WTCD 编译失败'; export const WTCD_ERROR_COMPILE_DESC = '该 WTCD 文档在编译时发生了错误。请检查是否有语法错误或是其他基本错误。'; export const WTCD_ERROR_RUNTIME_TITLE = 'WTCD 运行时错误'; export const WTCD_ERROR_RUNTIME_DESC = '该 WTCD 文档在运行时发生了错误。请检查是否有逻辑错误。'; export const WTCD_ERROR_INTERNAL_TITLE = 'WTCD 内部错误'; export const WTCD_ERROR_INTERNAL_DESC = 'WTCD 解释器在解释执行该 WTCD 文档时崩溃了。请务必告诉琳你做了什么好让她来修。'; export const WTCD_ERROR_MESSAGE = '错误信息:'; export const WTCD_ERROR_WTCD_STACK_TITLE = 'WTCD 调用栈'; export const WTCD_ERROR_WTCD_STACK_DESC = 'WTCD 调用栈记录了在错误发生时 WTCD 的解释器状态。这可以帮助理解错误发生的上下文。'; export const WTCD_ERROR_INTERNAL_STACK_TITLE = '内部调用栈'; export const WTCD_ERROR_INTERNAL_STACK_DESC = '内部调用栈记录了出现该错误时编译器或是解释器的状态。请注意内部调用栈通常只在调试 WTCD 编译器或是解释器时有用。内部调用栈通常对调试 WTCD 文档没有作用。'; export const WTCD_CANVAS_LOADING = '资源加载中... 取决于网络情况,这可能需要 1 秒 ~ 10 分钟。'; export const GENERIC_SUCCESS_TITLE = 'Success'; export const GENERIC_SUCCESS_DESC = 'Operation succeeded'; export const GENERIC_ERROR_TITLE = 'Failure'; export const GENERIC_ERROR_DESC = 'An error has occured'; export const GENERIC_LOADING_TITLE = 'Please Wait'; export const GENERIC_LOADING_DESC = 'Loading...'; export const GENERIC_HINT_TITLE = 'Hint'; export const GENERIC_CONFIRM = 'Confirm'; export const GENERIC_CANCEL = 'Cancel'; export const GENERIC_CLOSE = 'Close'; export const GENERIC_INTERNET_ERROR = 'An error occured loading the requested material. Check your internet connection, then try again.'; export const BACKEND_ERROR_NAME_DUPLICATED = 'This name is already in use. If you have used it on other devices before this, you can continue to use this name on 《WEARABLE TECHNOLOGY》 by loading your identity token generated with your previous comment in "Settings" > "User Settings Menu" > "Identity Token"'; export const BACKEND_ERROR_EMAIL_DUPLICATED = 'The email is already in use. If you have used it on other devices before this, you can continue to use this email on 《WEARABLE TECHNOLOGY》 bu loading your identity token generated with your previous comment in "Settings" > "User Settings Menu" > "Identity Token"'; export const BACKEND_ERROR_NAME_TOO_LONG = 'Name too long.'; export const BACKEND_ERROR_EMAIL_TOO_LONG = 'Email too long.'; export const BACKEND_ERROR_EMAIL_INVALID = 'E-mail format is incorrect. 《WEARABLE TECHNOLOGY》 comment system only accepts common e-mail address domains. If you feel that your domain should be supported, please contact 琳 (Lin)' export const BACKEND_ERROR_COMMENT_TOO_LONG = 'Comment too long.'; export const BACKEND_ERROR_TOKEN_INVALID = 'Invalid token.'; export const BACKEND_ERROR_NAME_TOO_SHORT = 'Name too short。'; export const BACKEND_ERROR_COMMENT_TOO_SHORT = 'Comment too short。'; export const BACKEND_ERROR_NAME_INVALID = 'The provided username is invalid. Please make sure no control characters are in the name.'; export const BACKEND_ERROR_UNKNOWN = 'An unknown interal server error occured. Please contact 琳 (Lin).'; export const USER_TOKEN_CHANGE_EMPTY = '请输入身份令牌。'; export const USER_TOKEN_CHANGE_INVALID = '身份令牌无效,请再次检查您输入的内容是否正确。'; export const USER_TOKEN_CHANGE_CHECKING = '正在确认您的身份令牌...'; export const USER_TOKEN_CHANGE_SUCCESS = '身份令牌设置成功'; export const USER_TOKEN_CHANGE_TITLE = '修改身份令牌'; export const USER_TOKEN_CHANGE_DESC = '这是您的身份令牌。\n使用身份令牌可以在《可穿戴科技》发表评论。\n当您第一次发表评论时,系统就会自动生成一个身份令牌。而后续发表的评论则会使用同一个令牌。\n您可以通过将这个令牌复制到别的电脑上来实现使用多台设备用一个身份回复。'; export const USER_TOKEN_CHANGE_INPUT_LABEL = '令牌:'; export const USER_TOKEN_DOES_NOT_EXIST = '您目前不持有身份令牌。请至少评论一次后再尝试。'; export const USER_UPDATE_PROFILE_ERROR_NOT_INITIALIZED = '身份信息初始化失败,请刷新页面重试。'; export const USER_UPDATE_PROFILE_TITLE = '修改身份信息'; export const USER_UPDATE_PROFILE_DESC = '您可以在此修改您在使用评论系统时的身份信息。'; export const USER_UPDATE_PROFILE_HINT_USER_NAME = '用户名决定他人如何在评论中 @ 您,不可修改。'; export const USER_UPDATE_PROFILE_HINT_DISPLAY_NAME = '昵称是显示在您发表的每一条评论上的身份标识。'; export const USER_UPDATE_PROFILE_HINT_EMAIL_0 = '邮箱用于加载头像;若要设置头像,请'; export const USER_UPDATE_PROFILE_HINT_EMAIL_GRAVATAR_LINK = '点此转到 Gravatar'; export const USER_UPDATE_PROFILE_HINT_EMAIL_1 = ',使用相同邮箱注册账号并上传头像;您的邮箱永远不会公开给其他用户。'; export const USER_UPDATE_PROFILE_USER_NAME_INPUT_LABEL = '用户名:'; export const USER_UPDATE_PROFILE_DISPLAY_NAME_INPUT_LABEL = '昵称:'; export const USER_UPDATE_PROFILE_EMAIL_INPUT_LABEL = '邮箱:'; export const USER_UPDATE_PROFILE_DISPLAY_NAME_EMPTY = '昵称不能为空。'; export const USER_UPDATE_PROFILE_LOADING = '正在更新您的信息...'; export const USER_UPDATE_PROFILE_SUCCESS = '信息更新成功!'; export const AUTHOR_PAGE_WORKS = '作品列表'; export const AUTHOR_PAGE_WORKS_DESC = '以下为$参与创作的作品。'; export const AUTHOR_PAGE_AS = '作为'; export const AUTHOR_PAGE_LINK = '链接'; export const MIRROR_TITLE = '镜像站选择'; export const MIRROR_DESC_0_NO_TOKEN = '请选择您要使用的镜像站。您的阅读历史和阅读器设置将不会被转移。'; export const MIRROR_DESC_0 = '请选择您要使用的镜像站。您的评论身份将会被自动转移,但是阅读历史和阅读器设置将不会被转移。(转移后,您依然可以使用同样的身份在之前使用的站点评论。)'; export const MIRROR_DESC_1 = '所有镜像站都是读者无偿提供的。如果好用,记得和提供者道一声谢哦。'; export const MIRROR_URL = '网址:'; export const MIRROR_PROVIDED_BY = '提供者:'; export const MIRROR_TECHNOLOGY = '技术:'; export const MIRROR_LANDING_INVALID_REFERRAL = '因为 referrer 错误,您的评论身份信息转移失败。'; export const MIRROR_LANDING_SUCCESS_HINT = '评论身份转移成功'; export const MIRROR_LANDING_CONFLICT_TITLE = '评论身份冲突'; export const MIRROR_LANDING_CONFLICT_DESC = '您刚刚使用的站点请求修改本站的评论身份。但是您之前已经在本站评论过,且使用了不同的评论身份,请问您要?'; export const MIRROR_LANDING_CONFLICT_OVERWRITE = '用刚刚使用的站点的评论身份覆盖本站的评论身份'; export const MIRROR_LANDING_CONFLICT_KEEP = '保留本站的评论身份'; export const MIRROR_HINT_0 = '当前正在使用由$提供的镜像站,'; export const MIRROR_HINT_1 = '。'; export const MIRROR_HINT_CLICK_TO_CHANGE = '点此更换';
kink/kat
src/web/constant/messages.ts
TypeScript
unknown
13,824
export interface MirrorSite { name: string; origin: string; provider: string; technology: string; } export const mirrorSites: Array<MirrorSite> = [ { name: 'wt.bgme.me', origin: 'https://wt.bgme.me', provider: 'Shrink', technology: '自行构建', }, { name: 'rbq.desi', origin: 'https://rbq.desi', provider: 'kookxiang', technology: '自行构建', }, { name: 'wt.0w0.bid', origin: 'https://wt.0w0.bid', provider: '立音喵', technology: 'Cloudflare Workers', }, { name: 'wt.umwings.com', origin: 'https://wt.umwings.com', provider: 'C86', technology: '同步构建产物', }, ]; export const mirrorSitesPlusMainSite: Array<MirrorSite> = [{ name: 'wt.tepis.me(主站)', origin: 'https://wt.tepis.me', provider: '琳 缇佩斯', technology: 'GitLab Pages', }, ...mirrorSites];
kink/kat
src/web/constant/mirrorSites.ts
TypeScript
unknown
880
// ! NOTE: Redirects are only applied after the path fails to match export const redirects: Array<(input: string) => string> = [ input => input.replace(/^chapter\/人设卡\/(.*)$/, 'chapter/主线/人设卡/$1'), input => input.replace(/^chapter\/支线\/(.*)$/, 'chapter/$1'), input => input.replace(/^menu\/章节选择\/所有章节\/支线\/(.*)$/, 'menu/章节选择/所有章节/$1'), input => { if (input.startsWith('chapter/') && input.endsWith('.html') && !input.endsWith('第-1-章.html')) { return input.replace(/^(chapter\/.*)\.html$/, '$1/第-1-章.html'); } else { return input; } }, ];
kink/kat
src/web/constant/redirects.ts
TypeScript
unknown
638
export const rolePriorities: Map<string, number> = new Map(); const rolesInOrder = [ '作者', '画师', '编辑', ]; rolesInOrder.reverse().forEach((role, index) => rolePriorities.set(role, index)); export function getRolePriority(role: string) { return rolePriorities.get(role) ?? -1; }
kink/kat
src/web/constant/rolePriorities.ts
TypeScript
unknown
300
export const stylePreviewArticle = `<h1>已移除</h1> <p>已移除</p>`;
kink/kat
src/web/constant/stylePreviewArticle.ts
TypeScript
unknown
74
export type Tag = string; export type TagInfo = { tag: Tag, definition: string, details?: Array<string>, prerequisite: Array<Tag | [Tag, string]>, };
kink/kat
src/web/constant/tags.ts
TypeScript
unknown
158
export const thanks: Array<{ name: string, link?: string }> = [ { name: '立音喵' }, { name: 'lgd_小翅膀' }, { name: '青葉' }, { name: 'kn' }, { name: 'F74nk', link: 'https://t.me/F74nk_K' }, { name: '杨佳文' }, { name: '不知名的N姓人士就好' }, { name: '某不愿透露姓名的N性?' }, { name: '神楽坂 萌绫' }, { name: 'Butby' }, { name: 'NekoCaffeine' }, { name: 'RainSlide' }, { name: 'czp', link: 'https://www.hiczp.com' }, { name: 'kookxiang' }, { name: '櫻川 紗良' }, { name: 'Skimige' }, { name: 'TExL', link: 'http://texas.penguin-logistics.cn' }, { name: '路人乙' }, { name: 'pokemonchw', link: 'https://github.com/pokemonchw' }, { name: '帕蒂卡', link: 'https://github.com/Patika-ailemait' }, { name: '零件', link: 'https://nekosc.com' }, { name: '幻梦', link: 'https://t.me/HuanmengQwQ' }, { name: 'acted咕咕喵', link: 'https://acted.gitlab.io/h3' }, { name: '重水时雨', link: 'https://t.me/boatmasteronD2O' }, { name: '神楽坂 紫' }, { name: 'Runian Lee', link: 'https://t.me/Runian' }, { name: '琥珀' }, { name: '为霜' }, { name: '冰蓮音' }, { name: 'Testingdoll01' }, { name: 'VV', link: 'https://www.pixiv.net/users/58170013' }, { name: '城岭 樱' }, { name: '熵' }, { name: '0 级骨钉' }, { name: '夏克斯' }, { name: '王木木' }, { name: 'C86', link: 'https://c86.moe' }, { name: '炽羽渡尘01' }, { name: '47AD' }, { name: '禾裱禾裱' }, { name: '灵翼' }, { name: '铱则' }, ].sort(() => Math.random() - 0.5);
kink/kat
src/web/constant/thanks.ts
TypeScript
unknown
1,587
function sign(x: number) { return x > 0 ? 1 : x < 0 ? -1 : 0; } function solveQuad(a: number, b: number, c: number) { const D = (b ** 2) - 4 * a * c; return (-b + sign(a) * (D ** 0.5)) / (2 * a); } export class MonoDimensionTransitionControl { /** Start time of the current transition */ private initialTime: number = 0; /** Time when the acceleration is reversed of the current transition */ private reverseTime: number = 0; /** Value when the acceleration is reversed of the current transition */ private reverseValue: number = 0; /** Velocity when the acceleration is reversed of the current transition */ private reverseVelocity: number = 0; /** Start velocity of the current transition */ private lastStartingVelocity: number = 0; /** Time when the current transition is finished */ private finalTime: number = 0; /** Target value of the current transition */ private finalValue: number = 0; /** Acceleration in unit per ms */ private acceleration: number = 0; public constructor( /** Initial value */ private lastValue: number, accelerationPerSecSq: number, ) { this.finalValue = lastValue; this.acceleration = accelerationPerSecSq / 1000 / 1000; } public setTarget(targetValue: number) { this.lastValue = this.getValue(); const x = targetValue - this.lastValue; if (x === 0) { return; } const now = Date.now(); const v = this.getVelocity(now); // Find a solution for reverse time let t = solveQuad(this.acceleration, 2 * v, 0.5 * (v ** 2) / this.acceleration - x); if (Number.isNaN(t) || t < 0) { // If a reverse time cannot be found with current sign of acceleration, try again with the opposite of acceleration this.acceleration = -this.acceleration; t = solveQuad(this.acceleration, 2 * v, 0.5 * (v ** 2) / this.acceleration - x); } const a = this.acceleration; this.initialTime = now; this.reverseTime = this.initialTime + t; this.reverseValue = this.lastValue + 0.5 * a * (t ** 2) + v * t; this.reverseVelocity = v + a * t; this.finalTime = this.reverseTime + t + v / a; this.lastStartingVelocity = v; this.finalValue = targetValue; } public getVelocity(now = Date.now()) { return now < this.reverseTime ? this.lastStartingVelocity + (now - this.initialTime) * this.acceleration : now < this.finalTime ? this.lastStartingVelocity + (2 * this.reverseTime - this.initialTime - now) * this.acceleration : 0; } public getValue(now = Date.now()) { if (now < this.reverseTime) { const t = now - this.initialTime; return this.lastValue + 0.5 * this.acceleration * (t ** 2) + this.lastStartingVelocity * t; } else if (now < this.finalTime) { const t = now - this.reverseTime; return this.reverseValue - 0.5 * this.acceleration * (t ** 2) + this.reverseVelocity * t; } else { return this.finalValue; } } public isFinished(now = Date.now()) { return now >= this.finalTime; } }
kink/kat
src/web/control/MonoDimensionTransitionControl.ts
TypeScript
unknown
3,046
import { FeatureProvider } from '../../wtcd/FeatureProvider'; import { resolvePath } from '../util/resolvePath'; import { DebugLogger } from '../DebugLogger'; import { Chapter } from '../../Data'; import { AutoCache } from '../data/AutoCache'; import { loadGoogleFonts } from '../util/loadGooleFonts'; import { WTCD_CANVAS_LOADING } from '../constant/messages'; const debugLogger = new DebugLogger('WTCD Feature Provider'); const imageCache = new AutoCache<string, HTMLImageElement>(url => { return new Promise((resolve, reject) => { const image = document.createElement('img'); image.onload = () => resolve(image); image.onerror = () => reject(new Error(`Failed to load ${url}.`)); image.src = url; }); }, new DebugLogger('WTCD Image Cache')); const fontsCache = new AutoCache<string, string>(identifier => { // Identifier should look like: "googleFonts:ZCOOL KuaiLe" const modeSeparatorIndex = identifier.indexOf(':'); if (modeSeparatorIndex === -1) { return Promise.reject(new Error('Cannot find mode separator ":".')); } const mode = identifier.substr(0, modeSeparatorIndex); if (mode !== 'googleFonts') { return Promise.reject(new Error(`Unknown mode: "${mode}".`)); } return loadGoogleFonts(identifier.substr(modeSeparatorIndex + 1)); }, new DebugLogger('WTCD Font Cache')); export class WTCDFeatureProvider extends FeatureProvider { public constructor( private chapter: Chapter ) { super(); } public loadImage(path: string): Promise<CanvasImageSource> { if (!path.startsWith('./')) { return Promise.reject(new Error('Path has to be relative and start ' + `with "./". Received: "${path}"`)); } let resolved = resolvePath( 'chapters', this.chapter.htmlRelativePath, '..', path.substr(2), ); if (resolved === null) { return Promise.reject(new Error(`Failed to resolve path: "${path}".`)); } resolved = '/' + resolved; debugLogger.log('Resolved from:', path, 'to:', resolved); return imageCache.get(resolved); } public loadFont(identifier: string): Promise<string> { return fontsCache.get(identifier); } public drawLoadingCanvas($canvas: HTMLCanvasElement) { const ctx = $canvas.getContext('2d')!; ctx.font = `${$canvas.width / 40}px sans-serif`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.strokeStyle = 'rgba(0,0,0,0.8)'; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.lineWidth = $canvas.width / 200; ctx.strokeText(WTCD_CANVAS_LOADING, $canvas.width / 2, $canvas.height / 2); ctx.fillStyle = 'white'; ctx.fillText(WTCD_CANVAS_LOADING, $canvas.width / 2, $canvas.height / 2); } }
kink/kat
src/web/control/WTCDFeatureProvider.ts
TypeScript
unknown
2,702
import { GameReader } from '../../wtcd/GameReader'; import { WTCDRoot } from '../../wtcd/types'; import { WTCD_GAME_LOAD, WTCD_GAME_LOAD_CANCEL, WTCD_GAME_LOAD_OK, WTCD_GAME_LOAD_QUICK, WTCD_GAME_LOAD_TITLE, WTCD_GAME_NO_DESC, WTCD_GAME_QUICK_LOAD, WTCD_GAME_QUICK_LOAD_CONFIRM_CANCEL, WTCD_GAME_QUICK_LOAD_CONFIRM_CONFIRM, WTCD_GAME_QUICK_LOAD_CONFIRM_DESC, WTCD_GAME_QUICK_LOAD_CONFIRM_TITLE, WTCD_GAME_QUICK_LOAD_NOT_EXIST, WTCD_GAME_QUICK_LOAD_OK, WTCD_GAME_QUICK_SAVE, WTCD_GAME_QUICK_SAVE_OK, WTCD_GAME_RESTART, WTCD_GAME_RESTART_ALL, WTCD_GAME_RESTART_ALL_DESC, WTCD_GAME_RESTART_CANCEL, WTCD_GAME_RESTART_DECISION_ONLY, WTCD_GAME_RESTART_DECISION_ONLY_DESC, WTCD_GAME_RESTART_DESC, WTCD_GAME_RESTART_OK, WTCD_GAME_RESTART_TITLE, WTCD_GAME_SAVE, WTCD_GAME_SAVE_CANCEL, WTCD_GAME_SAVE_NEW, WTCD_GAME_SAVE_OK, WTCD_GAME_SAVE_OVERWRITE_CANCEL, WTCD_GAME_SAVE_OVERWRITE_CONFIRM, WTCD_GAME_SAVE_OVERWRITE_TITLE, WTCD_GAME_SAVE_TITLE, } from '../constant/messages'; import { wtcdGameQuickLoadConfirm } from '../data/settings'; import { DebugLogger } from '../DebugLogger'; import { h } from '../hs'; import { formatTimeSimple } from '../util/formatTime'; import { Content, ContentBlock } from './contentControl'; import { createWTCDErrorMessageFromError } from './createWTCDErrorMessageFromError'; import { createHint } from './hintControl'; import { confirm, Modal } from './modalControl'; import { FeatureProvider, defaultFeatureProvider } from '../../wtcd/FeatureProvider'; const debugLogger = new DebugLogger('WTCD Game Reader UI'); export class WTCDGameReaderUI { private reader: GameReader; private controlsBlock!: ContentBlock; private mainBlock: ContentBlock | null = null; public constructor( private content: Content, docIdentifier: string, private slideAnimation: boolean, wtcdRoot: WTCDRoot, private elementPreprocessor: ($element: HTMLElement) => void, featureProvider: FeatureProvider = defaultFeatureProvider, ) { this.reader = new GameReader( docIdentifier, wtcdRoot, this.onOutput, this.onError, featureProvider, ); } private started = false; public start() { if (this.started) { throw new Error('Already started.'); } this.started = true; this.controlsBlock = this.content.addBlock({ initElement: h('div.wtcd-game-control', h('.button-container', [ h('div', { onclick: this.onClickRestart }, WTCD_GAME_RESTART), h('div', { onclick: this.onClickSave }, WTCD_GAME_SAVE), h('div', { onclick: this.onClickLoad }, WTCD_GAME_LOAD), h('div', { onclick: this.onClickQuickSave }, WTCD_GAME_QUICK_SAVE), h('div', { onclick: this.onClickQuickLoad }, WTCD_GAME_QUICK_LOAD), ]), ) as HTMLDivElement, }); const startTime = Date.now(); this.reader.start(); debugLogger.log(`Game loaded in ${Date.now() - startTime}ms.`); } private onClickRestart = () => { const modal = new Modal(h('div', [ h('h1', WTCD_GAME_RESTART_TITLE), h('p', WTCD_GAME_RESTART_DESC), h('ul', [ h('li', WTCD_GAME_RESTART_ALL_DESC), h('li', WTCD_GAME_RESTART_DECISION_ONLY_DESC), ]), h('.button-container', [ h('div', { onclick: () => { this.reader.reset(true); createHint(WTCD_GAME_RESTART_OK, 1000); modal.close(); }}, WTCD_GAME_RESTART_ALL), h('div', { onclick: () => { this.reader.reset(false); createHint(WTCD_GAME_RESTART_OK, 1000); modal.close(); }}, WTCD_GAME_RESTART_DECISION_ONLY), h('div', { onclick: () => modal.close() }, WTCD_GAME_RESTART_CANCEL), ]), ])); modal.setDismissible(); modal.open(); } private onClickSave = () => { const modal = new Modal(h('div', [ h('h1', WTCD_GAME_SAVE_TITLE), h('.wtcd-save-button-list', this.reader.getSaves().map( (save, saveIndex) => { if (saveIndex === 0) { return null; // quick save } if (save === null) { return h('.new', { onclick: () => { this.reader.save(saveIndex); createHint(WTCD_GAME_SAVE_OK, 1000); modal.close(); }, }, WTCD_GAME_SAVE_NEW); } else { return h('.save', { onclick: () => { confirm( WTCD_GAME_SAVE_OVERWRITE_TITLE, '', WTCD_GAME_SAVE_OVERWRITE_CONFIRM, WTCD_GAME_SAVE_OVERWRITE_CANCEL, ).then(result => { if (result) { this.reader.save(saveIndex); createHint(WTCD_GAME_SAVE_OK, 1000); modal.close(); } }); }, }, [ h('.id', String(saveIndex)), h('.info', [ h('.state-desc', save.desc === '' ? WTCD_GAME_NO_DESC : save.desc), h('.date', formatTimeSimple(save.date)), ]), ]); } }, )), h('.button-container', { style: { 'margin-top': '1.2vh' } }, [ h('div', { onclick: () => modal.close() }, WTCD_GAME_SAVE_CANCEL), ]), ])); modal.setDismissible(); modal.open(); } private onClickLoad = () => { const modal = new Modal(h('div', [ h('h1', WTCD_GAME_LOAD_TITLE), h('.wtcd-save-button-list', this.reader.getSaves().map( (save, saveIndex) => { if (save === null) { return null; } return h('.save', { onclick: () => { this.reader.load(saveIndex); createHint(WTCD_GAME_LOAD_OK, 1000); modal.close(); }, }, [ saveIndex !== 0 ? h('.id', String(saveIndex)) : h('.small.id', WTCD_GAME_LOAD_QUICK), h('.info', [ h('.state-desc', save.desc === '' ? WTCD_GAME_NO_DESC : save.desc), h('.date', formatTimeSimple(save.date)), ]), ]); }, )), h('.button-container', { style: { 'margin-top': '1.2vh' } }, [ h('div', { onclick: () => modal.close() }, WTCD_GAME_LOAD_CANCEL), ]), ])); modal.setDismissible(); modal.open(); } private onClickQuickSave = () => { this.reader.save(0); createHint(WTCD_GAME_QUICK_SAVE_OK, 1000); } private onClickQuickLoad = () => { if (this.reader.getSaves()[0] === null) { createHint(WTCD_GAME_QUICK_LOAD_NOT_EXIST, 3000); return; } if (wtcdGameQuickLoadConfirm.getValue()) { confirm( WTCD_GAME_QUICK_LOAD_CONFIRM_TITLE, WTCD_GAME_QUICK_LOAD_CONFIRM_DESC, WTCD_GAME_QUICK_LOAD_CONFIRM_CONFIRM, WTCD_GAME_QUICK_LOAD_CONFIRM_CANCEL, ).then(result => { if (result) { this.reader.load(0); createHint(WTCD_GAME_QUICK_LOAD_OK, 1000); } }); } else { this.reader.load(0); createHint(WTCD_GAME_QUICK_LOAD_OK, 1000); } } private onOutput = (content: HTMLDivElement) => { this.elementPreprocessor(content); if (this.mainBlock === null) { debugLogger.log('Initialize main block.'); this.mainBlock = this.content.addBlock({ initElement: content, slidable: true, }); } else { debugLogger.log('Updating main block.'); this.content.scrollTo(this.controlsBlock.element.offsetTop); if (this.slideAnimation) { this.mainBlock.slideReplace(content); } else { this.mainBlock.directReplace(content); } } } private onError = (error: Error) => { debugLogger.warn('Game reader reported error.'); this.content.addBlock({ initElement: createWTCDErrorMessageFromError(error), }); } }
kink/kat
src/web/control/WTCDGameReaderUI.ts
TypeScript
unknown
8,065
import { backendUrl } from './backendControl'; import { AutoCache } from '../data/AutoCache'; import { DebugLogger } from '../DebugLogger'; import { loadChapterEvent } from './chapterControl'; // 《可穿戴科技》统计系统 // 本系统服务端开源,并且不收集任何个人信息。 // 其存在目的仅仅是为了让琳知道有多少读者在看,以满足她的虚荣心。 // // 服务端源代码:https://github.com/SCLeoX/wt_analytics const analyticsCache = new AutoCache<string, any>(relativePath => { return fetch(backendUrl + '/stats/count', { method: 'POST', body: relativePath, }); }, new DebugLogger('Analytics Cache')); loadChapterEvent.on((chapterRelativePath) => { if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') { return; } const startPageSpecifier = window.location.hash.split('~')[0]; // Remove arguments // Wait for 5 seconds in order to confirm the user is still reading the same // chapter. setTimeout(() => { if (startPageSpecifier !== window.location.hash.split('~')[0]) { return; } analyticsCache.get(chapterRelativePath); }, 5000); });
kink/kat
src/web/control/analyticsControl.ts
TypeScript
unknown
1,173
import { BACKEND_ERROR_COMMENT_TOO_LONG, BACKEND_ERROR_COMMENT_TOO_SHORT, BACKEND_ERROR_EMAIL_DUPLICATED, BACKEND_ERROR_EMAIL_INVALID, BACKEND_ERROR_EMAIL_TOO_LONG, BACKEND_ERROR_NAME_DUPLICATED, BACKEND_ERROR_NAME_INVALID, BACKEND_ERROR_NAME_TOO_LONG, BACKEND_ERROR_NAME_TOO_SHORT, BACKEND_ERROR_TOKEN_INVALID, BACKEND_ERROR_UNKNOWN } from '../constant/messages'; export const backendUrl = 'https://wtb.tepis.me'; export enum ErrorCode { NAME_DUPLICATED = 1, EMAIL_DUPLICATED = 2, NAME_TOO_LONG = 3, EMAIL_TOO_LONG = 4, EMAIL_INVALID = 5, COMMENT_TOO_LONG = 6, TOKEN_INVALID = 7, NAME_TOO_SHORT = 8, COMMENT_TOO_SHORT = 9, NAME_INVALID = 10, } export function getErrorMessage(errorCode: ErrorCode): string { switch (errorCode) { case ErrorCode.NAME_DUPLICATED: return BACKEND_ERROR_NAME_DUPLICATED; case ErrorCode.EMAIL_DUPLICATED: return BACKEND_ERROR_EMAIL_DUPLICATED; case ErrorCode.NAME_TOO_LONG: return BACKEND_ERROR_NAME_TOO_LONG; case ErrorCode.EMAIL_TOO_LONG: return BACKEND_ERROR_EMAIL_TOO_LONG; case ErrorCode.EMAIL_INVALID: return BACKEND_ERROR_EMAIL_INVALID; case ErrorCode.COMMENT_TOO_LONG: return BACKEND_ERROR_COMMENT_TOO_LONG; case ErrorCode.TOKEN_INVALID: return BACKEND_ERROR_TOKEN_INVALID; case ErrorCode.NAME_TOO_SHORT: return BACKEND_ERROR_NAME_TOO_SHORT; case ErrorCode.COMMENT_TOO_SHORT: return BACKEND_ERROR_COMMENT_TOO_SHORT; case ErrorCode.NAME_INVALID: return BACKEND_ERROR_NAME_INVALID; default: return BACKEND_ERROR_UNKNOWN; } } export type ResultOf<T> = T extends (...[]: any) => Promise<infer U> ? U : never; export function fetchInit(token: string): Promise<{ success: false } | { success: true, user_name: string, email?: string, display_name: string, mentions: number, }> { return fetch(`${backendUrl}/user/init`, { cache: 'no-cache', method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ token }), }).then(response => response.json()); } export function fetchUpdateProfile(token: string, displayName: string, email?: string): Promise<{ success: true } | { success: false, code: ErrorCode, }> { return fetch(`${backendUrl}/user/updateProfile`, { cache: 'no-cache', method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ token, display_name: displayName, email }), }).then(response => response.json()); } export interface CommentData { body: string; create_timestamp: number; update_timestamp: number; relative_path: string; id: number; user: { avatar_url: string; user_name: string; display_name: string; }; } export function fetchGetChapterComments(pageName: string): Promise<Array<CommentData>> { return fetch(`${backendUrl}/comment/getChapter?relative_path=${pageName}`, { cache: 'no-cache', method: 'GET', }).then(response => response.json()); } export function fetchGetRecentComments(): Promise<Array<CommentData>> { return fetch(`${backendUrl}/comment/getRecent`, { cache: 'no-cache', method: 'GET', }).then(response => response.json()); } export function fetchGetRecentMentionedComments(token?: string): Promise<Array<CommentData>> { if (token === undefined) { return Promise.resolve([]); } return fetch(`${backendUrl}/comment/getRecentMentioned`, { cache: 'no-cache', method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ token }), }).then(response => response.json()); } export function fetchSendComment(token: string, pageName: string, content: string): Promise<{ success: true } | { success: false, code: ErrorCode, }> { return fetch(`${backendUrl}/comment/send`, { cache: 'no-cache', method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ token, relative_path: pageName, content, }), }).then(response => response.json()); } export function fetchRegister(displayName: string, email?: string): Promise<{ success: true, token: string, user_name: string, } | { success: false, code: ErrorCode, }> { return fetch(`${backendUrl}/user/register`, { cache: 'no-cache', method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ display_name: displayName, email, }), }).then(response => response.json()); } export function fetchDeleteComment(token: string, commentId: number): Promise<void> { return fetch(`${backendUrl}/comment/delete`, { cache: 'no-cache', method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ token, comment_id: commentId, }), }).then(() => undefined); }
kink/kat
src/web/control/backendControl.ts
TypeScript
unknown
4,974
import { $e } from '../$e'; import { Chapter, WTCDChapter, WTCDChapterFlow, WTCDChapterGame } from '../../Data'; import { FlowReader } from '../../wtcd/FlowReader'; import { WTCDParseResult, WTCDRoot } from '../../wtcd/types'; import { CHAPTER_FAILED, GO_TO_MENU, NEXT_CHAPTER, PREVIOUS_CHAPTER } from '../constant/messages'; import { AutoCache } from '../data/AutoCache'; import { authorInfoMap, ChapterContext, relativePathLookUpMap } from '../data/data'; import { chapterHref, pageHref, tagSearchHref } from '../data/hrefs'; import { updateChapterProgress } from '../data/readingProgress'; import { chapterRecommendationCount, earlyAccess, gestureSwitchChapter, showAbandonedChapters } from '../data/settings'; import { DebugLogger } from '../DebugLogger'; import { Event } from '../Event'; import { h } from '../hs'; import { SwipeDirection, swipeEvent } from '../input/gestures'; import { ArrowKey, arrowKeyPressEvent, escapeKeyPressEvent } from '../input/keyboard'; import { getTextNodes, id } from '../util/DOM'; import { formatRelativePath } from '../util/formatRelativePath'; import { removePotentialSuffix } from '../util/string'; import { tagSpan } from '../util/tag'; import { smartThrottle } from '../util/throttle'; import { resetUrlArgumentsTo } from '../util/urlArguments'; import { addPushHelperBlock } from './pushHelper'; import { loadChapterComments } from './commentsControl'; import { loadContactInfo } from './contactInfoControl'; import { Content, ContentBlock, ContentBlockSide, ContentBlockStyle, focus, newContent, Side } from './contentControl'; import { createWTCDErrorMessage } from './createWTCDErrorMessage'; import { createWTCDErrorMessageFromError } from './createWTCDErrorMessageFromError'; import { followQuery } from './followQuery'; import { Layout, setLayout } from './layoutControl'; import { enterMenuMode } from './menuControl'; import { isAnyModalOpened, Modal } from './modalControl'; import { resetProgressIndicator, setNavbarPath, setProgressIndicator } from './navbarControl'; import { processElements } from './processElements'; import { recommend } from './recommendControl'; import { WTCDFeatureProvider } from './WTCDFeatureProvider'; import { WTCDGameReaderUI } from './WTCDGameReaderUI'; import { loadWtcupInfo, loadWtcupInfoPre } from './wtcupInfoControl'; import { addPreloaderBlock } from './preloaderBlock'; type Selection = [number, number, number, number]; const debugLogger = new DebugLogger('Chapter Control'); export const loadChapterEvent = new Event<string>(); /** This is only used for determining the direction of animation when changing chapter. */ let lastChapterCtx: ChapterContext | null = null; const select = (textNodes: Array<Text>, [ anchorNodeIndex, anchorOffset, focusNodeIndex, focusOffset, ]: Selection) => { const anchorNode = textNodes[anchorNodeIndex]; const focusNode = textNodes[focusNodeIndex]; if (anchorNode === undefined || focusNode === undefined) { return; } document.getSelection()!.setBaseAndExtent( anchorNode, anchorOffset, focusNode, focusOffset, ); const element = anchorNode.parentElement; if (element !== null && (typeof element.scrollIntoView) === 'function') { element.scrollIntoView(); } }; export function canChapterShown(chapter: Chapter) { return (earlyAccess.getValue() || !chapter.isEarlyAccess) && (!chapter.hidden) && (showAbandonedChapters.getValue() || !chapter.abandoned); } function findNextChapter(chapterCtx: ChapterContext) { const index = chapterCtx.inFolderIndex; const folderChapters = chapterCtx.folder.children; for (let i = index + 1; i < folderChapters.length; i++) { const child = folderChapters[i]; if (child.type !== 'folder' && canChapterShown(child)) { return child; } } return null; } function findPreviousChapter(chapterCtx: ChapterContext) { const index = chapterCtx.inFolderIndex; const folderChapters = chapterCtx.folder.children; for (let i = index - 1; i >= 0; i--) { const child = folderChapters[i]; if (child.type !== 'folder' && canChapterShown(child)) { return child; } } return null; } function getChapterRelativeLink(chapter: Chapter) { return `${window.location.pathname}#/chapter/${chapter.htmlRelativePath}`; } function navigateToChapter(chapter: Chapter) { window.location.href = getChapterRelativeLink(chapter); } const chaptersCache = new AutoCache<string, string>( chapterHtmlRelativePath => { const url = `./chapters/${chapterHtmlRelativePath}`; debugLogger.log(`Loading chapter from ${url}.`); return fetch(url).then(response => response.text()); }, new DebugLogger('Chapters Cache'), ); function updateNavbar(htmlRelativePath: string) { setNavbarPath([ { display: '所有章节', hash: '#/menu/章节选择/所有章节', }, ...htmlRelativePath.split('/').map((segment, index, split) => { segment = segment.replace(/-/g, ' '); if (index === split.length - 1) { // Last element return { display: removePotentialSuffix(segment, '.html'), hash: null, }; } else { return { display: segment, hash: `#/menu/章节选择/所有章节/${split.slice(0, index + 1).join('/')}`, }; } }) ]); } function addAuthorsInfoBlock(content: Content, chapter: Chapter) { if (chapter.authors.length > 0) { const $authorsDiv = h('.authors', h('h3', '本文作者'), h('.outer-container', ...chapter.authors.map(authorRole => { const authorInfo = authorInfoMap.get( authorRole.name ) ?? { name: authorRole.name, avatar: `https://ui-avatars.com/api/?name=${encodeURIComponent(authorRole.name)}`, }; return h('.author-container', { onclick: () => { window.history.pushState(null, document.title, pageHref(`author/${authorInfo.name}`)); followQuery(); }, }, h('img.avatar', { src: authorInfo.avatar, }), h('.author-role-container', h('.role', authorRole.role), h('.name', authorInfo.name), ), ); }), h('.reprint', { href: '#', onclick: ((event: any) => { event.preventDefault(); const modal = new Modal(h('div', h('h1', '转载须知'), h('p', '《可穿戴科技》内所有文章均以 ', h('a.regular', { target: '_blank', href: 'https://creativecommons.org/licenses/by-nc-nd/4.0/', rel: 'noopener noreferrer', }, 'CC BY-NC-ND 4.0'), ' 协议发布。转载时请注明以下信息:', ), h('pre.wrapping', h('code', 'This is an exerpt from the text《可穿戴科技/Wearable Technology》(https://wt.tepis.me)。' + chapter.authors.map(authorInfo => authorInfo.role + ':' + authorInfo.name).join(',') + '。本文以 CC BY-NC-ND 4.0 协议发布,转载请注明上述所有信息。' )), h('.button-container', [ h('div', { onclick: () => { modal.close(); }, }, '我知道了'), ]), )); modal.setDismissible(); modal.open(); }), }, h('div', '转载须知')), ), ) as HTMLDivElement; content.addBlock({ initElement: $authorsDiv, side: ContentBlockSide.LEFT }); } } function addTagInfoBlock(content: Content, chapter: Chapter) { if (chapter.tags !== undefined) { content.addBlock({ initElement: ( <div className='tags'> <h3>本文标签</h3> { chapter.tags.map(tag => ( <a href={ tagSearchHref(tag) }> { tagSpan(tag, false) } </a> )) } </div> ) as HTMLDivElement, side: ContentBlockSide.LEFT, }); } else if (!chapter.htmlRelativePath.includes('META')) { content.addBlock({ initElement: ( <div> <h3>The tags for this article is missing</h3> <p>There are no tags for this article. If you are willing to contribute by adding tags, <a className='regular' href={ chapterHref('META/协助打标签.html') }>you can do so here</a>.</p> </div> ), side: ContentBlockSide.LEFT, }); } } function addRecommendedBlock(content: Content, chapter: Chapter) { if (chapterRecommendationCount.getValue() === 0) { return; } if (chapter.tags !== undefined && chapter.tags.length > 0) { recommend(chapter).then(results => { if (results === null) { return; } results = results .filter(({ chapter: targetChapter }) => targetChapter.htmlRelativePath !== chapter.htmlRelativePath) .filter((_, index) => index < (chapterRecommendationCount.getValue() * 5)); content.addBlock({ initElement: ( <div className='recommended-chapters'> <h3>Recommended Chapters</h3> <ul> { results.map(({ chapter: recommendedChapter, score }) => ( <li> <a className='regular' href={ chapterHref(recommendedChapter.htmlRelativePath) }> [{ (score * 100).toFixed(0) }%] { formatRelativePath(recommendedChapter.htmlRelativePath) } </a> </li> )) } </ul> <p>你也可以<a className='regular' href={ chapterHref('META/阅读器技术文档/推荐算法.html') }>点此查看《可穿戴科技》当前使用的推荐算法</a>。</p> </div> ) as HTMLDivElement, side: ContentBlockSide.RIGHT, }); }).catch(error => debugLogger.error(error)); } } function loadChapter( chapterHtmlRelativePath: string, selection?: Selection, side: Side = Side.LEFT, ) { debugLogger.log('Load chapter', chapterHtmlRelativePath, 'with selection', selection); loadChapterEvent.emit(chapterHtmlRelativePath); const chapterCtx = relativePathLookUpMap.get(chapterHtmlRelativePath)!; lastChapterCtx = chapterCtx; document.title = formatRelativePath(chapterHtmlRelativePath) + ' - 可穿戴科技'; window.history.replaceState(null, document.title); updateNavbar(chapterHtmlRelativePath); const content = newContent(side); maybeAddEarlyAccessWarning(chapterCtx, content); maybeAddAbandonedWarning(chapterCtx, content); const loadingBlock = addPreloaderBlock(content); setLayout(Layout.MAIN); function loadPrevChapter() { const previousChapter = findPreviousChapter(chapterCtx); if (previousChapter !== null) { navigateToChapter(previousChapter); } } function loadNextChapter() { const nextChapter = findNextChapter(chapterCtx); if (nextChapter !== null) { navigateToChapter(nextChapter); } } registerSwipeEvents(loadPrevChapter, loadNextChapter, content); registerArrowKeyEvents(loadPrevChapter, loadNextChapter, content); attachEscapeEvent(content); chaptersCache.get(chapterHtmlRelativePath).then(text => { if (content.isDestroyed) { debugLogger.log('Chapter loaded, but abandoned since the original ' + 'content page is already destroyed.'); return; } debugLogger.log('Chapter loaded.'); loadingBlock.directRemove(); loadWtcupInfoPre(content, chapterHtmlRelativePath); content.appendLeftSideContainer(); const mainBlock = insertContent(content, text, chapterCtx.chapter); const postMainBlock = mainBlock ?? content.addBlock(); content.appendRightSideContainer(); addAuthorsInfoBlock(content, chapterCtx.chapter); addTagInfoBlock(content, chapterCtx.chapter); addPushHelperBlock(content, chapterCtx.chapter); addRecommendedBlock(content, chapterCtx.chapter); const textNodes = getTextNodes(postMainBlock.element); restoreSelections(selection, textNodes); registerSelectionChangeListener(textNodes, content); addPageSwitcherBlock(chapterCtx, postMainBlock); startUpdatingProgressBar(mainBlock, content, chapterCtx); // Re-focus the rect so it is arrow-scrollable setTimeout(() => { focus(); }, 1); loadWtcupInfo(content); loadContactInfo(content); loadChapterComments(chapterCtx, content); }).catch(error => { debugLogger.error(`Failed to load chapter.`, error); loadingBlock.element.innerText = CHAPTER_FAILED; }); } export enum ErrorType { COMPILE, RUNTIME, INTERNAL, } function registerSelectionChangeListener(textNodes: Array<Text>, content: Content) { const selectionChangeListener = getSelectionChangeListener(textNodes); document.addEventListener('selectionchange', selectionChangeListener); content.leavingEvent.once(() => { document.removeEventListener('selectionchange', selectionChangeListener); }); } function restoreSelections(selection: Selection | undefined, textNodes: Array<Text>) { if (selection !== undefined) { if (id('warning') === null) { select(textNodes, selection); } else { id('warning').addEventListener('click', () => { select(textNodes, selection); }); } } } function maybeAddAbandonedWarning(chapterCtx: ChapterContext, content: Content) { if (chapterCtx.chapter.abandoned) { content.addBlock({ initElement: ( <div> <h1>Chapter Abandoned</h1> <p>The author of this chapter has abandoned it, and it is no longer being worked on. The content will remain incomplete.</p> </div> ), style: ContentBlockStyle.WARNING, }); } } function maybeAddEarlyAccessWarning(chapterCtx: ChapterContext, content: Content) { if (chapterCtx.chapter.isEarlyAccess) { content.addBlock({ initElement: ( <div> <h1>Chapter in Progress</h1> <p>This chapter is still being written, so it may contain incomplete, inaccurate, or out-of-date information/details.</p> </div> ), style: ContentBlockStyle.WARNING, }); } } function addPageSwitcherBlock(chapterCtx: ChapterContext, postMainBlock: ContentBlock) { const prevChapter = findPreviousChapter(chapterCtx); const nextChapter = findNextChapter(chapterCtx); postMainBlock.element.appendChild(h('div.page-switcher', [ // 上一章 (prevChapter !== null) ? h('a', { href: getChapterRelativeLink(prevChapter), }, PREVIOUS_CHAPTER) : null, // 返回菜单 h('a', { href: window.location.pathname, onclick: (event: MouseEvent) => { event.preventDefault(); enterMenuMode(); }, }, GO_TO_MENU), // 下一章 (nextChapter !== null) ? h('a', { href: getChapterRelativeLink(nextChapter), }, NEXT_CHAPTER) : null, ])); } function startUpdatingProgressBar(mainBlock: ContentBlock | undefined, content: Content, chapterCtx: ChapterContext) { if (mainBlock !== undefined) { const updateProgress = smartThrottle(() => { const scrollableRange = mainBlock.element.clientHeight - content.$element.clientHeight; let progress; if (scrollableRange > 0) { progress = (content.$element.scrollTop - mainBlock.element.offsetTop) / scrollableRange; } else { progress = (content.$element.scrollTop + content.$element.clientHeight) > (mainBlock.element.offsetTop + mainBlock.element.clientHeight) ? 1 : 0; } progress = Math.min(progress, 1); progress = Math.max(progress, 0); setProgressIndicator(progress); updateChapterProgress(chapterCtx.chapter.htmlRelativePath, progress) .catch(error => debugLogger.warn(`Failed to save chapter progress for ${chapterCtx.chapter.htmlRelativePath}:`, error)); }, 100); content.scrollEvent.on(() => { updateProgress(); }); content.leavingEvent.on(() => { resetProgressIndicator(); }); } } function getSelectionChangeListener(textNodes: Array<Text>) { return smartThrottle(() => { const selection = document.getSelection(); const urlArguments = new Map<string, string>(); if (selection !== null) { const anchor = ((selection.anchorNode instanceof HTMLElement) ? selection.anchorNode.firstChild : selection.anchorNode) as Text; const anchorNodeIndex = textNodes.indexOf(anchor); const focus = ((selection.focusNode instanceof HTMLElement) ? selection.focusNode.firstChild : selection.focusNode) as Text; const focusNodeIndex = textNodes.indexOf(focus); if ((anchorNodeIndex !== -1) && (focusNodeIndex !== -1) && !(anchorNodeIndex === focusNodeIndex && selection.anchorOffset === selection.focusOffset)) { if ((anchorNodeIndex < focusNodeIndex) || (anchorNodeIndex === focusNodeIndex && selection.anchorOffset < selection.focusOffset)) { urlArguments.set('selection', `${anchorNodeIndex},${selection.anchorOffset},${focusNodeIndex},${selection.focusOffset}`); } else { urlArguments.set('selection', `${focusNodeIndex},${selection.focusOffset},${anchorNodeIndex},${selection.anchorOffset}`); } } } resetUrlArgumentsTo(urlArguments); }, 250); } function attachEscapeEvent(content: Content) { escapeKeyPressEvent.onUntil(() => { if (isAnyModalOpened()) { return; } enterMenuMode(); }, content.leavingEvent); } function registerArrowKeyEvents(loadPrevChapter: () => void, loadNextChapter: () => void, content: Content) { arrowKeyPressEvent.onUntil(arrowKey => { if (isAnyModalOpened()) { return; } if (arrowKey === ArrowKey.LEFT) { loadPrevChapter(); } else if (arrowKey === ArrowKey.RIGHT) { loadNextChapter(); } }, content.leavingEvent); } function registerSwipeEvents(loadPrevChapter: () => void, loadNextChapter: () => void, content: Content) { swipeEvent.onUntil(direction => { if (!gestureSwitchChapter.getValue()) { return; } if (isAnyModalOpened()) { return; } if (direction === SwipeDirection.TO_RIGHT) { // 上一章 loadPrevChapter(); } else if (direction === SwipeDirection.TO_LEFT) { // 下一章 loadNextChapter(); } }, content.leavingEvent); } function insertContent(content: Content, text: string, chapter: Chapter) { switch (chapter.type) { case 'Markdown': return loadMarkdown(content, text); case 'WTCD': { loadWTCD(text, content, chapter); } } } function loadWTCD(text: string, content: Content, chapter: WTCDChapter) { const wtcdParseResult: WTCDParseResult = JSON.parse(text); if (wtcdParseResult.error === true) { content.addBlock({ initElement: createWTCDErrorMessage({ errorType: ErrorType.COMPILE, message: wtcdParseResult.message, internalStack: wtcdParseResult.internalStack, }), }); return; } const featureProvider = new WTCDFeatureProvider(chapter); switch (chapter.preferredReader) { case 'flow': { loadWTCDFlowReader(chapter, wtcdParseResult, featureProvider, content); return; } case 'game': { loadWTCDGameReader(content, chapter, wtcdParseResult, featureProvider); return; } } } function loadWTCDGameReader(content: Content, chapter: WTCDChapterGame, wtcdParseResult: { error: false, wtcdRoot: WTCDRoot, }, featureProvider: WTCDFeatureProvider) { new WTCDGameReaderUI( content, chapter.htmlRelativePath, chapter.slideAnimation, wtcdParseResult.wtcdRoot, processElements, featureProvider ).start(); } function loadWTCDFlowReader(chapter: WTCDChapterFlow, wtcdParseResult: { error: false, wtcdRoot: WTCDRoot, }, featureProvider: WTCDFeatureProvider, content: Content) { const flowReader = new FlowReader( chapter.htmlRelativePath, wtcdParseResult.wtcdRoot, createWTCDErrorMessageFromError, processElements, featureProvider ); const $wtcdContainer = content.addBlock().element; flowReader.renderTo($wtcdContainer); } function loadMarkdown(content: Content, text: string) { const block = content.addBlock(); block.element.innerHTML = text; processElements(block.element); return block; } function followQueryToChapter(relativePath: string, args: Map<string, string>): boolean { const chapterCtx = relativePathLookUpMap.get(relativePath); if (chapterCtx === undefined) { // Cannot find chapter return false; } const side = ( lastChapterCtx !== null && chapterCtx.inFolderIndex < lastChapterCtx.inFolderIndex ) ? Side.LEFT : Side.RIGHT; const selection: Array<number> = args.has('selection') ? args.get('selection')!.split(',').map(str => +str) : []; if (selection.length !== 4 || !selection.every( num => (num >= 0) && (num % 1 === 0) && (!Number.isNaN(num)) && (Number.isFinite(num)), )) { loadChapter(relativePath, undefined, side); } else { loadChapter( relativePath, selection as [number, number, number, number], side, ); } return true; } export function chapterPathHandler(path: string, args: Map<string, string>) { const handled = followQueryToChapter(path, args); return handled; }
kink/kat
src/web/control/chapterControl.tsx
TypeScript
unknown
21,496
import { COMMENTS_DELETE, COMMENTS_DELETE_CONFIRMATION, COMMENTS_DELETING, COMMENTS_FAILED, COMMENTS_LOADED, COMMENTS_LOADING, COMMENTS_LOSE_EDITED_CANCEL, COMMENTS_LOSE_EDITED_CONFIRM, COMMENTS_LOSE_EDITED_TITLE, COMMENTS_MENTION_LOADED, COMMENTS_MENTION_REPLIED_OK, COMMENTS_MENTION_REPLIED_TITLE, COMMENTS_MENTION_SECTION, COMMENTS_MODIFIED_DATE, COMMENTS_RECENT_LOADED, COMMENTS_RECENT_SECTION, COMMENTS_REPLY, COMMENTS_SECTION, COMMENTS_SEND, COMMENTS_SENDING, COMMENTS_SEND_CONFIRM, COMMENTS_SEND_DISPLAY_NAME_0, COMMENTS_SEND_DISPLAY_NAME_1, COMMENTS_SEND_DISPLAY_NAME_EDIT, COMMENTS_SEND_DISPLAY_NAME_PREFIX, COMMENTS_SEND_EMAIL_INPUT_PREFIX, COMMENTS_SEND_HINT, COMMENTS_SEND_TITLE, COMMENTS_SUBMIT_BY, GENERIC_CANCEL, GENERIC_CONFIRM, GENERIC_INTERNET_ERROR, GO_TO_MENU } from '../constant/messages'; import { AutoCache, AutoSingleCache } from '../data/AutoCache'; import { ChapterContext } from '../data/data'; import { chapterHref } from '../data/hrefs'; import { useComments } from '../data/settings'; import { DebugLogger } from '../DebugLogger'; import { h } from '../hs'; import { autoExpandTextArea, linkButton } from '../util/DOM'; import { formatRelativePath } from '../util/formatRelativePath'; import { formatTimeRelative } from '../util/formatTime'; import { padName } from '../util/padName'; import { CommentData, fetchDeleteComment, fetchGetChapterComments, fetchGetRecentComments, fetchGetRecentMentionedComments, fetchSendComment, getErrorMessage, ResultOf } from './backendControl'; import { Content, ContentBlock } from './contentControl'; import { enterMenuMode } from './menuControl'; import { confirm, Modal, notify, showGenericError, showGenericLoading } from './modalControl'; import { getCurrentUser, registerWithResultPopup, showUpdateProfileModal, tokenItem } from './userControl'; const debugLogger = new DebugLogger('Comments Control'); async function promptDeleteComment(pageName: string, commentId: number) { if (await confirm(COMMENTS_DELETE, COMMENTS_DELETE_CONFIRMATION, GENERIC_CONFIRM, GENERIC_CANCEL)) { const loadingModal = showGenericLoading(COMMENTS_DELETING); try { await fetchDeleteComment(tokenItem.getValue()!, commentId); } catch (error) { showGenericError(GENERIC_INTERNET_ERROR); debugLogger.error(error); return false; } finally { loadingModal.close(); } recentCommentsCache.delete(); chapterCommentsCache.delete(pageName); return true; } return false; } function createCommentElement(comment: CommentData, onComment: () => void, showPath: boolean) { const pageName = comment.relative_path; const actionButton = (comment.user.user_name === getCurrentUser()?.userName) ? h('a.action', { // 删除按钮 onclick: () => { promptDeleteComment(pageName!, comment.id).then(deleted => { if (deleted) { $comment.remove(); } }); }, }, COMMENTS_DELETE) : pageName && h('a.action', { // 回复按钮 onclick: () => { promptComment(pageName!, '@' + comment.user.user_name + ' ').then(replied => { if (replied) { onComment(); } }); }, }, COMMENTS_REPLY); const $comment = h('.comment', [ h('img.avatar', { src: comment.user.avatar_url }), h('.author', comment.user.display_name), h('.time', COMMENTS_SUBMIT_BY.replace('$', ` @${comment.user.user_name} `) + formatTimeRelative(new Date(comment.create_timestamp)) + ((comment.create_timestamp === comment.update_timestamp) ? '' : COMMENTS_MODIFIED_DATE.replace('$', formatTimeRelative(new Date(comment.update_timestamp)))) ), actionButton, ...comment.body.split('\n\n').map(paragraph => h('p', paragraph)), showPath ? h('p', h('a.dimmed', { href: chapterHref(pageName), }, `发表于${padName(formatRelativePath(pageName))}`)) : null, ]); return $comment; } function loadComments( content: Content, loadComment: () => Promise<Array<CommentData>>, title: string, desc: string, onComment: () => void, backButton: boolean = true, commentingPageName?: string, ) { const $commentsStatus = h('p', COMMENTS_LOADING); const $comments = h('.comments', [ h('h1', title), $commentsStatus, ]) as HTMLDivElement; const block = content.addBlock({ initElement: $comments, }); block.onEnteringView(() => { loadComment().then(data => { if (content.isDestroyed) { debugLogger.log('Comments loaded, but abandoned since the original ' + 'content page is already destroyed.'); return; } debugLogger.log('Comments loaded.'); $commentsStatus.innerText = desc; const appendCreateComment = (commentingPageName: string) => { $comments.appendChild( h('.create-comment', { onclick: () => { promptComment(commentingPageName).then(commented => { if (commented) { onComment(); } }); }, }, COMMENTS_SEND), ); }; if (commentingPageName !== undefined && data.length >= 6) { appendCreateComment(commentingPageName); } data.forEach((comment: any) => { $comments.appendChild(createCommentElement(comment, onComment, commentingPageName === undefined)); }); if (commentingPageName !== undefined) { appendCreateComment(commentingPageName); } }).catch(error => { $commentsStatus.innerText = COMMENTS_FAILED; debugLogger.error('Failed to load comments.', error); }).then(() => { if (backButton) { $comments.appendChild(createToMenuButton()); } }); }); return block; } export function createToMenuButton() { return h('div.page-switcher', [ h('a', { href: window.location.pathname, onclick: (event: MouseEvent) => { event.preventDefault(); enterMenuMode(); }, }, GO_TO_MENU), ]); } export async function sendComment(token: string, pageName: string, content: string) { let result: ResultOf<typeof fetchSendComment>; try { result = await fetchSendComment(token, pageName, content); } catch (error) { showGenericError(GENERIC_INTERNET_ERROR); debugLogger.error(error); return false; } if (!result.success) { showGenericError(getErrorMessage(result.code)); return false; } else { // Cache invalidation recentCommentsCache.delete(); chapterCommentsCache.delete(pageName); return true; } } export function promptComment(pageName: string, preFilled?: string) { return new Promise<boolean>((resolve, reject) => { const $nameInput = h('input') as HTMLInputElement; const $emailInput = h('input') as HTMLInputElement; const user = getCurrentUser(); const $displayNameSpan = h('span'); const updateDisplayName = () => { if (user !== null) { $displayNameSpan.innerText = padName(user.displayName); } }; updateDisplayName(); const name = tokenItem.exists() ? user === null ? h('div', { style: { 'margin-bottom': '0.8em' } }) : h('p', [ COMMENTS_SEND_DISPLAY_NAME_0, $displayNameSpan, COMMENTS_SEND_DISPLAY_NAME_1, linkButton(COMMENTS_SEND_DISPLAY_NAME_EDIT, () => { showUpdateProfileModal().then(updateDisplayName); }), ]) : [ h('.input-group', [ h('span', COMMENTS_SEND_DISPLAY_NAME_PREFIX), $nameInput, ]), h('.input-group', [ h('span', COMMENTS_SEND_EMAIL_INPUT_PREFIX), $emailInput, ]), ]; const $textarea = h('textarea.general.large') as HTMLTextAreaElement; if (preFilled !== undefined) { $textarea.value = preFilled; } const onSubmit = async () => { const loadingModal = showGenericLoading(COMMENTS_SENDING); try { if (!tokenItem.exists()) { if (!(await registerWithResultPopup( $nameInput.value, $emailInput.value.trim() === '' ? null : $emailInput.value ))) { return false; } } return await sendComment(tokenItem.getValue()!, pageName, $textarea.value); } finally { loadingModal.close(); } }; const modal = new Modal(h('div', [ h('h1', COMMENTS_SEND_TITLE), h('p', COMMENTS_SEND_HINT), $textarea, name, h('.button-container', [ h('div', { // Submit onclick: () => { onSubmit().then(commented => { if (commented) { modal.close(); resolve(true); } return commented; }).catch(reject); } }, COMMENTS_SEND_CONFIRM), h('div', { onclick: () => { if ($textarea.value === '') { modal.close(); resolve(false); } else { confirm( COMMENTS_LOSE_EDITED_TITLE, '', COMMENTS_LOSE_EDITED_CONFIRM, COMMENTS_LOSE_EDITED_CANCEL ).then(confirmed => { if (confirmed) { modal.close(); resolve(false); } }); } } }, GENERIC_CANCEL), ]), ])); modal.open(); $textarea.focus(); autoExpandTextArea($textarea); }); } const chapterCommentsCache = new AutoCache<string, Array<CommentData>>( fetchGetChapterComments, new DebugLogger('Chapter Comments Cache'), ); export function loadChapterComments(chapterCtx: ChapterContext, content: Content) { if (useComments.getValue() === false) { return; } let block: ContentBlock | null = null; const pageName = chapterCtx.chapter.htmlRelativePath; function load() { if (block !== null) { block.directRemove(); } block = loadComments( content, () => chapterCommentsCache.get(pageName), COMMENTS_SECTION, COMMENTS_LOADED, load, false, chapterCtx.chapter.htmlRelativePath, ); } load(); } const recentCommentsCache = new AutoSingleCache<Array<CommentData>>( fetchGetRecentComments, new DebugLogger('Recent Comments Cache'), ); export function loadRecentComments(content: Content) { let block: ContentBlock | null = null; function load() { if (block !== null) { block.directRemove(); } block = loadComments( content, () => recentCommentsCache.get(), COMMENTS_RECENT_SECTION, COMMENTS_RECENT_LOADED, load, ); } load(); } const recentMentionedCommentsCache = new AutoSingleCache<Array<CommentData>>( () => fetchGetRecentMentionedComments(tokenItem.getValue() ?? undefined), new DebugLogger('Recent Mentioned Comments Cache'), ); export function loadRecentMentions(content: Content, token: string) { loadComments( content, () => recentMentionedCommentsCache.get(), COMMENTS_MENTION_SECTION, COMMENTS_MENTION_LOADED, () => { notify(COMMENTS_MENTION_REPLIED_TITLE, '', COMMENTS_MENTION_REPLIED_OK); }, ); }
kink/kat
src/web/control/commentsControl.ts
TypeScript
unknown
11,301
import { $e } from '../$e'; import { contactInfo } from '../data/settings'; import { h } from '../hs'; import { Content } from './contentControl'; export function contactInfoElement(){ return ( <ul> <li> Telegram 讨论组: <a style={{ wordBreak: 'break-all' }} href='https://t.me/joinchat/Dt8_WlJnmEwYNbjzlnLyNA' className='regular' target='_blank' > https://t.me/joinchat/Dt8_WlJnmEwYNbjzlnLyNA </a> <ul> <li>非常欢迎色情,但是若要讨论血腥内容,请用群描述内的 R18G 群组。</li> </ul> </li> <li> Telegram 更新推送频道: <a style={{ wordBreak: 'break-all' }} href='https://t.me/joinchat/AAAAAEpkRVwZ-3s5V3YHjA' className='regular' target='_blank' > https://t.me/joinchat/AAAAAEpkRVwZ-3s5V3YHjA </a> </li> <li> Twitter: <a href='https://twitter.com/NovelWTech' className='regular' target='_blank'>@NovelWTech</a> </li> <li> Discord: <a style={{ wordBreak: 'break-all' }} href='https://discord.gg/HyKA6XCp6E' className='regular' target='_blank'> https://discord.gg/HyKA6XCp6E </a> <ul> <li>非常欢迎色情,但是若要讨论血腥内容,请用“#血腥猎奇”频道。</li> </ul> </li> {/* <li> QQ 群 <ul> <li style={{ fontWeight: 'bold', }}>不到万不得已请不要使用 QQ 群!请考虑使用上述明确允许色情内容的联系方式!QQ 群非常容易被封!我们的五百人 ① 群已经被封了!</li> <li style={{ fontWeight: 'bold', textDecoration: 'underline', }}>严格禁止政治/色情媒体,发现一次就踢了!</li> <li> 只收大号,小号勿扰! <ul> <li>如果申请被拒绝,说明等级不够高,请使用大号。如果大号也被拒绝,请使用别的联系方式(推荐 Telegram 讨论组)。</li> </ul> </li> <li>因人数限制,满人时会踢出不活跃用户。若要潜水,请使用别的联系方式(推荐 Telegram 讨论组)。</li> <li>再重复一遍:不到万不得已,不要用 QQ 群!大多数人都在 Telegram 讨论组。</li> <li>二群:1154421904</li> </ul> </li> */} </ul> ); } export function loadContactInfo(content: Content) { if (!contactInfo.getValue()) { return; } const block = content.addBlock({ initElement: h('div', h('h3', '欢迎加入《可穿戴科技》相关讨论组'), contactInfoElement(), h('a.regular', { href: '#', onclick: ((event: any) => { event.preventDefault(); block.directRemove(); contactInfo.setValue(false); }), }, '点此永久关闭本提示'), ), }); }
kink/kat
src/web/control/contactInfoControl.tsx
TypeScript
unknown
3,180
import { $e } from '../$e'; import { animation } from '../data/settings'; import { DebugLogger } from '../DebugLogger'; import { Event } from '../Event'; import { h } from '../hs'; import { ArrowKey, arrowKeyPressEvent } from '../input/keyboard'; import { forceReflow, id } from '../util/DOM'; import { getCurrentLayout, Layout, layoutChangeEvent } from './layoutControl'; import { MonoDimensionTransitionControl } from './MonoDimensionTransitionControl'; const $contentContainer = id('content-container'); const debugLogger = new DebugLogger('Content Control'); export enum Side { LEFT, RIGHT, } function setSide($element: HTMLElement, side: Side) { if (side === Side.LEFT) { $element.classList.add('left'); $element.classList.remove('right'); } else { $element.classList.add('right'); $element.classList.remove('left'); } } function otherSide(side: Side) { return side === Side.LEFT ? Side.RIGHT : Side.LEFT; } let currentContent: Content | null = null; export function getCurrentContent() { return currentContent; } export function focus() { if (currentContent !== null) { currentContent.$element.focus({ // Why: // https://stackoverflow.com/questions/26782998/why-does-calling-focus-break-my-css-transition preventScroll: true, }); } } /** Global scrolling event */ export const contentScrollEvent = new Event<{ scrollTop: number }>(); export const contentChangeEvent = new Event<{ newContent: Content }>(); /** * 创建一个新的 Content 并替换之前的 Content。 * * @param side 如果有动画,那么入场位置。 * @returns 创建的 Content 对象 */ export function newContent(side: Side): Content { const newContent = new Content(); currentContent?.ensureLeavingTriggered(); if (getCurrentLayout() === Layout.OFF) { if (currentContent !== null) { currentContent.destroy(); } } else { if (animation.getValue()) { // Animation is enabled if (currentContent !== null) { setSide(currentContent.$element, otherSide(side)); // Remove the content after a timeout instead of listening for // transition event const oldContent = currentContent; setTimeout(() => { oldContent.destroy(); }, 2500); } setSide(newContent.$element, side); // Force reflow, so transition starts now forceReflow(newContent.$element); newContent.$element.classList.remove('left', 'right'); } else { if (currentContent !== null) { currentContent.destroy(); } } } currentContent = newContent; contentChangeEvent.emit({ newContent }); return newContent; } export enum ContentBlockStyle { REGULAR, WARNING, } export class Content { public readonly $element: HTMLDivElement | HTMLElement; // jsx workaround public isDestroyed = false; private readonly blocks: Array<ContentBlock> = []; private scrollTransition: null | MonoDimensionTransitionControl = null; public leavingEvent = new Event(); public scrollEvent = new Event<{ scrollTop: number }>(); private leavingTriggered = false; private $leftSideContainer: null | HTMLDivElement | HTMLElement = null; // jsx workaround private $rightSideContainer: null | HTMLDivElement | HTMLElement = null; // jsx workaround public constructor() { const $content = h('div.content', { tabIndex: -1 }) as HTMLDivElement; $contentContainer.appendChild($content); this.$element = $content; this.$element.addEventListener('wheel', () => { this.interruptScrolling(); }, { passive: true }); this.$element.addEventListener('scroll', () => { this.scrollEvent.emit({ scrollTop: this.$element.scrollTop }); contentScrollEvent.emit({ scrollTop: this.$element.scrollTop }); }, { passive: true }); arrowKeyPressEvent.on(this.onKeyPress); layoutChangeEvent.on(({ newLayout }, listener) => { if (newLayout === Layout.OFF) { this.ensureLeavingTriggered(); layoutChangeEvent.off(listener); } }); } public appendLeftSideContainer() { if (this.$leftSideContainer !== null) { throw new Error('Left side container already exists.'); } this.$leftSideContainer = <div className='left-side-container'/>; this.$element.append(this.$leftSideContainer); } public appendRightSideContainer() { if (this.$rightSideContainer !== null) { throw new Error('Right side container already exists.'); } this.$rightSideContainer = <div className='right-side-container'/>; this.$element.append(this.$rightSideContainer); } public getLeftSideContainer() { if (this.$leftSideContainer === null) { throw new Error('Left side container does not exist.'); } return this.$leftSideContainer; } public getRightSideContainer() { if (this.$rightSideContainer === null) { throw new Error('Right side container does not exist.'); } return this.$rightSideContainer; } public ensureLeavingTriggered() { if (!this.leavingTriggered) { debugLogger.log('Triggering leaving event.'); this.leavingTriggered = true; this.leavingEvent.emit(); } } public addBlock(opts: ContentBlockOpts = {}) { const block = new ContentBlock(this, opts); this.blocks.push(block); return block; } public destroy() { this.isDestroyed = true; this.$element.remove(); window.removeEventListener('wheel', this.interruptScrolling); arrowKeyPressEvent.off(this.onKeyPress); } private onKeyPress = (key: ArrowKey) => { if (key === ArrowKey.UP || key === ArrowKey.DOWN) { this.interruptScrolling(); } } private interruptScrolling = () => { if (this.scrollTransition !== null) { this.scrollTransition = null; debugLogger.log('Transition interrupted.'); } } private scrollAnimation = () => { if (this.scrollTransition === null) { return; } const now = Date.now(); this.$element.scrollTop = this.scrollTransition.getValue(now); if (this.scrollTransition.isFinished(now)) { debugLogger.log('Transition finished.'); this.scrollTransition = null; } else { requestAnimationFrame(this.scrollAnimation); } } public scrollTo(target: number) { if (!animation.getValue() || getCurrentLayout() === Layout.OFF) { debugLogger.log(`Scroll to ${target}, no animation.`); this.$element.scrollTop = target; return; } if (this.scrollTransition === null) { debugLogger.log(`Scrolling to ${target}, new transition stared.`); this.scrollTransition = new MonoDimensionTransitionControl( this.$element.scrollTop, 20_000, ); this.scrollTransition.setTarget(target); requestAnimationFrame(this.scrollAnimation); } else { debugLogger.log(`Scrolling to ${target}, existing transition updated.`); this.scrollTransition.setTarget(target); } } } export enum ContentBlockSide { LEFT, RIGHT, } interface ContentBlockOpts { initElement?: HTMLDivElement | HTMLElement; // jsx workaround style?: ContentBlockStyle; slidable?: boolean; prepend?: boolean; side?: ContentBlockSide; } export class ContentBlock { private slideContainer: HTMLDivElement | null = null; private heightHolder: HTMLDivElement | null = null; private sliding: number = 0; public element: HTMLDivElement; public constructor( content: Content, { initElement = h('div'), style = ContentBlockStyle.REGULAR, slidable = false, prepend = false, side, }: ContentBlockOpts, ) { if (!(initElement instanceof HTMLDivElement)) { throw new Error('Init element must be a div.'); } if (side !== undefined && slidable) { throw new Error('"side" and "slidable" are incompatible.'); } this.element = initElement; initElement.classList.add('content-block'); switch (style) { case ContentBlockStyle.WARNING: initElement.classList.add('warning'); break; } let $parent = content.$element; let $self = initElement; if (slidable) { this.slideContainer = h('.slide-container', $self) as HTMLDivElement; $self = this.slideContainer; } if (side === ContentBlockSide.LEFT) { $parent = content.getLeftSideContainer(); } else if (side === ContentBlockSide.RIGHT) { $parent = content.getRightSideContainer(); } if (prepend) { $parent.prepend($self); } else { $parent.append($self); } } public hide() { this.element.classList.add('display-none'); return this; } public show() { this.element.classList.remove('display-none'); return this; } public onEnteringView(callback: () => void) { const observer = new IntersectionObserver(entries => { const entry = entries[0]; if (entry.isIntersecting) { observer.disconnect(); callback(); } }, { root: $contentContainer, threshold: 0, }); observer.observe(this.element); } public directRemove() { if (this.slideContainer !== null) { this.slideContainer.remove(); } else { this.element.remove(); } } public directReplace($newElement: HTMLDivElement = h('div')) { $newElement.classList.add('content-block'); this.element.parentElement!.replaceChild( $newElement, this.element, ); this.element = $newElement; } public slideReplace($newElement: HTMLDivElement = h('div')) { if (!animation.getValue()) { this.directReplace($newElement); return; } const $container = this.slideContainer; if ($container === null) { throw new Error('Content block is not slidable.'); } this.sliding++; $container.classList.add('in-transition'); $newElement.classList.add('content-block'); const $oldElement = this.element; $newElement.classList.add('right'); // $newElement.style.top = `${$contentContainer.scrollTop - $container.offsetTop + 30}px`; $container.prepend($newElement); const newHeight = $newElement.offsetHeight; // This also forces reflow $newElement.classList.remove('right'); // $newElement.style.top = null; if (this.heightHolder === null) { this.heightHolder = h('.height-holder') as HTMLDivElement; this.heightHolder.style.height = `${$oldElement.offsetHeight}px`; $container.appendChild(this.heightHolder); forceReflow(this.heightHolder); } this.heightHolder.style.height = `${newHeight}px`; $oldElement.classList.add('left'); this.element = $newElement; setTimeout(() => { $oldElement.remove(); this.sliding--; if (this.sliding === 0) { $container.classList.remove('in-transition'); if (this.heightHolder !== null) { this.heightHolder.remove(); this.heightHolder = null; } } }, 2500); } }
kink/kat
src/web/control/contentControl.tsx
TypeScript
unknown
10,947
import { WTCD_ERROR_COMPILE_TITLE, WTCD_ERROR_INTERNAL_DESC, WTCD_ERROR_INTERNAL_STACK_DESC, WTCD_ERROR_INTERNAL_STACK_TITLE, WTCD_ERROR_INTERNAL_TITLE, WTCD_ERROR_MESSAGE, WTCD_ERROR_RUNTIME_DESC, WTCD_ERROR_RUNTIME_TITLE, WTCD_ERROR_WTCD_STACK_DESC, WTCD_ERROR_WTCD_STACK_TITLE, } from '../constant/messages'; import { ErrorType } from './chapterControl'; export function createWTCDErrorMessage({ errorType, message, internalStack, wtcdStack, }: { errorType: ErrorType; message: string; internalStack?: string; wtcdStack?: string; }): HTMLDivElement { const $target = document.createElement('div'); const $title = document.createElement('h1'); const $desc = document.createElement('p'); switch (errorType) { case ErrorType.COMPILE: $title.innerText = WTCD_ERROR_COMPILE_TITLE; $desc.innerText = WTCD_ERROR_COMPILE_TITLE; break; case ErrorType.RUNTIME: $title.innerText = WTCD_ERROR_RUNTIME_TITLE; $desc.innerText = WTCD_ERROR_RUNTIME_DESC; break; case ErrorType.INTERNAL: $title.innerText = WTCD_ERROR_INTERNAL_TITLE; $desc.innerText = WTCD_ERROR_INTERNAL_DESC; break; } $target.appendChild($title); $target.appendChild($desc); const $message = document.createElement('p'); $message.innerText = WTCD_ERROR_MESSAGE + message; $target.appendChild($message); if (wtcdStack !== undefined) { const $stackTitle = document.createElement('h2'); $stackTitle.innerText = WTCD_ERROR_WTCD_STACK_TITLE; $target.appendChild($stackTitle); const $stackDesc = document.createElement('p'); $stackDesc.innerText = WTCD_ERROR_WTCD_STACK_DESC; $target.appendChild($stackDesc); const $pre = document.createElement('pre'); const $code = document.createElement('code'); $code.innerText = wtcdStack; $pre.appendChild($code); $target.appendChild($pre); } if (internalStack !== undefined) { const $stackTitle = document.createElement('h2'); $stackTitle.innerText = WTCD_ERROR_INTERNAL_STACK_TITLE; $target.appendChild($stackTitle); const $stackDesc = document.createElement('p'); $stackDesc.innerText = WTCD_ERROR_INTERNAL_STACK_DESC; $target.appendChild($stackDesc); const $pre = document.createElement('pre'); const $code = document.createElement('code'); $code.innerText = internalStack; $pre.appendChild($code); $target.appendChild($pre); } return $target; }
kink/kat
src/web/control/createWTCDErrorMessage.ts
TypeScript
unknown
2,459
import { WTCDError } from '../../wtcd/WTCDError'; import { ErrorType } from './chapterControl'; import { createWTCDErrorMessage } from './createWTCDErrorMessage'; export function createWTCDErrorMessageFromError(error: Error) { return createWTCDErrorMessage({ errorType: (error instanceof WTCDError) ? ErrorType.RUNTIME : ErrorType.INTERNAL, message: error.message, internalStack: error.stack, wtcdStack: (error instanceof WTCDError) ? error.wtcdStack : undefined, }); }
kink/kat
src/web/control/createWTCDErrorMessageFromError.ts
TypeScript
unknown
514
import { BROKEN_LINK_DESC, BROKEN_LINK_OK, BROKEN_LINK_TITLE } from '../constant/messages'; import { redirects } from '../constant/redirects'; import { DebugLogger } from '../DebugLogger'; import { Event } from '../Event'; import { chapterPathHandler } from './chapterControl'; import { handleMainMenu, menuPathHandler } from './menuControl'; import { mirrorLandingHandler } from './mirrorControl'; import { notify } from './modalControl'; import { pagePathHandler } from './pageControl'; const debugLogger = new DebugLogger('Follow Query'); /** * Example: * If the URL is "https://wt.tepis.me/#/chapter/a/b~selection=1,2,3,4~another=wow" * path will be "a/b" * args will be {selection: "1,2,3,4"} * Returns whether the handling was successful */ export type PathHandler = (path: string, args: Map<string, string>) => boolean; export const onPathHandled = new Event<{ handlerId: string }>(); let pathHandlers: Map<string, PathHandler>; export function initPathHandlers() { pathHandlers = new Map([ ['chapter', chapterPathHandler], ['page', pagePathHandler], ['menu', menuPathHandler], ['mirror-landing', mirrorLandingHandler], ]); } export function followQuery() { if (window.location.hash === '') { document.title = '可穿戴科技'; // No hash, go to main menu. handleMainMenu(); return; } const segments = window.location.hash.split('~').map(decodeURIComponent); // First segment is the page specifier let pageSpecifier = segments[0]; const args = new Map(segments.slice(1).map(arg => { const split = arg.split('='); if (split.length === 2) { return [split[0], split[1]]; } else { return [split[0], '']; } })); // Legacy conversion if (!pageSpecifier.startsWith('#/')) { // URL looks like https://wt.tepis.me/#a/b // This is a legacy URL. Now convert it to the new style. pageSpecifier = `#/chapter/${pageSpecifier.substr('#'.length)}`; if (window.location.search !== '') { // There are query parameters, which were previously used for saving selections const match = /^\?selection=((?:0|[1-9][0-9]*),(?:0|[1-9][0-9]*),(?:0|[1-9][0-9]*),(?:0|[1-9][0-9]*))$/.exec(window.location.search); if (match !== null) { args.set('selection', match[1]); } } } // At this point, page specifier should look like #/chapter/xxxx pageSpecifier = pageSpecifier.substr('#/'.length); // Removes #/ let handlerIdEndIndex = pageSpecifier.indexOf('/'); // Finds the "/" after handlerId if (handlerIdEndIndex === -1) { // If not found, extend to the entire string handlerIdEndIndex = pageSpecifier.length; } const handlerId = pageSpecifier.substr(0, handlerIdEndIndex); // chapter const path = pageSpecifier.substr(handlerIdEndIndex + '/'.length); // xxx const handler = pathHandlers.get(handlerId); let handled = false; if (handler !== undefined) { // Found handler handled = handler(path, args); if (handled) { onPathHandled.emit({ handlerId }); } } if (!handled) { // Try redirects for (const redirect of redirects) { const newPageSpecifier = redirect(pageSpecifier); if (newPageSpecifier !== pageSpecifier) { // Redirect debugLogger.log('Redirect matched: ', redirect, `\nOld page specifier: ${pageSpecifier}\nNew page specifier: ${newPageSpecifier}`); window.location.hash = '#/' + [newPageSpecifier, ...segments.slice(1)].join('~'); return; } } debugLogger.log(`${redirects.length} possible redirects processed. None matched.`); notify(BROKEN_LINK_TITLE, BROKEN_LINK_DESC, BROKEN_LINK_OK); document.title = '可穿戴科技'; window.history.replaceState(null, '可穿戴科技', window.location.pathname); followQuery(); } }
kink/kat
src/web/control/followQuery.ts
TypeScript
unknown
3,805
import { h } from '../hs'; // Promise queue let current: Promise<void> = Promise.resolve(); export function createHint(text: string, timeMs = 2000) { current = current.then(async () => { const $hint = h('.hint', text) as HTMLDivElement; document.body.appendChild($hint); $hint.style.opacity = '0'; // tslint:disable-next-line:no-unused-expression $hint.offsetWidth; $hint.style.removeProperty('opacity'); await new Promise(resolve => setTimeout(resolve, timeMs)); $hint.style.opacity = '0'; await new Promise(resolve => setTimeout(resolve, 500)); $hint.remove(); }); }
kink/kat
src/web/control/hintControl.ts
TypeScript
unknown
615
import { DebugLogger } from '../DebugLogger'; import { Event } from '../Event'; export enum Layout { SIDE, MAIN, OFF, } const $body = document.body; const debugLogger = new DebugLogger('Layout'); export const layoutChangeEvent = new Event<{ previousLayout: Layout, newLayout: Layout, }>(); layoutChangeEvent.on(({ newLayout }) => { $body.classList.remove('layout-side', 'layout-main', 'layout-off'); switch (newLayout) { case Layout.SIDE: $body.classList.add('layout-side'); break; case Layout.MAIN: $body.classList.add('layout-main'); break; case Layout.OFF: $body.classList.add('layout-off'); break; } }); let layout: Layout = Layout.OFF; export function getCurrentLayout() { return layout; } export function setLayout(newLayout: Layout) { if (newLayout !== layout) { debugLogger.log(`${Layout[layout]} -> ${Layout[newLayout]}`); } if (layout === newLayout) { return; } // if (newLayout === Layout.OFF) { // $rect.classList.remove('reading'); // } else { // if (layout === Layout.MAIN) { // $rect.classList.remove('main'); // } else if (layout === Layout.SIDE) { // $rect.classList.remove('side'); // } else { // $rect.classList.remove('main', 'side'); // $rect.classList.add('reading'); // } // if (newLayout === Layout.MAIN) { // $rect.classList.add('main'); // } else { // $rect.classList.add('side'); // } // } layoutChangeEvent.emit({ previousLayout: layout, newLayout, }); layout = newLayout; }
kink/kat
src/web/control/layoutControl.ts
TypeScript
unknown
1,581
import { $e } from '../$e'; import { dbKVGet, dbKVKey, dbKVSet } from '../data/db'; import { DebugLogger } from '../DebugLogger'; import { contactInfoElement } from './contactInfoControl'; import { Modal } from './modalControl'; const debugLogger = new DebugLogger('Lose Contact Prevention'); const hasShownKey = dbKVKey<boolean>('loseContactPreventionHasShown'); export async function initLoseContactPrevention() { try { if (await dbKVGet(hasShownKey) || true) { return; } const modal = new Modal( <div style={{ width: '850px', }}> <h1>防失联信息</h1> <p>本消息只显示一次。</p> <p>可能大家已经知道了,即使我们如此严格地禁止在 QQ 群内讨论色情/政治内容,我们的 QQ ① 群还是被封了,并且没有给出任何封禁的理由。为了防止失联,欢迎通过以下方式加入我们的讨论组/频道。</p> { contactInfoElement() } <p>除此之外,你也可以把本站的地址记下来。不过,我只能尽量确保网站地址不变。</p> <div className='button-container'> <div onclick={ () => modal.close() }>关闭</div> </div> </div> as HTMLDivElement ); modal.setDismissible(); modal.open(); await dbKVSet(hasShownKey, true); } catch (error) { debugLogger.error(error); } }
kink/kat
src/web/control/loseContactPreventionControl.tsx
TypeScript
unknown
1,383
// Provide menu coordination import { DebugLogger } from '../DebugLogger'; import { h } from '../hs'; import { escapeKeyPressEvent } from '../input/keyboard'; import { Menu } from '../Menu'; import { MainMenu } from '../menu/MainMenu'; import { forceReflow, id } from '../util/DOM'; import { onPathHandled, PathHandler } from './followQuery'; export const mainMenu = new MainMenu('#/menu'); mainMenu.show(); const $path = id('menu-control-path'); const $back = id<HTMLAnchorElement>('menu-control-back'); const $control = id('menu-control'); const $titleContainer = id('title-container'); const debugLogger = new DebugLogger('Menu Control'); interface MenuStackItem { menu: Menu; urlSegment: string; pathSpan: HTMLSpanElement; } // Root behaves extremely different from other menus, therefore we will not // include it in the stack. const menuStack: Array<MenuStackItem> = []; function getMenu(index: number) { if (index === -1) { return mainMenu; } else { return menuStack[index].menu; } } function getCurrentMenu() { return getMenu(menuStack.length - 1); } let isMenuMode = true; /** * Used by "enterMenuMode" or regular handling of menu urls. */ function enteredMenuMode() { isMenuMode = true; document.title = '可穿戴科技'; $titleContainer.classList.remove('hidden'); } export function enterMenuMode() { debugLogger.log('Enter menu mode'); if (menuStack.length === 0) { window.location.hash = '#'; } else { window.location.hash = '#/menu/' + menuStack.map(({ urlSegment }) => urlSegment).join('/'); } enteredMenuMode(); } export function exitMenuMode() { isMenuMode = false; debugLogger.log('Exit menu mode'); getCurrentMenu().hide(); $control.classList.add('hidden'); $titleContainer.classList.add('hidden'); } function pop() { const { menu, pathSpan: $pathSpan } = menuStack.pop()!; menu.destroy(); const startX = $pathSpan.offsetLeft; $pathSpan.classList.add('exiting'); if (menuStack.length !== 0) { // Only play the moving animation when it is not the first element $pathSpan.style.left = `${startX}px`; forceReflow($pathSpan); $pathSpan.style.left = `${startX + 10}px`; } else { $pathSpan.classList.add('first'); } setTimeout(() => $pathSpan.remove(), 500); } function popUntil(targetLength: number) { if (menuStack.length > targetLength) { debugLogger.log('Pop until', targetLength); } while (menuStack.length > targetLength) { pop(); } menuStack.length = targetLength; } function updateShowingMenuControl() { $control.classList.toggle('hidden', menuStack.length === 0); } export function handleMainMenu() { debugLogger.log('Handle main menu'); enteredMenuMode(); popUntil(0); mainMenu.show(); updateShowingMenuControl(); } export const menuPathHandler: PathHandler = path => { debugLogger.log(`Handle path=${path}`); enteredMenuMode(); const urlSegments = path.split('/'); // Step 0: Hide current menu getCurrentMenu().hide(); // Step 1: Forward iterate until point of diversion let index = 0; while (index < menuStack.length && index < urlSegments.length && menuStack[index].urlSegment === urlSegments[index]) { index++; } // Step 2: Discard additional menus from menu stack popUntil(index); // Step 3: Add additional menus for (; index < urlSegments.length; index++) { const urlSegment = urlSegments[index]; const parentMenu = getMenu(index - 1); if (!parentMenu.subMenus.has(urlSegment)) { return false; } const { factory, name } = parentMenu.subMenus.get(urlSegment)!; const subMenu = factory(); const $pathSpan = h('span', [ h('span', '>'), h('a.button', { href: subMenu.urlBase, }, name), ]) as HTMLSpanElement; if (index !== 0) { $pathSpan.classList.add('pre-entering'); $path.append($pathSpan); forceReflow($pathSpan); $pathSpan.classList.remove('pre-entering'); } else { $path.append($pathSpan); } menuStack.push({ menu: subMenu, pathSpan: $pathSpan, urlSegment, }); } // Step 4: Show new menu getCurrentMenu().show(); // Step 5: Show/hide menu control updateShowingMenuControl(); // Step 6: Update back URL if (menuStack.length > 1) { // There are something other than main menu $back.href = menuStack[menuStack.length - 2].menu.urlBase; } else { $back.href = '#'; } return true; }; escapeKeyPressEvent.on(() => { if (!isMenuMode) { return; } if (menuStack.length > 1) { window.location.hash = menuStack[menuStack.length - 2].menu.urlBase; } else if (menuStack.length === 1) { window.location.hash = ''; } }); onPathHandled.on(({ handlerId }) => { if (handlerId !== 'menu') { exitMenuMode(); } }); const $logo = id('navbar-logo').cloneNode(true) as SVGElement; $logo.id = 'path-logo'; $path.prepend(h('a', { href: '#', }, $logo));
kink/kat
src/web/control/menuControl.ts
TypeScript
unknown
4,935
import { GENERIC_CLOSE, MIRROR_DESC_0, MIRROR_DESC_0_NO_TOKEN, MIRROR_DESC_1, MIRROR_HINT_0, MIRROR_HINT_1, MIRROR_HINT_CLICK_TO_CHANGE, MIRROR_LANDING_CONFLICT_DESC, MIRROR_LANDING_CONFLICT_KEEP, MIRROR_LANDING_CONFLICT_OVERWRITE, MIRROR_LANDING_CONFLICT_TITLE, MIRROR_LANDING_INVALID_REFERRAL, MIRROR_LANDING_SUCCESS_HINT, MIRROR_PROVIDED_BY, MIRROR_TECHNOLOGY, MIRROR_TITLE, MIRROR_URL, } from '../constant/messages'; import { mirrorSites, mirrorSitesPlusMainSite } from '../constant/mirrorSites'; import { chapterHref, mirrorLandingHref } from '../data/hrefs'; import { h } from '../hs'; import { padName } from '../util/padName'; import { PathHandler } from './followQuery'; import { createHint } from './hintControl'; import { confirm, Modal, showGenericError } from './modalControl'; import { tokenItem } from './userControl'; export function showMirrorSitesModal(scroll?: number) { const modal = new Modal(h('.mirror-site-modal', [ h('h1', MIRROR_TITLE), h('p', tokenItem.exists() ? MIRROR_DESC_0 : MIRROR_DESC_0_NO_TOKEN), h('p', MIRROR_DESC_1), h('p', { style: { 'font-weight': 'bold' }, }, [ '主站暂时无法工作。其原因参阅', h('a.regular', { href: chapterHref('META/公告/关于被-GitLab.com-封禁的公告.html'), onclick: () => { modal.close(); }, }, '这条公告'), '。', ]), h('.button-container', [ ...mirrorSitesPlusMainSite.map(({ name, origin, provider, technology }) => { const $button = h('a.rich', { href: (origin === window.location.origin) ? '#' : mirrorLandingHref(origin, tokenItem.getValue()), onclick: (event: MouseEvent) => { event.preventDefault(); if (origin === window.location.origin) { return; } window.location.replace(mirrorLandingHref(origin, tokenItem.getValue(), modal.modal.scrollTop)); }, }, [ h('h2', name), h('p', [ MIRROR_URL + origin, h('br'), MIRROR_PROVIDED_BY + provider, h('br'), MIRROR_TECHNOLOGY + technology, ]), ]); if (origin === window.location.origin) { $button.classList.add('selected'); } return $button; }), h('div', { onclick: () => modal.close(), }, GENERIC_CLOSE), ]), ]) as HTMLDivElement); modal.setDismissible(); modal.open(); if (scroll !== undefined) { modal.modal.scrollTop = scroll; } } export const mirrorLandingHandler: PathHandler = (_, args) => { // Prevent leaving the token in browser history window.history.replaceState(null, document.title, '#/mirror-landing'); window.location.hash = '#'; showMirrorSitesModal(args.has('scroll') ? +args.get('scroll')! : undefined); const newToken = args.get('token'); if (newToken === undefined) { return true; } if (!mirrorSitesPlusMainSite.some( mirror => document.referrer === mirror.origin || document.referrer.startsWith(mirror.origin + '/')) ) { showGenericError(MIRROR_LANDING_INVALID_REFERRAL); return true; } const oldToken = tokenItem.getValue(); if (oldToken !== null) { if (oldToken !== newToken) { confirm( MIRROR_LANDING_CONFLICT_TITLE, MIRROR_LANDING_CONFLICT_DESC, MIRROR_LANDING_CONFLICT_OVERWRITE, MIRROR_LANDING_CONFLICT_KEEP, ).then(result => { if (result) { // Overwrite tokenItem.setValue(newToken); createHint(MIRROR_LANDING_SUCCESS_HINT); } }); } } else { // No conflict tokenItem.setValue(newToken); createHint(MIRROR_LANDING_SUCCESS_HINT); } return true; }; const currentMirrorSite = mirrorSites.find(({ origin }) => origin === window.location.origin); if (currentMirrorSite !== undefined) { const $mirrorHint = h('.mirror-hint', [ MIRROR_HINT_0.replace('$', padName(currentMirrorSite.provider)), h('span', { onclick: () => showMirrorSitesModal(), }, MIRROR_HINT_CLICK_TO_CHANGE), MIRROR_HINT_1, ]); document.body.append($mirrorHint); }
kink/kat
src/web/control/mirrorControl.ts
TypeScript
unknown
4,211
import { GENERIC_CONFIRM, GENERIC_ERROR_DESC, GENERIC_ERROR_TITLE, GENERIC_HINT_TITLE, GENERIC_LOADING_DESC, GENERIC_LOADING_TITLE, GENERIC_SUCCESS_DESC, GENERIC_SUCCESS_TITLE } from '../constant/messages'; import { animation } from '../data/settings'; import { h } from '../hs'; import { escapeKeyPressEvent } from '../input/keyboard'; import { forceReflow, id } from '../util/DOM'; const $modalHolder = id('modal-holder'); export class Modal { public readonly modal: HTMLDivElement; public readonly modalContainer: HTMLDivElement; public constructor( $initElement: HTMLDivElement = h('div'), ) { $initElement.classList.add('modal'); this.modal = $initElement; this.modalContainer = h( '.modal-container.closed', $initElement, ) as HTMLDivElement; $modalHolder.appendChild(this.modalContainer); } public open() { forceReflow(this.modalContainer); this.modalContainer.classList.remove('closed'); } public close() { if (animation.getValue()) { this.modalContainer.classList.add('closed'); setTimeout(() => { this.modalContainer.remove(); }, 400); } else { this.modalContainer.remove(); } if (this.escKeyListener !== null) { escapeKeyPressEvent.off(this.escKeyListener); } } private dismissSet = false; private escKeyListener: (() => void) | null = null; public setDismissible(onDismiss: () => void = () => { this.close(); }) { if (this.dismissSet) { throw new Error('Dismissible already set.'); } this.dismissSet = true; escapeKeyPressEvent.on(onDismiss); this.modalContainer.addEventListener('click', event => { if (event.target === this.modalContainer) { onDismiss(); } }); } } export function confirm(title: string, desc: string, yes: string, no: string) { let resolved = false; return new Promise<boolean>(resolve => { const modal = new Modal(h('div', [ h('h1', title), desc === '' ? null : h('p', desc), h('.button-container', [ h('div', { onclick: () => { if (resolved) { return; } resolved = true; modal.close(); resolve(true); }, }, yes), h('div', { onclick: () => { if (resolved) { return; } resolved = true; modal.close(); resolve(false); }, }, no), ]), ])); modal.open(); }); } export function notify(title: string, desc: string, yes: string) { let resolved = false; return new Promise<void>(resolve => { const modal = new Modal(h('div', [ h('h1', title), desc === '' ? null : h('p', desc), h('.button-container', [ h('div', { onclick: () => { if (resolved) { return; } resolved = true; modal.close(); resolve(); }, }, yes), ]), ])); modal.open(); }); } export function showGenericSuccess(desc?: string) { return notify(GENERIC_SUCCESS_TITLE, desc ?? GENERIC_SUCCESS_DESC, GENERIC_CONFIRM); } export function showGenericError(desc?: string) { return notify(GENERIC_ERROR_TITLE, desc ?? GENERIC_ERROR_DESC, GENERIC_CONFIRM); } export function showGenericHint(desc: string) { return notify(GENERIC_HINT_TITLE, desc, GENERIC_CONFIRM); } export function showGenericLoading(desc?: string) { const modal = new Modal(h('div', [ h('h1', GENERIC_LOADING_TITLE), h('p', desc ?? GENERIC_LOADING_DESC), ])); modal.open(); return modal; } export function isAnyModalOpened() { return $modalHolder.childElementCount > 0; }
kink/kat
src/web/control/modalControl.ts
TypeScript
unknown
3,749
import { animation } from '../data/settings'; import { h } from '../hs'; import { forceReflow, id } from '../util/DOM'; import { contentChangeEvent, contentScrollEvent } from './contentControl'; import { Layout, layoutChangeEvent } from './layoutControl'; import { enterMenuMode } from './menuControl'; const $navbar = id('navbar'); const $navbarPathContainer = id('navbar-path-container'); const $progressIndicator = id('navbar-progress-indicator'); const $logo = id('navbar-logo'); const $title = id('navbar-title'); /** * Used for skipping the animation when transitioning from main layout. */ let delayedLayout: Layout; export function setProgressIndicator(progress: number) { $progressIndicator.style.transform = `scaleX(${progress})`; $progressIndicator.classList.toggle('hidden', progress === 1 || progress === 0); } export function resetProgressIndicator() { setProgressIndicator(0); } layoutChangeEvent.on(({ newLayout }) => { resetProgressIndicator(); setTimeout(() => delayedLayout = newLayout, 100); }); $logo.addEventListener('click', () => { enterMenuMode(); }); $title.addEventListener('click', event => { event.preventDefault(); enterMenuMode(); }); contentScrollEvent.on(({ scrollTop }) => $navbar.classList.toggle('flat', scrollTop < 50)); contentChangeEvent.on(() => $navbar.classList.add('flat')); export interface NavbarPathSegmentSpecifier { display: string; hash: string | null; } export interface NavbarPathSegment extends NavbarPathSegmentSpecifier { $anchor: HTMLElement; $arrow: HTMLDivElement; } const currentNavbarPath: Array<NavbarPathSegment> = []; function compareNavbarPathSegment( a: NavbarPathSegmentSpecifier, b: NavbarPathSegmentSpecifier, ) { return a.display === b.display && a.hash === b.hash; } function removeElement($element: HTMLElement) { if (animation.getValue() && delayedLayout === Layout.MAIN) { $element.style.left = `${$element.offsetLeft}px`; $element.classList.add('exiting'); setTimeout(() => { $element.remove(); }, 500); } else { $element.remove(); } } function removeNavbarPathSegment(segment: NavbarPathSegment) { removeElement(segment.$anchor); removeElement(segment.$arrow); } function createNavbarPathSegment(segmentSpecifier: NavbarPathSegmentSpecifier): NavbarPathSegment { const $arrow = h('.arrow', '>') as HTMLDivElement; const $anchor = segmentSpecifier.hash === null ? h('.anchor', segmentSpecifier.display) as HTMLElement : h('a.button.anchor', { href: segmentSpecifier.hash, }, segmentSpecifier.display) as HTMLElement; $navbarPathContainer.appendChild($arrow); $navbarPathContainer.appendChild($anchor); if (animation.getValue() && delayedLayout === Layout.MAIN) { $arrow.classList.add('entering'); $anchor.classList.add('entering'); forceReflow($anchor); $arrow.classList.remove('entering'); $anchor.classList.remove('entering'); } return { $arrow, $anchor, ...segmentSpecifier, }; } export function setNavbarPath(newNavbarPath: Array<NavbarPathSegmentSpecifier>) { let firstDifferentIndex = 0; while ( currentNavbarPath.length > firstDifferentIndex && newNavbarPath.length > firstDifferentIndex && compareNavbarPathSegment( currentNavbarPath[firstDifferentIndex], newNavbarPath[firstDifferentIndex] ) ) { firstDifferentIndex++; } // Remove extras from current navbar path for (let i = currentNavbarPath.length - 1; i >= firstDifferentIndex; i--) { removeNavbarPathSegment(currentNavbarPath[i]); } currentNavbarPath.length = firstDifferentIndex; // Shorten the array // Add new segments for (let i = firstDifferentIndex; i < newNavbarPath.length; i++) { currentNavbarPath.push(createNavbarPathSegment(newNavbarPath[i])); } }
kink/kat
src/web/control/navbarControl.ts
TypeScript
unknown
3,811
import { escapeKeyPressEvent } from '../input/keyboard'; import { author } from '../pages/author'; import { recentComments } from '../pages/recentComments'; import { recentMentions } from '../pages/recentMentions'; import { taggingTool } from '../pages/taggingTool'; import { tagSearch } from '../pages/tagSearch'; import { visitCount } from '../pages/visitCount'; import { wtcupVote } from '../pages/wtcupVote'; import { Content, newContent, Side } from './contentControl'; import { PathHandler } from './followQuery'; import { Layout, setLayout } from './layoutControl'; import { enterMenuMode } from './menuControl'; export interface Page { name: string; handler: (content: Content, pagePath: PagePath) => boolean; } const pages: Array<Page> = [ recentComments, visitCount, recentMentions, author, wtcupVote, taggingTool, tagSearch, ]; class PagePath { public constructor( private current: string, private prefix: string, ) {} public get() { return this.current; } public set(newPath: string) { this.current = newPath; window.history.replaceState(null, document.title, this.prefix + newPath); } } export const pagePathHandler: PathHandler = path => { for (const page of pages) { if (path === page.name || path.startsWith(page.name + '/')) { const content = newContent(Side.RIGHT); escapeKeyPressEvent.onceUntil(enterMenuMode, content.leavingEvent); setLayout(Layout.MAIN); const handleResult = page.handler(content, new PagePath(path.substr(page.name.length + 1), `#/page/${page.name}/`)); return handleResult; } } return false; };
kink/kat
src/web/control/pageControl.ts
TypeScript
unknown
1,633
export class PersistentItem<T> { public constructor( private key: string, private serializer: (value: T) => string, private deserializer: (str: string) => T | null, ) {} public getValue(): T | null { const str = window.localStorage.getItem(this.key); if (str === null) { return null; } return this.deserializer(str); } public setValue(value: T) { window.localStorage.setItem(this.key, this.serializer(value)); } public remove() { window.localStorage.removeItem(this.key); } public setValueNullable(value: T | null) { if (value === null) { this.remove(); } else { this.setValue(value); } } public exists(): boolean { return this.getValue() !== null; } } const identity = <T>(input: T) => input; export class StringPersistentItem extends PersistentItem<string> { public constructor(key: string) { super(key, identity, identity); } } const numberToString = (input: number) => String(input); const stringToNumber = (input: string) => { const num = +input; if (Number.isNaN(num)) { return null; } return num; }; export class NumberPersistentItem extends PersistentItem<number> { public constructor(key: string) { super(key, numberToString, stringToNumber); } }
kink/kat
src/web/control/persistentItem.ts
TypeScript
unknown
1,282
import { $e } from '../$e'; import { produce } from '../util/array'; import { randomInt } from '../util/math'; import { Content } from './contentControl'; function getLine(percentage: number) { const style = (percentage === 100) ? {} : { clipPath: `inset(0 ${100 - percentage}% 0 0)` }; return ( <div className='flash-container' style={style}> <div className='flash'/> </div> ); } function getFullLine() { return getLine(100); } function getPartialLine() { return getLine(Math.random() * 60 + 20); } export function addPreloaderBlock(content: Content) { return content.addBlock({ initElement: ( <div className='preloader'> <div className='preloader-title'> {getPartialLine()} </div> {produce(12, () => ( <div className='preloader-paragraph'> {produce(randomInt(1, 5), getFullLine)} {getPartialLine()} </div> ))} </div> ), }); }
kink/kat
src/web/control/preloaderBlock.tsx
TypeScript
unknown
966
import { selectNode } from '../util/DOM'; export function processElements($parent: HTMLElement) { Array.from($parent.getElementsByTagName('a')).forEach(($anchor: HTMLAnchorElement) => { const hrefAttribute = $anchor.attributes.getNamedItem('href'); if (hrefAttribute !== null && !hrefAttribute.value.startsWith('#')) { $anchor.target = '_blank'; } $anchor.rel = 'noopener noreferrer'; $anchor.className = 'regular'; }); Array.from($parent.getElementsByTagName('code')).forEach($code => $code.addEventListener('dblclick', () => { if (!($code.parentNode instanceof HTMLPreElement)) { selectNode($code); } })); Array.from($parent.getElementsByTagName('img')).forEach($image => { const src = $image.src; const fullResolutionPath = src.replace(/\.([^.]+)$/, '.full.$1'); $image.style.cursor = 'zoom-in'; $image.addEventListener('click', () => window.open(fullResolutionPath)); }); }
kink/kat
src/web/control/processElements.ts
TypeScript
unknown
947
import { $e } from '../$e'; import { Chapter } from '../../Data'; import { enablePushHelper } from '../data/settings'; import { Content, ContentBlockSide } from './contentControl'; import { Modal } from './modalControl'; export function addPushHelperBlock(content: Content, chapter: Chapter) { if (!enablePushHelper.getValue()) { return; } content.addBlock({ initElement: ( <div> <h3>推送助手</h3> <div className='button-container'> <div onclick={() => { openPushHelper(chapter); }}>打开推送助手</div> </div> <p>推送助手是给《可穿戴科技》的编辑们使用的工具。如果你不是《可穿戴科技》的编辑,你可以前往设置并禁用推送助手。</p> </div> ), side: ContentBlockSide.LEFT, }); } function openPushHelper(chapter: Chapter) { const tags = [...new Set(chapter.tags?.map(tagVariant => `#${tagVariant.split('(')[0]}`) ?? [])]; const modal = new Modal( <div> <h1>推送助手</h1> <p>字数:{chapter.charsCount}</p> <p>标签:</p> <pre className='wrapping'> <code>{tags.join(' ')}</code> </pre> <div className='button-container'> <div onclick={() => modal.close()}>关闭</div> </div> </div> as HTMLDivElement ); modal.setDismissible(); modal.open(); }
kink/kat
src/web/control/pushHelper.tsx
TypeScript
unknown
1,385
import { Chapter } from '../../Data'; import { relativePathLookUpMap } from '../data/data'; import { canChapterShown } from './chapterControl'; function nextTick() { return new Promise(resolve => setTimeout(resolve, 1)); } export async function recommend(sourceChapter: Chapter) { if (sourceChapter.tags === undefined) { return null; } const recommendations: Array<{ score: number, chapter: Chapter, }> = []; let sliceStartTime = Date.now(); const originalSet = new Set(sourceChapter.tags); for (const { chapter } of relativePathLookUpMap.values()) { if (Date.now() - sliceStartTime > 10) { await nextTick(); sliceStartTime = Date.now(); } if (!canChapterShown(chapter)) { continue; } if (chapter.tags === undefined) { continue; } const union = new Set(originalSet); let intersectionSize = 0; for (const tag of chapter.tags) { if (originalSet.has(tag)) { intersectionSize++; } union.add(tag); } const jaccardIndex = intersectionSize / union.size; if (jaccardIndex !== 0) { recommendations.push({ score: jaccardIndex, chapter, }); } } return recommendations.sort((a, b) => b.score - a.score); }
kink/kat
src/web/control/recommendControl.ts
TypeScript
unknown
1,247
import { Chapter } from '../../Data'; import { relativePathLookUpMap } from '../data/data'; import { canChapterShown } from './chapterControl'; function nextTick() { return new Promise(resolve => setTimeout(resolve, 1)); } export type SearchInput = Array<{ searchTag: string, type: 'required' | 'excluded' | 'favored' }>; function matchTag(tagList: Array<string>, searchTag: string) { if (tagList.includes(searchTag)) { return searchTag; } if (searchTag.includes('(')) { // Search tag has specified tag variant return null; } // tagList may contain tag variant of search tag for (const tag of tagList) { if (tag.startsWith(searchTag + '(')) { return tag; } } return null; } export async function search(searchInput: SearchInput) { let sliceStartTime = Date.now(); const candidates: Array<{ chapter: Chapter, score: number, matchedTags: Array<string>, }> = []; eachChapter: for (const { chapter } of relativePathLookUpMap.values()) { if (Date.now() - sliceStartTime > 10) { await nextTick(); sliceStartTime = Date.now(); } if (!canChapterShown(chapter)) { continue; } if (chapter.tags === undefined) { continue; } let score = 0; const matchedTags: Array<string> = []; for (const { searchTag, type } of searchInput) { const matchedTag = matchTag(chapter.tags, searchTag); if (type === 'excluded') { if (matchedTag !== null) { continue eachChapter; } score++; } else if (type === 'required') { if (matchedTag === null) { continue eachChapter; } score++; matchedTags.push(matchedTag); } else if (type === 'favored' && matchedTag !== null) { score++; matchedTags.push(matchedTag); } } if (score > 0) { candidates.push({ score, chapter, matchedTags, }); } } candidates.sort((a, b) => (a.score !== b.score) ? (b.score - a.score) : (b.chapter.creationTime - a.chapter.creationTime)); return candidates; }
kink/kat
src/web/control/searchControl.ts
TypeScript
unknown
2,116
import { GENERIC_CANCEL, GENERIC_CLOSE, GENERIC_CONFIRM, GENERIC_INTERNET_ERROR, USER_TOKEN_CHANGE_CHECKING, USER_TOKEN_CHANGE_DESC, USER_TOKEN_CHANGE_EMPTY, USER_TOKEN_CHANGE_INPUT_LABEL, USER_TOKEN_CHANGE_INVALID, USER_TOKEN_CHANGE_SUCCESS, USER_TOKEN_CHANGE_TITLE, USER_TOKEN_DOES_NOT_EXIST, USER_UPDATE_PROFILE_DESC, USER_UPDATE_PROFILE_DISPLAY_NAME_EMPTY, USER_UPDATE_PROFILE_DISPLAY_NAME_INPUT_LABEL, USER_UPDATE_PROFILE_EMAIL_INPUT_LABEL, USER_UPDATE_PROFILE_ERROR_NOT_INITIALIZED, USER_UPDATE_PROFILE_HINT_DISPLAY_NAME, USER_UPDATE_PROFILE_HINT_EMAIL_0, USER_UPDATE_PROFILE_HINT_EMAIL_1, USER_UPDATE_PROFILE_HINT_EMAIL_GRAVATAR_LINK, USER_UPDATE_PROFILE_HINT_USER_NAME, USER_UPDATE_PROFILE_LOADING, USER_UPDATE_PROFILE_SUCCESS, USER_UPDATE_PROFILE_TITLE, USER_UPDATE_PROFILE_USER_NAME_INPUT_LABEL } from '../constant/messages'; import { pageHref } from '../data/hrefs'; import { DebugLogger } from '../DebugLogger'; import { h } from '../hs'; import { ItemDecoration, ItemHandle, ItemLocation } from '../Menu'; import { externalLink } from '../util/DOM'; import { fetchInit, fetchRegister, fetchUpdateProfile, getErrorMessage, ResultOf } from './backendControl'; import { mainMenu } from './menuControl'; import { Modal, showGenericError, showGenericHint, showGenericLoading, showGenericSuccess } from './modalControl'; import { StringPersistentItem } from './persistentItem'; const debugLogger = new DebugLogger('User Control'); export const tokenItem = new StringPersistentItem('token'); let initializedData: { userName: string, displayName: string, email: string | null, } | null = null; export async function registerWithResultPopup(displayName: string, email: string | null): Promise<boolean> { let result: ResultOf<typeof fetchRegister>; try { result = await fetchRegister(displayName, email ?? undefined); } catch (error) { showGenericError(GENERIC_INTERNET_ERROR); debugLogger.error(error); return false; } if (!result.success) { showGenericError(getErrorMessage(result.code)); return false; } else { tokenItem.setValue(result.token); initializedData = { displayName, userName: result.user_name, email, }; return true; } } export function getCurrentUser() { return initializedData; } let newMentionLink: null | ItemHandle = null; export function removeNewMentionLink() { if (newMentionLink === null) { return; } newMentionLink.remove(); newMentionLink = null; } enum InitResult { SUCCESS, ERROR_NETWORK, ERROR_TOKEN, } export async function init(token: string) { // 以下代码用于从后端拉取是否有新回复 // 这一步不会记录任何个人数据 debugLogger.log('Initializing.'); removeNewMentionLink(); let data: ResultOf<typeof fetchInit>; try { data = await fetchInit(token); } catch (error) { debugLogger.warn('Initialization failed: ', error); return InitResult.ERROR_NETWORK; } if (data.success) { tokenItem.setValue(token); initializedData = { displayName: data.display_name, email: data.email ?? null, userName: data.user_name, }; debugLogger.log(`Initialization result: ${data.mentions} new mentions.`); if (data.mentions !== 0) { newMentionLink = mainMenu.addItem(`您有 ${data.mentions} 条新回复`, { button: true, link: pageHref('recent-mentions'), decoration: ItemDecoration.ICON_NOTIFICATION, location: ItemLocation.BEFORE, }); newMentionLink.addClass('force-small'); } return InitResult.SUCCESS; } else { debugLogger.warn('Initialization failed: Invalid token.'); return InitResult.ERROR_TOKEN; } } export function showLoginModal() { const initialTokenValue = tokenItem.getValue() ?? ''; const $tokenInput: HTMLInputElement = h('input', { value: initialTokenValue, }) as HTMLInputElement; const $confirmButton = h('div.display-none', { onclick: () => { if ($tokenInput.value === '') { showGenericError(USER_TOKEN_CHANGE_EMPTY); return; } const loadingModal = showGenericLoading(USER_TOKEN_CHANGE_CHECKING); debugLogger.log('Changing token...'); init($tokenInput.value).then(initResult => { if (initResult === InitResult.SUCCESS) { debugLogger.log('Change token successful.'); showGenericSuccess(USER_TOKEN_CHANGE_SUCCESS).then(() => { loginModal.close(); }); } else { if (initResult === InitResult.ERROR_NETWORK) { showGenericError(GENERIC_INTERNET_ERROR); } else { showGenericError(USER_TOKEN_CHANGE_INVALID); } } }).finally(() => { loadingModal.close(); }); }, }, GENERIC_CONFIRM); const $closeButton = h('div', { onclick: () => { loginModal.close(); } }, GENERIC_CLOSE); $tokenInput.addEventListener('input', () => { if ($tokenInput.value === initialTokenValue) { $confirmButton.classList.add('display-none'); $closeButton.innerText = GENERIC_CLOSE; } else { $confirmButton.classList.remove('display-none'); $closeButton.innerText = GENERIC_CANCEL; } }); const loginModal = new Modal(h('div', [ h('h1', USER_TOKEN_CHANGE_TITLE), ...USER_TOKEN_CHANGE_DESC.split('\n').map(p => h('p', p)), h('.input-group', [ h('span', USER_TOKEN_CHANGE_INPUT_LABEL), $tokenInput, ]), h('.button-container', [ $confirmButton, $closeButton, ]), ])); loginModal.open(); } export function showUpdateProfileModal() { return new Promise<void>(resolve => { if (!tokenItem.exists()) { showGenericHint(USER_TOKEN_DOES_NOT_EXIST); return; } const userData = initializedData; if (userData === null) { showGenericError(USER_UPDATE_PROFILE_ERROR_NOT_INITIALIZED); console.error(1); return; } const $nameInput: HTMLInputElement = h('input', { value: userData.displayName, }) as HTMLInputElement; const $emailInput: HTMLInputElement = h('input', { value: userData.email ?? '', }) as HTMLInputElement; const updateProfileModal = new Modal(h('div', [ h('h1', USER_UPDATE_PROFILE_TITLE), ...USER_UPDATE_PROFILE_DESC.split('\n').map(p => h('p', p)), h('ul', [ h('li', USER_UPDATE_PROFILE_HINT_USER_NAME), h('li', USER_UPDATE_PROFILE_HINT_DISPLAY_NAME), h('li', [ USER_UPDATE_PROFILE_HINT_EMAIL_0, externalLink(USER_UPDATE_PROFILE_HINT_EMAIL_GRAVATAR_LINK, 'https://cn.gravatar.com/'), USER_UPDATE_PROFILE_HINT_EMAIL_1, ]), ]), h('.input-group', [ h('span', USER_UPDATE_PROFILE_USER_NAME_INPUT_LABEL + '@' + userData.userName), ]), h('.input-group', [ h('span', USER_UPDATE_PROFILE_DISPLAY_NAME_INPUT_LABEL), $nameInput, ]), h('.input-group', [ h('span', USER_UPDATE_PROFILE_EMAIL_INPUT_LABEL), $emailInput, ]), h('.button-container', [ h('div', { onclick: () => { if ($nameInput.value === '') { showGenericError(USER_UPDATE_PROFILE_DISPLAY_NAME_EMPTY); return; } const loadingModal = showGenericLoading(USER_UPDATE_PROFILE_LOADING); debugLogger.log('Updating profile...'); const newDisplayName = $nameInput.value; const newEmail = ($emailInput.value === '') ? undefined : $emailInput.value; fetchUpdateProfile(tokenItem.getValue()!, newDisplayName, newEmail) .then(result => { if (result.success) { showGenericSuccess(USER_UPDATE_PROFILE_SUCCESS).then(() => { updateProfileModal.close(); resolve(); }); userData.displayName = newDisplayName; userData.email = newEmail ?? null; debugLogger.log('Update profile success'); } else { debugLogger.warn('Update profile failed, error code:', result.code, ', translated:', getErrorMessage(result.code)); showGenericError(getErrorMessage(result.code)); } }, error => { showGenericError(GENERIC_INTERNET_ERROR); debugLogger.error('Update profile failed:', error); }) .finally(() => { loadingModal.close(); }); } }, GENERIC_CONFIRM), h('div', { onclick: () => { updateProfileModal.close(); resolve(); } }, GENERIC_CANCEL), ]), ])); updateProfileModal.open(); }); }
kink/kat
src/web/control/userControl.ts
TypeScript
unknown
8,844