mirror of
https://github.com/PaiGramTeam/luoxu-api-pub.git
synced 2024-11-21 22:58:21 +00:00
add typescript && editorconfig.
This commit is contained in:
parent
d09faea0b4
commit
ea4a3d4d19
12
.editorconfig
Normal file
12
.editorconfig
Normal file
@ -0,0 +1,12 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[{package.json,.travis.yml,.eslintrc.json}]
|
||||
indent_style = space
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -2,3 +2,4 @@
|
||||
/public/build/
|
||||
|
||||
.DS_Store
|
||||
.vscode
|
||||
|
795
package-lock.json
generated
795
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
13
package.json
13
package.json
@ -5,7 +5,8 @@
|
||||
"scripts": {
|
||||
"build": "rollup -c",
|
||||
"dev": "rollup -c -w",
|
||||
"start": "sirv public --no-clear"
|
||||
"start": "sirv public --no-clear",
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^17.0.0",
|
||||
@ -15,9 +16,15 @@
|
||||
"rollup-plugin-livereload": "^2.0.0",
|
||||
"rollup-plugin-svelte": "^7.0.0",
|
||||
"rollup-plugin-terser": "^7.0.0",
|
||||
"svelte": "^3.0.0"
|
||||
"svelte": "^3.0.0",
|
||||
"svelte-check": "^2.0.0",
|
||||
"svelte-preprocess": "^4.0.0",
|
||||
"@rollup/plugin-typescript": "^8.0.0",
|
||||
"typescript": "^4.0.0",
|
||||
"tslib": "^2.0.0",
|
||||
"@tsconfig/svelte": "^2.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"sirv-cli": "^1.0.0"
|
||||
}
|
||||
}
|
||||
}
|
@ -3,6 +3,8 @@ import commonjs from '@rollup/plugin-commonjs';
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import livereload from 'rollup-plugin-livereload';
|
||||
import { terser } from 'rollup-plugin-terser';
|
||||
import sveltePreprocess from 'svelte-preprocess';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import css from 'rollup-plugin-css-only';
|
||||
|
||||
const production = !process.env.ROLLUP_WATCH;
|
||||
@ -29,7 +31,7 @@ function serve() {
|
||||
}
|
||||
|
||||
export default {
|
||||
input: 'src/main.js',
|
||||
input: 'src/main.ts',
|
||||
output: {
|
||||
sourcemap: true,
|
||||
format: 'iife',
|
||||
@ -38,6 +40,7 @@ export default {
|
||||
},
|
||||
plugins: [
|
||||
svelte({
|
||||
preprocess: sveltePreprocess({ sourceMap: !production }),
|
||||
compilerOptions: {
|
||||
// enable run-time checks when not in production
|
||||
dev: !production
|
||||
@ -57,6 +60,10 @@ export default {
|
||||
dedupe: ['svelte']
|
||||
}),
|
||||
commonjs(),
|
||||
typescript({
|
||||
sourceMap: !production,
|
||||
inlineSources: !production
|
||||
}),
|
||||
|
||||
// In dev mode, call `npm run start` once
|
||||
// the bundle has been generated
|
@ -1,121 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/** This script modifies the project to support TS code in .svelte files like:
|
||||
|
||||
<script lang="ts">
|
||||
export let name: string;
|
||||
</script>
|
||||
|
||||
As well as validating the code for CI.
|
||||
*/
|
||||
|
||||
/** To work on this script:
|
||||
rm -rf test-template template && git clone sveltejs/template test-template && node scripts/setupTypeScript.js test-template
|
||||
*/
|
||||
|
||||
const fs = require("fs")
|
||||
const path = require("path")
|
||||
const { argv } = require("process")
|
||||
|
||||
const projectRoot = argv[2] || path.join(__dirname, "..")
|
||||
|
||||
// Add deps to pkg.json
|
||||
const packageJSON = JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8"))
|
||||
packageJSON.devDependencies = Object.assign(packageJSON.devDependencies, {
|
||||
"svelte-check": "^2.0.0",
|
||||
"svelte-preprocess": "^4.0.0",
|
||||
"@rollup/plugin-typescript": "^8.0.0",
|
||||
"typescript": "^4.0.0",
|
||||
"tslib": "^2.0.0",
|
||||
"@tsconfig/svelte": "^2.0.0"
|
||||
})
|
||||
|
||||
// Add script for checking
|
||||
packageJSON.scripts = Object.assign(packageJSON.scripts, {
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json"
|
||||
})
|
||||
|
||||
// Write the package JSON
|
||||
fs.writeFileSync(path.join(projectRoot, "package.json"), JSON.stringify(packageJSON, null, " "))
|
||||
|
||||
// mv src/main.js to main.ts - note, we need to edit rollup.config.js for this too
|
||||
const beforeMainJSPath = path.join(projectRoot, "src", "main.js")
|
||||
const afterMainTSPath = path.join(projectRoot, "src", "main.ts")
|
||||
fs.renameSync(beforeMainJSPath, afterMainTSPath)
|
||||
|
||||
// Switch the app.svelte file to use TS
|
||||
const appSveltePath = path.join(projectRoot, "src", "App.svelte")
|
||||
let appFile = fs.readFileSync(appSveltePath, "utf8")
|
||||
appFile = appFile.replace("<script>", '<script lang="ts">')
|
||||
appFile = appFile.replace("export let name;", 'export let name: string;')
|
||||
fs.writeFileSync(appSveltePath, appFile)
|
||||
|
||||
// Edit rollup config
|
||||
const rollupConfigPath = path.join(projectRoot, "rollup.config.js")
|
||||
let rollupConfig = fs.readFileSync(rollupConfigPath, "utf8")
|
||||
|
||||
// Edit imports
|
||||
rollupConfig = rollupConfig.replace(`'rollup-plugin-terser';`, `'rollup-plugin-terser';
|
||||
import sveltePreprocess from 'svelte-preprocess';
|
||||
import typescript from '@rollup/plugin-typescript';`)
|
||||
|
||||
// Replace name of entry point
|
||||
rollupConfig = rollupConfig.replace(`'src/main.js'`, `'src/main.ts'`)
|
||||
|
||||
// Add preprocessor
|
||||
rollupConfig = rollupConfig.replace(
|
||||
'compilerOptions:',
|
||||
'preprocess: sveltePreprocess({ sourceMap: !production }),\n\t\t\tcompilerOptions:'
|
||||
);
|
||||
|
||||
// Add TypeScript
|
||||
rollupConfig = rollupConfig.replace(
|
||||
'commonjs(),',
|
||||
'commonjs(),\n\t\ttypescript({\n\t\t\tsourceMap: !production,\n\t\t\tinlineSources: !production\n\t\t}),'
|
||||
);
|
||||
fs.writeFileSync(rollupConfigPath, rollupConfig)
|
||||
|
||||
// Add TSConfig
|
||||
const tsconfig = `{
|
||||
"extends": "@tsconfig/svelte/tsconfig.json",
|
||||
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
|
||||
}`
|
||||
const tsconfigPath = path.join(projectRoot, "tsconfig.json")
|
||||
fs.writeFileSync(tsconfigPath, tsconfig)
|
||||
|
||||
// Add global.d.ts
|
||||
const dtsPath = path.join(projectRoot, "src", "global.d.ts")
|
||||
fs.writeFileSync(dtsPath, `/// <reference types="svelte" />`)
|
||||
|
||||
// Delete this script, but not during testing
|
||||
if (!argv[2]) {
|
||||
// Remove the script
|
||||
fs.unlinkSync(path.join(__filename))
|
||||
|
||||
// Check for Mac's DS_store file, and if it's the only one left remove it
|
||||
const remainingFiles = fs.readdirSync(path.join(__dirname))
|
||||
if (remainingFiles.length === 1 && remainingFiles[0] === '.DS_store') {
|
||||
fs.unlinkSync(path.join(__dirname, '.DS_store'))
|
||||
}
|
||||
|
||||
// Check if the scripts folder is empty
|
||||
if (fs.readdirSync(path.join(__dirname)).length === 0) {
|
||||
// Remove the scripts folder
|
||||
fs.rmdirSync(path.join(__dirname))
|
||||
}
|
||||
}
|
||||
|
||||
// Adds the extension recommendation
|
||||
fs.mkdirSync(path.join(projectRoot, ".vscode"), { recursive: true })
|
||||
fs.writeFileSync(path.join(projectRoot, ".vscode", "extensions.json"), `{
|
||||
"recommendations": ["svelte.svelte-vscode"]
|
||||
}
|
||||
`)
|
||||
|
||||
console.log("Converted to TypeScript.")
|
||||
|
||||
if (fs.existsSync(path.join(projectRoot, "node_modules"))) {
|
||||
console.log("\nYou will need to re-run your dependency manager to get started.")
|
||||
}
|
276
src/App.svelte
276
src/App.svelte
@ -1,169 +1,175 @@
|
||||
<script>
|
||||
import { onMount, setContext } from 'svelte'
|
||||
import Message from './Message.svelte'
|
||||
import Name from './Name.svelte'
|
||||
import { sleep } from './util.js'
|
||||
<script lang="ts">
|
||||
import { onMount, setContext } from "svelte";
|
||||
import Message from "./Message.svelte";
|
||||
import Name from "./Name.svelte";
|
||||
import { sleep } from "./util.js";
|
||||
|
||||
const LUOXU_URL = 'https://lab.lilydjwg.me/luoxu'
|
||||
const islocal = LUOXU_URL.indexOf('http://localhost') === 0
|
||||
let groups = []
|
||||
let group
|
||||
let query
|
||||
let error
|
||||
let result
|
||||
let now = new Date()
|
||||
let loading = false
|
||||
let need_update_title = false
|
||||
let sender
|
||||
let selected_init
|
||||
let our_hash_change = false
|
||||
const LUOXU_URL = "https://lab.lilydjwg.me/luoxu";
|
||||
const islocal = LUOXU_URL.startsWith("http://localhost");
|
||||
let groups = [];
|
||||
let group: string;
|
||||
let query: string;
|
||||
let error: string;
|
||||
let result: { messages: string | any[]; has_more: any; groupinfo: any };
|
||||
let now = new Date();
|
||||
let loading = false;
|
||||
let need_update_title = false;
|
||||
let sender: string;
|
||||
let selected_init: string;
|
||||
let our_hash_change = false;
|
||||
|
||||
setContext('LUOXU_URL', LUOXU_URL)
|
||||
setContext("LUOXU_URL", LUOXU_URL);
|
||||
|
||||
function parse_hash() {
|
||||
const hash = location.hash
|
||||
if(hash) {
|
||||
return new URLSearchParams(hash.substring(1))
|
||||
const hash = location.hash;
|
||||
if (hash) {
|
||||
return new URLSearchParams(hash.substring(1));
|
||||
}
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
do_hash_search()
|
||||
while(true) {
|
||||
try{
|
||||
const res = await fetch(`${LUOXU_URL}/groups`)
|
||||
groups = (await res.json()).groups
|
||||
need_update_title = true
|
||||
if(!group) {
|
||||
group = ''
|
||||
do_hash_search();
|
||||
while (true) {
|
||||
try {
|
||||
const res = await fetch(`${LUOXU_URL}/groups`);
|
||||
groups = (await res.json()).groups;
|
||||
need_update_title = true;
|
||||
if (!group) {
|
||||
group = "";
|
||||
}
|
||||
break
|
||||
}catch(e){
|
||||
console.error('failed to fetch group info, will retry', e)
|
||||
await sleep(1000)
|
||||
break;
|
||||
} catch (e) {
|
||||
console.error("failed to fetch group info, will retry", e);
|
||||
await sleep(1000);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
$: {
|
||||
// only update title on hash change (doing a search)
|
||||
if(need_update_title && groups) {
|
||||
let group_name
|
||||
for(const g of groups) {
|
||||
if(g.group_id == group) {
|
||||
group_name = g.name
|
||||
if (need_update_title && groups) {
|
||||
let group_name: any;
|
||||
for (const g of groups) {
|
||||
if (g.group_id === group) {
|
||||
group_name = g.name;
|
||||
}
|
||||
}
|
||||
if(query && group_name) {
|
||||
document.title = `搜索:${query} 于 ${group_name} - 落絮`
|
||||
}else if(query) {
|
||||
document.title = `搜索:${query} - 落絮`
|
||||
}else if(group_name) {
|
||||
document.title = `搜索 ${group_name} - 落絮`
|
||||
}else{
|
||||
document.title = '落絮'
|
||||
if (query && group_name) {
|
||||
document.title = `搜索:${query} 于 ${group_name} - 落絮`;
|
||||
} else if (query) {
|
||||
document.title = `搜索:${query} - 落絮`;
|
||||
} else if (group_name) {
|
||||
document.title = `搜索 ${group_name} - 落絮`;
|
||||
} else {
|
||||
document.title = "落絮";
|
||||
}
|
||||
need_update_title = false
|
||||
need_update_title = false;
|
||||
}
|
||||
}
|
||||
|
||||
function do_hash_search() {
|
||||
const info = parse_hash()
|
||||
if(info) {
|
||||
query = ''
|
||||
group = ''
|
||||
result = null
|
||||
if(info.has('g')) {
|
||||
group = info.get('g')|0
|
||||
const info = parse_hash();
|
||||
if (info) {
|
||||
query = "";
|
||||
group = "";
|
||||
result = null;
|
||||
if (info.has("g")) {
|
||||
group = (parseFloat(info.get("g")) | 0).toString();
|
||||
}
|
||||
if(info.has('q')) {
|
||||
query = info.get('q')
|
||||
if (info.has("q")) {
|
||||
query = info.get("q");
|
||||
}
|
||||
if(info.has('sender')) {
|
||||
sender = info.get('sender')
|
||||
selected_init = sender
|
||||
if (info.has("sender")) {
|
||||
sender = info.get("sender");
|
||||
selected_init = sender;
|
||||
}
|
||||
if((group || islocal) && query) {
|
||||
result = null
|
||||
do_search()
|
||||
if ((group || islocal) && query) {
|
||||
result = null;
|
||||
do_search();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function do_search(more) {
|
||||
if(!group && !islocal) {
|
||||
error = '请选择要搜索的群组'
|
||||
return
|
||||
async function do_search(more?: any) {
|
||||
if (!group && !islocal) {
|
||||
error = "请选择要搜索的群组";
|
||||
return;
|
||||
}
|
||||
if(!query && !islocal) {
|
||||
error = '请输入搜索关键字'
|
||||
return
|
||||
if (!query && !islocal) {
|
||||
error = "请输入搜索关键字";
|
||||
return;
|
||||
}
|
||||
error = ''
|
||||
our_hash_change = true
|
||||
console.log(`searching ${query} for group ${group}, older than ${more}, from ${sender}`)
|
||||
const q = new URLSearchParams()
|
||||
if(group) {
|
||||
q.append('g', group)
|
||||
error = "";
|
||||
our_hash_change = true;
|
||||
console.log(
|
||||
`searching ${query} for group ${group}, older than ${more}, from ${sender}`
|
||||
);
|
||||
const q = new URLSearchParams();
|
||||
if (group) {
|
||||
q.append("g", group);
|
||||
}
|
||||
if(query) {
|
||||
q.append('q', query)
|
||||
if (query) {
|
||||
q.append("q", query);
|
||||
}
|
||||
if(sender) {
|
||||
q.append('sender', sender)
|
||||
if (sender) {
|
||||
q.append("sender", sender);
|
||||
}
|
||||
let url
|
||||
const qstr = q.toString()
|
||||
if(!more) {
|
||||
location.hash = `#${qstr}`
|
||||
need_update_title = true
|
||||
if(result) {
|
||||
result.messages = []
|
||||
let url: RequestInfo | URL;
|
||||
const qstr = q.toString();
|
||||
if (!more) {
|
||||
location.hash = `#${qstr}`;
|
||||
need_update_title = true;
|
||||
if (result) {
|
||||
result.messages = [];
|
||||
}
|
||||
url = `${LUOXU_URL}/search?${qstr}`
|
||||
}else{
|
||||
url = `${LUOXU_URL}/search?${q}&end=${more}`
|
||||
url = `${LUOXU_URL}/search?${qstr}`;
|
||||
} else {
|
||||
url = `${LUOXU_URL}/search?${q}&end=${more}`;
|
||||
}
|
||||
|
||||
now = new Date()
|
||||
loading = true
|
||||
try{
|
||||
const res = await fetch(url)
|
||||
const r = await res.json()
|
||||
loading = false
|
||||
if(more) {
|
||||
return r
|
||||
}else{
|
||||
result = r
|
||||
now = new Date();
|
||||
loading = true;
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
const r = await res.json();
|
||||
loading = false;
|
||||
if (more) {
|
||||
return r;
|
||||
} else {
|
||||
result = r;
|
||||
}
|
||||
}catch(e){
|
||||
error = e
|
||||
loading = false
|
||||
} catch (e) {
|
||||
error = e;
|
||||
loading = false;
|
||||
}
|
||||
our_hash_change = false;
|
||||
}
|
||||
|
||||
async function on_group_change() {
|
||||
error = ''
|
||||
if(query) {
|
||||
await do_search()
|
||||
error = "";
|
||||
if (query) {
|
||||
await do_search();
|
||||
}
|
||||
}
|
||||
|
||||
async function do_search_more() {
|
||||
const more = result.messages[result.messages.length-1].t
|
||||
const old_msgs = result.messages
|
||||
const new_result = await do_search(more)
|
||||
result.messages = [...old_msgs, ...new_result.messages]
|
||||
result.has_more = new_result.has_more
|
||||
const more = result.messages[result.messages.length - 1].t;
|
||||
const old_msgs = result.messages;
|
||||
const new_result = await do_search(more);
|
||||
result.messages = [...old_msgs, ...new_result.messages];
|
||||
result.has_more = new_result.has_more;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window on:hashchange={() => {if(!our_hash_change) do_hash_search()}}/>
|
||||
<svelte:window
|
||||
on:hashchange={() => {
|
||||
if (!our_hash_change) do_hash_search();
|
||||
}}
|
||||
/>
|
||||
|
||||
<main>
|
||||
<div id="searchbox">
|
||||
{#if groups.length == 0}
|
||||
{#if groups.length === 0}
|
||||
<select>
|
||||
<option selected>正在加载群组信息...</option>
|
||||
</select>
|
||||
@ -177,21 +183,30 @@
|
||||
{/each}
|
||||
</select>
|
||||
{/if}
|
||||
<input type="search" bind:value={query}
|
||||
on:input={() => error = ''}
|
||||
on:keydown={e => {if(e.key == 'Enter'){do_search()}}}
|
||||
<input
|
||||
type="search"
|
||||
bind:value={query}
|
||||
on:input={() => (error = "")}
|
||||
on:keydown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
do_search();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Name group={group} bind:selected={sender} selected_init={selected_init}/>
|
||||
<Name {group} bind:selected={sender} {selected_init} />
|
||||
<button on:click={() => do_search()}>搜索</button>
|
||||
</div>
|
||||
|
||||
{#if result}
|
||||
{#each result.messages as message}
|
||||
<Message msg={message} groupinfo={result.groupinfo} now={now} />
|
||||
<Message msg={message} groupinfo={result.groupinfo} {now} />
|
||||
{/each}
|
||||
{:else if !loading && !error}
|
||||
<div>
|
||||
<p>搜索消息时,搜索字符串不区分简繁(会使用 OpenCC 自动转换),也不进行分词(请手动将可能不连在一起的词语以空格分开)。</p>
|
||||
<p>
|
||||
搜索消息时,搜索字符串不区分简繁(会使用 OpenCC
|
||||
自动转换),也不进行分词(请手动将可能不连在一起的词语以空格分开)。
|
||||
</p>
|
||||
<p>搜索字符串支持以下功能:</p>
|
||||
<ul>
|
||||
<li>以空格分开的多个搜索词是「与」的关系</li>
|
||||
@ -200,7 +215,10 @@
|
||||
<li>使用小括号来分组</li>
|
||||
</ul>
|
||||
<p>人名补全支持上下方向键和 Alt+N/P 进行选择。</p>
|
||||
<p>搜索结果右下角的时间,悬停可查看绝对时间、最后编辑时间(如编辑过),点击可跳转到 Telegram 中展示该消息。</p>
|
||||
<p>
|
||||
搜索结果右下角的时间,悬停可查看绝对时间、最后编辑时间(如编辑过),点击可跳转到
|
||||
Telegram 中展示该消息。
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@ -209,13 +227,15 @@
|
||||
{:else}
|
||||
{#if error}
|
||||
<p class="error">{error}</p>
|
||||
{:else if result && result.messages.length == 0}
|
||||
{:else if result && result.messages.length === 0}
|
||||
<div class="info"><p>没有匹配的消息。</p></div>
|
||||
{:else if result && !result.has_more}
|
||||
<div class="info"><p>到底了。</p></div>
|
||||
{/if}
|
||||
{#if result && result.has_more}
|
||||
<div class="info"><button on:click={do_search_more}>加载更多</button></div>
|
||||
<div class="info">
|
||||
<button on:click={do_search_more}>加载更多</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</main>
|
||||
@ -232,7 +252,7 @@
|
||||
#searchbox {
|
||||
display: flex;
|
||||
}
|
||||
#searchbox input[type=search] {
|
||||
#searchbox input[type="search"] {
|
||||
flex-grow: 1;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
@ -259,12 +279,16 @@
|
||||
border-radius: 2em;
|
||||
}
|
||||
|
||||
:global(input), :global(button), :global(select) {
|
||||
:global(input),
|
||||
:global(button),
|
||||
:global(select) {
|
||||
border-radius: 0;
|
||||
border: 1px solid var(--color-inactive);
|
||||
height: 2.3em;
|
||||
}
|
||||
:global(input:focus), :global(button:focus), :global(select:focus) {
|
||||
:global(input:focus),
|
||||
:global(button:focus),
|
||||
:global(select:focus) {
|
||||
border-color: var(--color-active);
|
||||
outline: 1px solid var(--color-active);
|
||||
}
|
||||
|
@ -1,58 +1,69 @@
|
||||
<script>
|
||||
import { onMount, getContext } from 'svelte'
|
||||
import { onMount, getContext } from "svelte";
|
||||
|
||||
export let msg
|
||||
export let groupinfo
|
||||
export let now
|
||||
export let msg;
|
||||
export let groupinfo;
|
||||
export let now;
|
||||
|
||||
const formatter = new Intl.DateTimeFormat(undefined, {
|
||||
timeStyle: "full",
|
||||
dateStyle: "full",
|
||||
hour12: false,
|
||||
})
|
||||
});
|
||||
|
||||
let dt = new Date(msg.t * 1000)
|
||||
let edited = msg.edited ? new Date(msg.edited * 1000) : null
|
||||
let title = format_dt(dt) + (edited ? `\n最后编辑于:${format_dt(edited)}` : '')
|
||||
let relative_dt = format_relative_time(dt, now)
|
||||
let iso_date = dt.toISOString()
|
||||
let msgurl = groupinfo[msg.group_id][0] ? `tg://resolve?domain=${groupinfo[msg.group_id][0]}&post=${msg.id}` : `tg://privatepost?channel=${msg.group_id}&post=${msg.id}`
|
||||
let dt = new Date(msg.t * 1000);
|
||||
let edited = msg.edited ? new Date(msg.edited * 1000) : null;
|
||||
let title =
|
||||
format_dt(dt) + (edited ? `\n最后编辑于:${format_dt(edited)}` : "");
|
||||
let relative_dt = format_relative_time(dt, now);
|
||||
let iso_date = dt.toISOString();
|
||||
let msgurl = groupinfo[msg.group_id][0]
|
||||
? `tg://resolve?domain=${groupinfo[msg.group_id][0]}&post=${msg.id}`
|
||||
: `tg://privatepost?channel=${msg.group_id}&post=${msg.id}`;
|
||||
|
||||
function format_relative_time(d1, d2) {
|
||||
// in miliseconds
|
||||
const units = {
|
||||
year : 24 * 60 * 60 * 1000 * 365,
|
||||
month : 24 * 60 * 60 * 1000 * 365 / 12,
|
||||
day : 24 * 60 * 60 * 1000,
|
||||
hour : 60 * 60 * 1000,
|
||||
year: 24 * 60 * 60 * 1000 * 365,
|
||||
month: (24 * 60 * 60 * 1000 * 365) / 12,
|
||||
day: 24 * 60 * 60 * 1000,
|
||||
hour: 60 * 60 * 1000,
|
||||
minute: 60 * 1000,
|
||||
second: 1000,
|
||||
}
|
||||
};
|
||||
|
||||
const rtf = new Intl.RelativeTimeFormat()
|
||||
const rtf = new Intl.RelativeTimeFormat();
|
||||
|
||||
const elapsed = d1 - d2
|
||||
const elapsed = d1 - d2;
|
||||
|
||||
for(const u in units) {
|
||||
if(Math.abs(elapsed) > units[u] || u == 'second') {
|
||||
return rtf.format(Math.round(elapsed/units[u]), u)
|
||||
for (const u in units) {
|
||||
if (Math.abs(elapsed) > units[u] || u === "second") {
|
||||
return rtf.format(Math.round(elapsed / units[u]), u);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function format_dt(t) {
|
||||
return formatter.format(t)
|
||||
return formatter.format(t);
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<div class="message">
|
||||
<img class="avatar" src="{getContext('LUOXU_URL')}/avatar/{msg.from_id}.jpg" height="64" width="64" alt="{msg.from_name} 的头像"/>
|
||||
<img
|
||||
class="avatar"
|
||||
src="{getContext('LUOXU_URL')}/avatar/{msg.from_id}.jpg"
|
||||
height="64"
|
||||
width="64"
|
||||
alt="{msg.from_name} 的头像"
|
||||
/>
|
||||
<div class="content">
|
||||
<div class="name">{msg.from_name || ' '}</div>
|
||||
<div class="name">{msg.from_name || " "}</div>
|
||||
<div class="text">{@html msg.html}</div>
|
||||
<div class="time">{groupinfo[msg.group_id][1]} <a href={msgurl}><time datetime={iso_date} title={title}>{relative_dt}</time></a></div>
|
||||
<div class="time">
|
||||
{groupinfo[msg.group_id][1]}
|
||||
<a href={msgurl}><time datetime={iso_date} {title}>{relative_dt}</time></a
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -82,14 +93,15 @@
|
||||
white-space: pre-wrap;
|
||||
margin: 0.2em 0;
|
||||
}
|
||||
.text >:global(.keyword) {
|
||||
.text > :global(.keyword) {
|
||||
background-color: #ffffab;
|
||||
}
|
||||
.time {
|
||||
font-size: 0.75em;
|
||||
float: right;
|
||||
}
|
||||
.time, .time > a {
|
||||
.time,
|
||||
.time > a {
|
||||
color: gray;
|
||||
}
|
||||
</style>
|
||||
|
202
src/Name.svelte
202
src/Name.svelte
@ -1,145 +1,164 @@
|
||||
<script>
|
||||
import { onMount, getContext } from 'svelte'
|
||||
import { onMount, getContext } from "svelte";
|
||||
|
||||
export let group
|
||||
export let group;
|
||||
|
||||
export let selected
|
||||
export let selected_init
|
||||
let selected_name = ''
|
||||
let selected_idx
|
||||
export let selected;
|
||||
export let selected_init;
|
||||
let selected_name = "";
|
||||
let selected_idx;
|
||||
|
||||
let to
|
||||
let names = []
|
||||
let url = getContext('LUOXU_URL')
|
||||
let input
|
||||
let ul
|
||||
let should_hide = false
|
||||
let to;
|
||||
let names = [];
|
||||
let url = getContext("LUOXU_URL");
|
||||
let input;
|
||||
let ul;
|
||||
let should_hide = false;
|
||||
|
||||
let abort = new AbortController()
|
||||
let abort = new AbortController();
|
||||
|
||||
onMount(() => {
|
||||
const rect = input.getBoundingClientRect()
|
||||
ul.style.top = `${rect.height - 1}px`
|
||||
ul.style.width = `${rect.width - 2}px`
|
||||
})
|
||||
const rect = input.getBoundingClientRect();
|
||||
ul.style.top = `${rect.height - 1}px`;
|
||||
ul.style.width = `${rect.width - 2}px`;
|
||||
});
|
||||
|
||||
function update_list_width() {
|
||||
const rect = input.getBoundingClientRect()
|
||||
ul.style.width = `${rect.width - 2}px`
|
||||
const rect = input.getBoundingClientRect();
|
||||
ul.style.width = `${rect.width - 2}px`;
|
||||
}
|
||||
|
||||
function may_complete() {
|
||||
if(to) {
|
||||
clearTimeout(to)
|
||||
if (to) {
|
||||
clearTimeout(to);
|
||||
}
|
||||
to = setTimeout(function(){
|
||||
complete_it()
|
||||
}, 300)
|
||||
to = setTimeout(function () {
|
||||
complete_it();
|
||||
}, 300);
|
||||
}
|
||||
|
||||
async function complete_it() {
|
||||
if(!input.value) {
|
||||
return
|
||||
if (!input.value) {
|
||||
return;
|
||||
}
|
||||
selected_idx = null
|
||||
abort.abort()
|
||||
abort = new AbortController()
|
||||
try{
|
||||
const res = await fetch(`${url}/names?g=${group}&q=${input.value}`,
|
||||
{signal: abort.signal})
|
||||
const j = await res.json()
|
||||
if(!abort.aborted) {
|
||||
selected_idx = null;
|
||||
abort.abort();
|
||||
abort = new AbortController();
|
||||
try {
|
||||
const res = await fetch(`${url}/names?g=${group}&q=${input.value}`, {
|
||||
signal: abort.signal,
|
||||
});
|
||||
const j = await res.json();
|
||||
if (!abort.aborted) {
|
||||
// only update if we're current
|
||||
names = j.names
|
||||
names = j.names;
|
||||
}
|
||||
}catch(e){
|
||||
if(e instanceof DOMException && e.name == 'AbortError'){
|
||||
}else{
|
||||
console.error(e)
|
||||
} catch (e) {
|
||||
if (e instanceof DOMException && e.name === "AbortError") {
|
||||
} else {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function select_by_click(e) {
|
||||
let el = e.target
|
||||
if(el.tagName == 'IMG') {
|
||||
el = el.parentNode
|
||||
let el = e.target;
|
||||
if (el.tagName === "IMG") {
|
||||
el = el.parentNode;
|
||||
}
|
||||
if(el.tagName != 'LI') {
|
||||
return
|
||||
if (el.tagName != "LI") {
|
||||
return;
|
||||
}
|
||||
selected_idx = el.dataset.idx|0
|
||||
select_confirmed()
|
||||
input.focus()
|
||||
should_hide = true
|
||||
selected_idx = el.dataset.idx | 0;
|
||||
select_confirmed();
|
||||
input.focus();
|
||||
should_hide = true;
|
||||
}
|
||||
|
||||
function select_confirmed() {
|
||||
selected = names[selected_idx][0]
|
||||
selected_name = names[selected_idx][1]
|
||||
input.value = selected_name
|
||||
selected_init = null
|
||||
selected = names[selected_idx][0];
|
||||
selected_name = names[selected_idx][1];
|
||||
input.value = selected_name;
|
||||
selected_init = null;
|
||||
}
|
||||
|
||||
function update_value() {
|
||||
if(!selected || selected === selected_init) {
|
||||
return
|
||||
if (!selected || selected === selected_init) {
|
||||
return;
|
||||
}
|
||||
if(input.value) {
|
||||
input.value = selected_name
|
||||
}else{
|
||||
selected = selected_init
|
||||
selected_name = ''
|
||||
if (input.value) {
|
||||
input.value = selected_name;
|
||||
} else {
|
||||
selected = selected_init;
|
||||
selected_name = "";
|
||||
}
|
||||
}
|
||||
|
||||
function select_by_key(e) {
|
||||
if(e.key == 'ArrowDown' || (e.key == 'n' && e.altKey)) {
|
||||
select_next(1)
|
||||
e.preventDefault()
|
||||
}else if(e.key == 'ArrowUp' || (e.key == 'p' && e.altKey)) {
|
||||
select_next(-1)
|
||||
e.preventDefault()
|
||||
}else if(e.key == 'Enter') {
|
||||
select_confirmed()
|
||||
e.preventDefault()
|
||||
if (e.key === "ArrowDown" || (e.key === "n" && e.altKey)) {
|
||||
select_next(1);
|
||||
e.preventDefault();
|
||||
} else if (e.key === "ArrowUp" || (e.key === "p" && e.altKey)) {
|
||||
select_next(-1);
|
||||
e.preventDefault();
|
||||
} else if (e.key === "Enter") {
|
||||
select_confirmed();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
function select_next(dir) {
|
||||
if(typeof selected_idx === 'number') {
|
||||
if(dir > 0) {
|
||||
selected_idx = (selected_idx + 1) % names.length
|
||||
}else{
|
||||
selected_idx = (selected_idx - 1) % names.length
|
||||
if (typeof selected_idx === "number") {
|
||||
if (dir > 0) {
|
||||
selected_idx = (selected_idx + 1) % names.length;
|
||||
} else {
|
||||
selected_idx = (selected_idx - 1) % names.length;
|
||||
}
|
||||
}else{
|
||||
if(dir > 0) {
|
||||
selected_idx = 0
|
||||
}else{
|
||||
selected_idx = names.length - 1
|
||||
} else {
|
||||
if (dir > 0) {
|
||||
selected_idx = 0;
|
||||
} else {
|
||||
selected_idx = names.length - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<input bind:this={input} type="text"
|
||||
on:input={() => {should_hide=false;may_complete()}}
|
||||
on:focus={() => should_hide=false}
|
||||
on:blur={() => {should_hide=true;update_value()}}
|
||||
<input
|
||||
bind:this={input}
|
||||
type="text"
|
||||
on:input={() => {
|
||||
should_hide = false;
|
||||
may_complete();
|
||||
}}
|
||||
on:focus={() => (should_hide = false)}
|
||||
on:blur={() => {
|
||||
should_hide = true;
|
||||
update_value();
|
||||
}}
|
||||
on:keydown={select_by_key}
|
||||
/>
|
||||
<img class="selected-avatar" alt="" src="{url}/avatar/{selected?selected:'nobody'}.jpg"/>
|
||||
<ul bind:this={ul} on:click={select_by_click} on:mousedown|preventDefault={()=>{}} class:hidden={names.length === 0 || should_hide}>
|
||||
<img
|
||||
class="selected-avatar"
|
||||
alt=""
|
||||
src="{url}/avatar/{selected ? selected : 'nobody'}.jpg"
|
||||
/>
|
||||
<ul
|
||||
bind:this={ul}
|
||||
on:click={select_by_click}
|
||||
on:mousedown|preventDefault={() => {}}
|
||||
class:hidden={names.length === 0 || should_hide}
|
||||
>
|
||||
{#each names as name, i (name)}
|
||||
<li data-idx={i} class:selected={i===selected_idx} title={name[1]}><img src="{url}/avatar/{name[0]}.jpg" alt="avatar"/>{name[1]}</li>
|
||||
<li data-idx={i} class:selected={i === selected_idx} title={name[1]}>
|
||||
<img src="{url}/avatar/{name[0]}.jpg" alt="avatar" />{name[1]}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<svelte:window on:resize={update_list_width}/>
|
||||
<svelte:window on:resize={update_list_width} />
|
||||
|
||||
<style>
|
||||
div {
|
||||
@ -171,18 +190,21 @@
|
||||
display: inline-block;
|
||||
overflow: hidden;
|
||||
}
|
||||
ul:not(:hover) > li.selected, li:hover {
|
||||
ul:not(:hover) > li.selected,
|
||||
li:hover {
|
||||
background-color: #d9f5ff;
|
||||
}
|
||||
input {
|
||||
padding-left: 2.5em;
|
||||
width: 100%;
|
||||
}
|
||||
input, ul {
|
||||
input,
|
||||
ul {
|
||||
border-radius: 0;
|
||||
border: 1px solid var(--color-inactive);
|
||||
}
|
||||
input:focus, input:focus ~ ul {
|
||||
input:focus,
|
||||
input:focus ~ ul {
|
||||
border-color: var(--color-active);
|
||||
box-shadow: 0 0 4px var(--color-active);
|
||||
outline: 1px solid var(--color-active);
|
||||
|
1
src/global.d.ts
vendored
Normal file
1
src/global.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
||||
/// <reference types="svelte" />
|
6
tsconfig.json
Normal file
6
tsconfig.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "@tsconfig/svelte/tsconfig.json",
|
||||
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
|
||||
}
|
Loading…
Reference in New Issue
Block a user