DOM
object
%charts
/phlo/resources/DOM/charts.phlo
static
charts :: spark ($values, $color = '#888', $w = 240, $h = 48, $label = null):string
line 8
根据提供的值生成SVG火花线图,计算渲染所需的点和区域。
$values = array_values(array_map('floatval', (array)$values))
if (!$values) return void
$max = max($values) ?: 1
$min = min($values)
$range = max(0.0001, $max - $min)
$count = count($values)
$step = $count > 1 ? $w / ($count - 1) : 0
$points = []
foreach ($values AS $i => $v){
$x = round($i * $step, 1)
$y = round($h - (($v - $min) / $range) * ($h - 6) - 3, 1)
$points[] = "$x,$y"
}
$area = array_merge($points, [round($w, 1).comma.$h, '0,'.$h])
$id = 'g'.substr(md5(implode(comma, $points)), 0, 6)
$aria = $label !== null ? ' role="img" aria-label="'.esc($label).'"' : void
return '<svg viewBox="0 0 '.$w.' '.$h.'"'.$aria.' xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" style="display:block;width:100%;height:'.$h.'px"><defs><linearGradient id="'.$id.'" x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stop-color="'.$color.'" stop-opacity=".4"/><stop offset="100%" stop-color="'.$color.'" stop-opacity="0"/></linearGradient></defs><polygon points="'.implode(space, $area).'" fill="url(#'.$id.')"/><polyline points="'.implode(space, $points).'" fill="none" stroke="'.$color.'" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round"/></svg>'static
charts :: bars ($values, $color = '#888', $w = 240, $h = 48, $label = null):string
line 28
根据提供的值生成SVG条形图,计算每个条形相对于最大值的高度和位置。
$values = array_values(array_map('floatval', (array)$values))
if (!$values) return void
$max = max($values) ?: 1
$count = count($values)
$gap = 2
$bw = max(1, ($w - ($count - 1) * $gap) / $count)
$out = void
foreach ($values AS $i => $v){
$bh = round(($v / $max) * ($h - 4), 1)
$x = round($i * ($bw + $gap), 1)
$y = round($h - $bh, 1)
$out .= '<rect x="'.$x.'" y="'.$y.'" width="'.round($bw, 1).'" height="'.max(0.5, $bh).'" fill="'.$color.'" rx="1.5"/>'
}
$aria = $label !== null ? ' role="img" aria-label="'.esc($label).'"' : void
return '<svg viewBox="0 0 '.$w.' '.$h.'"'.$aria.' xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" style="display:block;width:100%;height:'.$h.'px">'.$out.'</svg>'static
charts :: donut ($parts, $colors = null, $size = 120):string
line 46
根据提供的部分生成SVG甜甜圈图,计算每个部分的比例和颜色。
$parts = array_filter(array_map('floatval', (array)$parts))
$total = array_sum($parts)
if (!$total) return void
$colors ??= ['#FFC76B', '#6CC0FF', '#9D7BFF', '#6BE39E', '#FF8A5C', '#FF6B6B']
$cx = $size / 2
$cy = $size / 2
$r = $size * 0.4
$circumference = 2 * M_PI * $r
$out = void
$rotate = -90
$i = 0
foreach ($parts AS $value){
$len = ($value / $total) * $circumference
$color = $colors[$i % count($colors)]
$out .= '<circle cx="'.$cx.'" cy="'.$cy.'" r="'.$r.'" fill="none" stroke="'.$color.'" stroke-width="'.($size * 0.18).'" stroke-dasharray="'.$len.space.$circumference.'" transform="rotate('.$rotate.space.$cx.space.$cy.')"/>'
$rotate += ($value / $total) * 360
$i++
}
return '<svg viewBox="0 0 '.$size.' '.$size.'" xmlns="http://www.w3.org/2000/svg" style="display:block;width:'.$size.'px;height:'.$size.'px">'.$out.'<circle cx="'.$cx.'" cy="'.$cy.'" r="'.($r - $size * 0.09).'" fill="rgba(255,255,255,.04)"/></svg>'object
%connection
/phlo/resources/DOM/connection.phlo
view
script
line 9
app.connection = {
online: true,
since: Date.now(),
reason: 'start',
subs: [],
on(event, cb){
app.connection.subs.push(cb)
return () => app.connection.subs = app.connection.subs.filter(sub => sub !== cb)
},
set(online, reason){
if (online === app.connection.online) return
Object.assign(app.connection, {online, reason, since: Date.now()})
document.body.classList.toggle('offline', !online)
phlo.log('🖧 Connection ' + (online ? 'online' : 'offline'), reason)
app.connection.subs.forEach(cb => cb(online, reason))
},
attempting: false,
}
Object.defineProperty(app, 'online', {get: () => app.connection.online})
const connectionRequest = phlo.request
phlo.request = (...args) => {
const xhr = connectionRequest(...args)
if (xhr){
xhr.addEventListener('load', () => app.connection.set(true, 'response'))
xhr.addEventListener('error', () => app.connection.set(false, 'request'))
xhr.addEventListener('timeout', () => app.connection.set(false, 'timeout'))
}
return xhr
}
queueMicrotask(() => {
app.websocket?.on?.('connect', () => [app.connection.attempting = false, app.connection.set(true, 'websocket')])
app.websocket?.on?.('close', () => app.connection.attempting = true)
app.websocket?.on?.('error', () => app.connection.attempting && app.connection.set(false, 'websocket'))
})object
%cookiewall
/phlo/resources/DOM/cookiewall.phlo
static
cookiewall :: __handle
line 9
此方法处理 cookie wall 功能,管理用户对 cookies 的同意。
nullprop
%cookiewall -> choice
line 11
从 %cookies 对象中获取 'cookieChoice' 的值,如果未设置则返回 null。
%cookies->cookieChoice ?? nullmethod
%cookiewall -> hasChosen:bool
line 12
通过验证选择不为 null 来检查是否已做出选择。
$this->choice !== nullmethod
%cookiewall -> canTrack:bool
line 13
根据用户的选择确定是否允许跟踪,特别是如果设置为'all'。
$this->choice === 'all'method
%cookiewall -> canAnalytics:bool
line 14
检查当前选择是否设置为'all'以确定是否可以启用分析。
$this->choice === 'all'prop
%cookiewall -> translate:bool
line 16
检查当前作用域中是否存在函数'en'。
function_exists('en')prop
%cookiewall -> labels:array
line 17
定义了一组用于cookie同意墙的标签,包括区域标题、主体文本和按钮标签。
arr(
region: 'Cookie choice',
body: 'We use essential cookies to make this site work. With your permission we also use analytics to improve the site.',
essential: 'Essential only',
accept: 'Accept',
)method
%cookiewall -> label ($key):string
line 23
检索与指定键关联的标签,如果启用了翻译,则进行翻译。
$this->translate ? en($this->labels[$key]) : $this->labels[$key]route
route async POST cookiewall accept all
line 25
定义一个路由,设置一个cookie,表示用户已接受所有cookie,并异步移除cookiewall视图。
%cookies->objSet('cookieChoice', 'all', ['expires' => time() + 60 * 60 * 24 * 365, 'httponly' => false])
apply(remove: '#cookiewall')route
route async POST cookiewall accept essential
line 30
该路由设置一个名为'cookieChoice'的cookie,其值为'essential',有效期为一年,然后应用移除ID为'cookiewall'的元素。
%cookies->objSet('cookieChoice', 'essential', ['expires' => time() + 60 * 60 * 24 * 365, 'httponly' => false])
apply(remove: '#cookiewall')view
%cookiewall -> banner
line 35
如果用户尚未做出选择,则显示一个提示用户接受基本或所有cookie的cookie同意墙。
<if !$this->hasChosen()>
<div#cookiewall role=region aria-label="{{ $this->label('region') }}">
<p>{{ $this->label('body') }}</p>
<div.actions>
<form.async method=post action=/cookiewall/accept/essential>
<button.ghost type=submit>{{ $this->label('essential') }}</button>
</form>
<form.async method=post action=/cookiewall/accept/all>
<button.primary type=submit>{{ $this->label('accept') }}</button>
</form>
</div>
</div>
</if>view
style
line 50
定义cookiewall组件的CSS样式,包括布局、颜色和响应式设计。
#cookiewall {
background: #1a1a1a
border-radius: 8px
bottom: 16px
box-shadow: 0 8px 32px #0004
color: #fff
font-size: 13px
left: 16px
line-height: 1.5
max-width: 360px
padding: 14px 16px
position: fixed
right: 16px
z-index: 9999
@media(min-width: 600px): right: auto
p: margin: 0 0 10px
.actions {
display: flex
gap: 8px
justify-content: flex-end
}
button {
border-radius: 4px
border: 0
cursor: pointer
font-size: 12px
padding: 6px 12px
}
button.ghost {
background: #444
color: #fff
}
button.primary {
background: #fff
color: #1a1a1a
font-weight: 600
}
}object
%CSS_fixes
/phlo/resources/DOM/CSS.fixes.phlo
view
style
line 8
*, ::before, ::after: box-sizing: border-box
a, area, button, input, label, select, summary, textarea, [tabindex]: touch-action: manipulation
button:focus, input:focus, select:focus, textarea:focus, [contenteditable]:focus: outline: 0
input::-webkit-outer-spin-button, input::-webkit-inner-spin-button: -webkit-appearance: none
input[type="number"]: -moz-appearance: textfield
table: border-collapse: collapse
[hidden]: display: none !important
::-ms-expand: display: noneobject
%CSS_var
/phlo/resources/DOM/CSS.var.phlo
view
script
line 8
定义一个代理,用于访问和修改文档根元素上的 CSS 自定义属性(变量),允许动态更新和检索它们的值。
Object.defineProperty(app, 'var', {get(){return new Proxy({}, {get(_, key){return getComputedStyle(document.documentElement).getPropertyValue(`--${key}`).trim()}, set(_, key, value){ return document.documentElement.style.setProperty(`--${key}`, value)}})}, configurable: true})
app.mod.setvar = (key, value) => app.var[key] = valueobject
%datatags
/phlo/resources/DOM/datatags.phlo
view
script
line 9
处理带有数据属性的元素的点击事件,防止默认操作,并使用指定的路径和数据执行相应的方法。
on('click', '[data-get], [data-post], [data-put], [data-patch], [data-delete]', (el, e) => {
if (el.dataset.confirm) return
e.preventDefault()
let method, path, data = null
if ((path = el.dataset.get) !== undefined) method = 'get'
else if ((path = el.dataset.delete) !== undefined) method = 'delete'
else [data = {}, Object.keys(el.dataset).forEach(key => key === 'post' || key === 'put' || key === 'patch' ? [method = key, path = el.dataset[key]] : data[key] = el.dataset[key])]
app[method](path, data)
})object
%dialog
/phlo/resources/DOM/dialog.phlo
view
script
line 9
window.alert = app.mod.alert = msg => phlo.dialog('alert', msg)
window.confirm = msg => phlo.dialog('confirm', msg)
window.prompt = (msg, defaultValue) => phlo.dialog('prompt', msg, defaultValue)
app.dlgLabels = {ok: 'OK', cancel: 'Cancel'}
phlo.dialog = async (type, message, defaultValue = '') => new Promise(resolve => {
app.mod.append('body', '<dialog id="phloDialog" class="phlo-dialog" role="dialog" aria-modal="true">\n<form method="dialog">\n<p class="phlo-dialog__message"></p>\n' + (type === 'prompt' ? '<input class="phlo-dialog__input" name="value">' : '') + '\n<menu class="phlo-dialog__actions">\n<button value="1" autofocus>' + app.dlgLabels.ok + '</button>\n' + (type !== 'alert' ? '<button value="0">' + app.dlgLabels.cancel + '</button>' : '') + '\n</menu>\n</form>\n</dialog>')
const dialog = obj('#phloDialog')
const messageEl = dialog.querySelector('.phlo-dialog__message')
messageEl && (messageEl.textContent = String(message ?? ''))
if (type === 'prompt') dialog.querySelector('input').value = String(defaultValue ?? '')
dialog.showModal()
dialog.addEventListener('close', () => {
const value = dialog.returnValue
const input = dialog.querySelector('input')
dialog.remove()
if (type === 'alert') return resolve()
if (type === 'confirm') return resolve(value === '1')
if (type === 'prompt') return resolve(value === '1' ? input.value : null)
})
})
on('click', '[data-confirm]', async (el, e) => {
e.preventDefault()
if (!await window.confirm(el.dataset.confirm)) return
delete el.dataset.confirm
app.update()
el.click()
})object
%exists
/phlo/resources/DOM/exists.phlo
view
script
line 9
此函数跟踪元素及其关联的回调,对于存在但尚未注册的元素执行回调。
phlo.exist = []
phlo.existing = new WeakMap
const onExist = (els, cb) => phlo.exist.push({els, cb})
app.updates.push(() => {
const existing = []
phlo.exist.forEach(item => objects(item.els).forEach(el => phlo.existing.has(el) || existing.push({el, cb: item.cb})))
existing.forEach(item => [phlo.existing.has(item.el) || phlo.existing.set(item.el, 'exist'), item.cb(item.el)])
})object
%ffmpeg
/phlo/resources/DOM/ffmpeg.phlo
view
script
line 12
ffmpeg-wasm in the browser: the singleton ffmpeg, or new Ffmpeg({corePath}). Decoding prefers
class Ffmpeg {
constructor(opts = {}){
this.corePath = opts.corePath || '/ffmpeg/'
this.mp4boxURL = opts.mp4boxURL || '/mp4box.js'
this.muxerURL = opts.muxerURL || '/mp4-muxer.js'
this.log = opts.log || (() => {})
this.ffmpeg = null
this.mode = null
this.scripts = {}
this.demuxKey = null
this.demuxVal = null
}
loadScript(src){
if (this.scripts[src]) return this.scripts[src]
this.scripts[src] = new Promise((resolve, reject) => {
const el = document.createElement('script')
el.src = src
const nonce = document.querySelector('meta[name="nonce"]')
if (nonce) el.nonce = nonce.content
el.onload = () => resolve()
el.onerror = () => {
delete this.scripts[src]
reject(new Error('ffmpeg: failed to load ' + src))
}
document.head.appendChild(el)
})
return this.scripts[src]
}
async frameSource(src, opts = {}){
const from = opts.from || 0
const to = opts.to || 0
const mp4boxURL = opts.mp4boxURL || this.mp4boxURL
const log = opts.log || this.log
const isFile = (typeof File !== 'undefined') && src instanceof File
const seek = () => this.seekSource(isFile ? URL.createObjectURL(src) : src, isFile)
if (!('VideoDecoder' in window)) return seek()
let wc = null
try {
await this.loadScript(mp4boxURL)
const size = await this.sourceSize(src)
const key = isFile ? src.name + ':' + src.size + ':' + src.lastModified : src
let demuxed
if (this.demuxKey === key) demuxed = this.demuxVal
else {
demuxed = await this.demux(src, size)
this.demuxKey = key
this.demuxVal = demuxed
}
const support = await VideoDecoder.isConfigSupported(demuxed.config)
if (!support.supported){
log('[ffmpeg] codec ' + demuxed.config.codec + ' not decodable, using seek')
return seek()
}
log('[ffmpeg] WebCodecs ' + demuxed.config.codec + ', ' + demuxed.samples.length + ' frames, ' + Math.round(size / 1048576) + ' MiB streamed')
const build = async acceleration => {
const config = acceleration ? Object.assign({}, demuxed.config, {hardwareAcceleration: acceleration}) : demuxed.config
const source = this.webCodecsSource(src, size, config, demuxed.samples, from, to)
try {
if (!await source.getFrame(from)) throw new Error('decoder produced no frames')
}
catch (err){
source.close()
throw err
}
return source
}
try {
wc = await build()
}
catch (err){
log('[ffmpeg] hardware decode failed (' + (err && err.message ? err.message : err) + '), retrying software')
wc = await build('prefer-software')
}
return wc
}
catch (err){
if (wc) try { wc.close() } catch (e){}
log('[ffmpeg] WebCodecs unavailable (' + (err && err.message ? err.message : err) + '), using seek')
return seek()
}
}
async sourceSize(src){
if ((typeof File !== 'undefined') && src instanceof File) return src.size
const res = await fetch(src, {method: 'HEAD'})
const length = res.headers.get('content-length')
if (!length) throw new Error('source size unknown')
return parseInt(length, 10)
}
async readRange(src, offset, length){
if ((typeof File !== 'undefined') && src instanceof File) return new Uint8Array(await src.slice(offset, offset + length).arrayBuffer())
const res = await fetch(src, {headers: {Range: 'bytes=' + offset + '-' + (offset + length - 1)}})
if (res.status !== 206) throw new Error('no range support: ' + res.status)
return new Uint8Array(await res.arrayBuffer())
}
async demux(src, size){
const mp4 = MP4Box.createFile()
let info = null
let error = null
mp4.onReady = i => info = i
mp4.onError = e => error = e
const step = 1 << 20
let next = 0
while (!info && !error && next < size){
const bytes = await this.readRange(src, next, Math.min(step, size - next))
if (!bytes.length) break
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
buffer.fileStart = next
const parsed = mp4.appendBuffer(buffer)
if (parsed == null || parsed <= next) break
next = parsed
}
if (error) throw new Error('demux error: ' + error)
const track = info && info.videoTracks && info.videoTracks[0]
if (!track) throw new Error('no video track')
const trak = mp4.getTrackById(track.id)
let description = null
for (const entry of trak.mdia.minf.stbl.stsd.entries){
const box = entry.avcC || entry.hvcC || entry.vpcC || entry.av1C
if (box){
const stream = new DataStream(undefined, 0, DataStream.BIG_ENDIAN)
box.write(stream)
description = new Uint8Array(stream.buffer, 8)
break
}
}
const samples = (trak.samples || []).map(s => ({offset: s.offset, size: s.size, cts: s.cts, duration: s.duration, timescale: s.timescale, key: !!s.is_sync}))
if (!samples.length) throw new Error('demux produced no samples')
return {config: {codec: track.codec, codedWidth: track.video.width, codedHeight: track.video.height, description}, samples}
}
webCodecsSource(src, size, config, samples, startT, endT){
const decoded = []
let error = null
let waiter = null
let target = -Infinity
const signal = () => {
if (!waiter) return
const w = waiter
waiter = null
w()
}
const prune = () => {
let keep = 0
for (let i = 0; i < decoded.length; i++){
if (decoded[i].timestamp <= target + 1000) keep = i
else break
}
for (let i = 0; i < keep; i++) decoded[i].close()
if (keep) decoded.splice(0, keep)
}
const decoder = new VideoDecoder({
output: f => {
decoded.push(f)
prune()
signal()
},
error: e => {
error = e
signal()
},
})
decoder.configure(config)
const seconds = s => s.cts / s.timescale
let fed = 0
let last = samples.length - 1
for (let i = 0; i < samples.length; i++) if (samples[i].key && seconds(samples[i]) <= startT) fed = i
if (endT > startT){
for (let i = samples.length - 1; i >= fed; i--) if (seconds(samples[i]) <= endT){
last = Math.min(samples.length - 1, i + 2)
break
}
}
const blockSize = 8 << 20
const self = this
let block = null
const ensure = async (offset, need) => {
if (block && offset >= block.start && offset + need <= block.end) return
const end = Math.min(size, Math.max(offset + need, offset + blockSize))
block = {start: offset, end, bytes: await self.readRange(src, offset, end - offset)}
}
const nextChunk = async () => {
const s = samples[fed++]
await ensure(s.offset, s.size)
const at = s.offset - block.start
return new EncodedVideoChunk({
type: s.key ? 'key' : 'delta',
timestamp: Math.round(s.cts * 1e6 / s.timescale),
duration: Math.round((s.duration || 0) * 1e6 / s.timescale),
data: block.bytes.subarray(at, at + s.size),
})
}
let flushed = false
const pump = async tMicros => {
target = tMicros
while (!error){
prune()
if (decoded.length && decoded[decoded.length - 1].timestamp > tMicros) return
if (fed <= last){
while (fed <= last && decoder.decodeQueueSize < 4 && decoded.length < 4) decoder.decode(await nextChunk())
await new Promise(r => {
waiter = r
setTimeout(signal, 100)
})
}
else {
if (!flushed){
flushed = true
await decoder.flush().catch(e => error = e)
}
return
}
}
}
return {
mode: 'webcodecs',
async getFrame(t){
const tM = Math.round(t * 1e6)
await Promise.race([pump(tM), new Promise((res, rej) => setTimeout(() => rej(new Error('WebCodecs decode timeout')), 20000))])
if (error) throw error
let idx = 0
for (let i = 0; i < decoded.length; i++){
if (decoded[i].timestamp <= tM + 1000) idx = i
else break
}
for (let i = 0; i < idx; i++) decoded[i].close()
decoded.splice(0, idx)
return decoded[0] || null
},
close(){
block = null
for (const f of decoded) f.close()
decoded.length = 0
try {
decoder.close()
}
catch (e){}
},
}
}
seekTo(rv, time){
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('seek timeout')), 20000)
rv.addEventListener('seeked', function once(){
rv.removeEventListener('seeked', once)
clearTimeout(timer)
resolve()
})
rv.currentTime = time
})
}
async seekSource(srcUrl, revoke){
const rv = document.createElement('video')
rv.muted = true
rv.preload = 'auto'
rv.src = srcUrl
const self = this
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('video load timeout')), 20000)
rv.addEventListener('loadedmetadata', () => {
clearTimeout(timer)
resolve()
}, {once: true})
rv.addEventListener('error', () => {
clearTimeout(timer)
reject(new Error('Could not load video for rendering'))
}, {once: true})
})
return {
mode: 'seek',
async getFrame(t){
await self.seekTo(rv, Math.min(t, (rv.duration || t + 1) - 0.001))
return rv
},
close(){
rv.removeAttribute('src')
rv.load()
if (revoke) URL.revokeObjectURL(srcUrl)
},
}
}
drop(){
if (!this.ffmpeg) return
try {
this.ffmpeg.terminate()
}
catch (e){}
this.ffmpeg = null
}
async load(log){
log = log || this.log
await this.loadScript(this.corePath + 'ffmpeg.js')
const mode = (window.crossOriginIsolated && !window.ffmpegForceST) ? 'mt' : 'st'
if (this.ffmpeg && this.ffmpeg.loaded && this.mode === mode) return this.ffmpeg
this.drop()
log('[ffmpeg] loading core: ' + mode)
this.ffmpeg = new FFmpegWASM.FFmpeg()
this.ffmpeg.on('log', e => log('[ffmpeg] ' + e.message))
this.mode = mode
const base = new URL(this.corePath, location.origin).href
await this.ffmpeg.load(mode === 'mt'
? {coreURL: base + 'ffmpeg-core.js', wasmURL: base + 'ffmpeg-core.wasm', workerURL: base + 'ffmpeg-core.worker.js'}
: {coreURL: base + 'ffmpeg-core-st.js', wasmURL: base + 'ffmpeg-core-st.wasm'})
return this.ffmpeg
}
async exec(args, log){
log = log || this.log
const ff = this.ffmpeg
log('[ffmpeg] $ ffmpeg ' + args.join(' '))
let beat = performance.now()
const bump = () => beat = performance.now()
ff.on('log', bump)
ff.on('progress', bump)
const watchdog = setInterval(() => {
if (performance.now() - beat > 25000) ff.terminate()
}, 4000)
try {
await ff.exec(args)
}
finally {
clearInterval(watchdog)
ff.off('log', bump)
ff.off('progress', bump)
}
}
async withFallback(fn, onProgress, log){
log = log || this.log
try {
return await fn()
}
catch (err){
if (this.mode !== 'mt') throw err
log('[ffmpeg] multithreaded stalled (' + (err && err.message ? err.message : err) + '); retrying single-threaded')
window.ffmpegForceST = true
this.drop()
if (onProgress) onProgress('Multithreaded encoder stalled; retrying single-threaded...', 3)
return fn()
}
}
async run(opts){
const log = opts.log || this.log
return this.withFallback(async () => {
const ff = await this.load(log)
const inName = opts.inputName || 'input'
const outName = opts.output || 'output'
const cleanups = []
if (opts.input != null){
const src = opts.input
const bytes = src instanceof Uint8Array ? src
: (typeof Blob !== 'undefined' && src instanceof Blob ? new Uint8Array(await src.arrayBuffer())
: new Uint8Array(await fetch(src).then(r => r.arrayBuffer())))
await ff.writeFile(inName, bytes)
cleanups.push(() => ff.deleteFile(inName).catch(() => {}))
}
try {
await this.exec(opts.args, log)
const out = await ff.readFile(outName)
cleanups.push(() => ff.deleteFile(outName).catch(() => {}))
return new Blob([out.buffer], {type: opts.type || 'video/mp4'})
}
finally {
for (const c of cleanups) await c()
}
}, opts.onProgress, log)
}
async transcode(input, opts = {}){
const to = opts.to || 'mp4'
const inName = 'tc-in'
const outName = 'tc-out.' + to
const args = ['-i', inName]
if (opts.args) args.push(...opts.args)
else args.push('-c:v', 'libx264', '-preset', 'veryfast', '-crf', String(opts.crf || 20), '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart')
args.push(outName)
return this.run({input, inputName: inName, output: outName, args, type: opts.type || 'video/' + to, log: opts.log, onProgress: opts.onProgress})
}
async encode(opts){
this.demuxKey = null
this.demuxVal = null
const log = opts.log || this.log
if ('VideoEncoder' in window && !window.ffmpegForceEncoder){
try {
return await this.encodeWebCodecs(opts)
}
catch (err){
log('[ffmpeg] hardware encode failed (' + (err && err.message ? err.message : err) + '), retrying software')
try {
return await this.encodeWebCodecs(Object.assign({}, opts, {acceleration: 'prefer-software'}))
}
catch (err2){
log('[ffmpeg] WebCodecs encode failed (' + (err2 && err2.message ? err2.message : err2) + '), using ffmpeg')
}
}
}
return this.withFallback(() => this.pass(opts), opts.onProgress, log)
}
async pickVideoCodec(width, height, fps, bitrate, acceleration){
for (const codec of ['avc1.640028', 'avc1.4d0028', 'avc1.42001f']){
const config = {codec, width, height, bitrate, framerate: fps}
if (acceleration) config.hardwareAcceleration = acceleration
try {
const support = await VideoEncoder.isConfigSupported(config)
if (support.supported) return codec
}
catch (e){}
}
return null
}
async encodeWebCodecs(opts){
const log = opts.log || this.log
const fps = opts.fps
const from = opts.from || 0
const to = opts.to
const onProgress = opts.onProgress || (() => {})
const audio = opts.audio || []
const W = Math.round(opts.width) - (Math.round(opts.width) % 2)
const H = Math.round(opts.height) - (Math.round(opts.height) % 2)
const total = Math.max(1, Math.round((to - from) * fps))
const bitrate = opts.bitrate || Math.round(W * H * fps * 0.15)
await this.loadScript(this.muxerURL)
const codec = await this.pickVideoCodec(W, H, fps, bitrate, opts.acceleration)
if (!codec) throw new Error('no supported h264 encoder configuration')
log('[ffmpeg] WebCodecs encode ' + W + 'x' + H + ' @' + fps + 'fps, ' + total + ' frames, ' + codec + ', ' + Math.round(bitrate / 1000) + ' kbps' + (opts.acceleration ? ', ' + opts.acceleration : ''))
const target = new Mp4Muxer.ArrayBufferTarget()
const muxer = new Mp4Muxer.Muxer({target, video: {codec: 'avc', width: W, height: H}, fastStart: 'in-memory'})
let error = null
const encoder = new VideoEncoder({
output: (chunk, meta) => muxer.addVideoChunk(chunk, meta),
error: e => error = e,
})
const config = {codec, width: W, height: H, bitrate, framerate: fps, avc: {format: 'avc'}}
if (opts.acceleration) config.hardwareAcceleration = opts.acceleration
encoder.configure(config)
const canvas = opts.canvas || document.createElement('canvas')
canvas.width = W
canvas.height = H
const ctx = canvas.getContext('2d', {willReadFrequently: false})
const keyEvery = Math.max(1, Math.round(fps * 2))
let video
if (opts.beforePass) await opts.beforePass()
try {
for (let i = 0; i < total; i++){
if (error) throw error
await opts.drawFrame(ctx, from + i / fps, W, H)
const frame = new VideoFrame(canvas, {timestamp: Math.round(i * 1e6 / fps), duration: Math.round(1e6 / fps)})
encoder.encode(frame, {keyFrame: i % keyEvery === 0})
frame.close()
while (encoder.encodeQueueSize > 8 && !error) await new Promise(r => setTimeout(r, 0))
onProgress('Rendering frame ' + (i + 1) + '/' + total, 5 + 85 * (i + 1) / total)
}
if (error) throw error
await Promise.race([encoder.flush(), new Promise((res, rej) => setTimeout(() => rej(new Error('encoder flush timeout')), 30000))])
if (error) throw error
muxer.finalize()
video = new Blob([target.buffer], {type: 'video/mp4'})
}
finally {
try {
encoder.close()
}
catch (e){}
if (opts.afterPass) await opts.afterPass()
}
log('[ffmpeg] WebCodecs video ' + video.size + ' bytes')
if (!audio.length) return video
return this.muxAudio(video, audio, onProgress, log)
}
async muxAudio(video, audio, onProgress, log){
log = log || this.log
onProgress('Muxing audio...', 92)
const ff = await this.load(log)
await ff.writeFile('wcv.mp4', new Uint8Array(await video.arrayBuffer()))
let prepared
try {
prepared = await this.prepareAudio(ff, audio)
}
catch (err){
log('[ffmpeg] audio unavailable, keeping silent video: ' + (err && err.message ? err.message : err))
await ff.deleteFile('wcv.mp4').catch(() => {})
return video
}
const args = ['-i', 'wcv.mp4'].concat(prepared.args)
const ins = prepared.inputs
if (ins.length === 1 && ins[0].volume === 1 && !ins[0].delay) args.push('-map', '0:v', '-map', '1:a?', '-c', 'copy', '-shortest', 'out.mp4')
else if (ins.length === 1 && !ins[0].delay) args.push('-map', '0:v', '-map', '1:a?', '-c:v', 'copy', '-filter:a', 'volume=' + ins[0].volume, '-c:a', 'aac', '-b:a', '192k', '-shortest', 'out.mp4')
else {
const parts = ins.map((a, i) => '[' + (i + 1) + ':a]' + (a.delay ? 'adelay=' + Math.round(a.delay) + ':all=1,' : '') + 'volume=' + a.volume + '[a' + i + ']')
const mix = ins.map((a, i) => '[a' + i + ']').join('') + 'amix=inputs=' + ins.length + ':duration=longest:normalize=0[aout]'
args.push('-filter_complex', parts.join(';') + ';' + mix, '-map', '0:v', '-map', '[aout]', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', 'out.mp4')
}
try {
await this.exec(args, log)
onProgress('Reading result...', 98)
const out = await ff.readFile('out.mp4')
return new Blob([out.buffer], {type: 'video/mp4'})
}
catch (err){
log('[ffmpeg] audio mux failed, keeping silent video: ' + (err && err.message ? err.message : err))
video.silent = true
return video
}
finally {
await ff.deleteFile('wcv.mp4').catch(() => {})
await ff.deleteFile('out.mp4').catch(() => {})
await prepared.cleanup()
}
}
async prepareAudio(ff, audio){
const args = []
const inputs = []
const cleanups = []
let mountIdx = 0
for (const a of audio){
if (!a) continue
let path
if (a.file){
const dir = '/ffaud' + (mountIdx++)
await ff.createDir(dir).catch(() => {})
await ff.mount(FFmpegWASM.FFFSType.WORKERFS, {files: [a.file]}, dir)
path = dir + '/' + a.file.name
cleanups.push(() => ff.unmount(dir).catch(() => {}))
}
else {
const ext = String(a.name || a.url || 'a.mp4').split('?')[0].split('.').pop() || 'mp4'
const name = a.name || ('ffaud' + inputs.length + '.' + ext)
const bytes = a.bytes ? a.bytes : new Uint8Array(await fetch(a.url).then(r => r.arrayBuffer()))
await ff.writeFile(name, bytes)
path = name
cleanups.push(() => ff.deleteFile(name).catch(() => {}))
}
if (a.seek) args.push('-ss', String(a.seek))
args.push('-i', path)
inputs.push({volume: a.volume == null ? 1 : a.volume, delay: a.delay || 0})
}
return {args, inputs, cleanup: async () => { for (const c of cleanups) await c() }}
}
async pass(opts){
const log = opts.log || this.log
const fps = opts.fps
const from = opts.from || 0
const to = opts.to
const drawFrame = opts.drawFrame
const audio = opts.audio || []
const onProgress = opts.onProgress || (() => {})
const quality = opts.quality || 0.9
const crf = opts.crf || 20
const segmentFrames = opts.segmentFrames || 120
const W = Math.round(opts.width) - (Math.round(opts.width) % 2)
const H = Math.round(opts.height) - (Math.round(opts.height) % 2)
const ff = await this.load(log)
const canvas = opts.canvas || document.createElement('canvas')
canvas.width = W
canvas.height = H
const ctx = canvas.getContext('2d', {willReadFrequently: false})
const total = Math.max(1, Math.round((to - from) * fps))
log('[ffmpeg] encode ' + W + 'x' + H + ' @' + fps + 'fps, ' + total + ' frames, ' + from.toFixed(2) + '-' + to.toFixed(2) + 's, mode=' + this.mode)
if (opts.beforePass) await opts.beforePass()
const segments = []
try {
let frame = 0
let segIdx = 0
while (frame < total){
const count = Math.min(segmentFrames, total - frame)
for (let i = 0; i < count; i++){
const t = from + (frame + i) / fps
await drawFrame(ctx, t, W, H)
const blob = await new Promise(res => canvas.toBlob(res, 'image/jpeg', quality))
await ff.writeFile('f' + String(i).padStart(6, '0') + '.jpg', new Uint8Array(await blob.arrayBuffer()))
onProgress('Rendering frame ' + (frame + i + 1) + '/' + total, 5 + 75 * (frame + i + 1) / total)
}
const segName = 'seg' + segIdx + '.mp4'
onProgress('Encoding segment ' + (segIdx + 1) + '...', 5 + 75 * (frame + count) / total)
await this.exec(['-threads', '4', '-framerate', String(fps), '-i', 'f%06d.jpg', '-frames:v', String(count), '-c:v', 'libx264', '-preset', 'veryfast', '-crf', String(crf), '-pix_fmt', 'yuv420p', segName], log)
for (let i = 0; i < count; i++) await ff.deleteFile('f' + String(i).padStart(6, '0') + '.jpg').catch(() => {})
segments.push(segName)
frame += count
segIdx++
}
}
finally {
if (opts.afterPass) await opts.afterPass()
}
onProgress('Muxing audio...', 85)
await ff.writeFile('list.txt', new TextEncoder().encode(segments.map(s => "file '" + s + "'").join('\n') + '\n'))
const args = ['-f', 'concat', '-safe', '0', '-i', 'list.txt']
let prepared = {args: [], inputs: [], cleanup: async () => {}}
if (audio.length){
try {
prepared = await this.prepareAudio(ff, audio)
}
catch (err){
log('[ffmpeg] audio unavailable, rendering silent: ' + (err && err.message ? err.message : err))
}
}
args.push(...prepared.args)
const ins = prepared.inputs
if (!ins.length) args.push('-map', '0:v', '-an', '-c:v', 'copy', 'out.mp4')
else if (ins.length === 1 && !ins[0].delay){
args.push('-map', '0:v', '-map', '1:a?', '-c:v', 'copy')
if (ins[0].volume !== 1) args.push('-filter:a', 'volume=' + ins[0].volume)
args.push('-c:a', 'aac', '-b:a', '192k', '-shortest', 'out.mp4')
}
else {
const parts = ins.map((a, i) => '[' + (i + 1) + ':a]' + (a.delay ? 'adelay=' + Math.round(a.delay) + ':all=1,' : '') + 'volume=' + a.volume + '[a' + i + ']')
const mix = ins.map((a, i) => '[a' + i + ']').join('') + 'amix=inputs=' + ins.length + ':duration=longest:normalize=0[aout]'
args.push('-filter_complex', parts.join(';') + ';' + mix, '-map', '0:v', '-map', '[aout]', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', 'out.mp4')
}
await this.exec(args, log)
onProgress('Reading result...', 96)
const out = await ff.readFile('out.mp4')
log('[ffmpeg] output ' + out.length + ' bytes (' + segments.length + ' segments)')
for (const s of segments) await ff.deleteFile(s).catch(() => {})
await ff.deleteFile('list.txt').catch(() => {})
await ff.deleteFile('out.mp4').catch(() => {})
await prepared.cleanup()
return new Blob([out.buffer], {type: 'video/mp4'})
}
}
const ffmpeg = new Ffmpeg()object
%form
/phlo/resources/DOM/form.phlo
view
script
line 9
on('input change', 'input, select, textarea', input => {
if (input.tagName === 'SELECT') input.querySelectorAll('option').forEach((option, index) => option.selected ? option.setAttribute('selected', '') : option.removeAttribute('selected'))
if (input.type === 'checkbox') input.checked ? input.setAttribute('checked', '') : input.removeAttribute('checked')
if (input.type === 'text' && input.value !== input.getAttribute('value')) input.setAttribute('value', input.value)
if (input.type === 'textarea' && input.value !== input.innerHTML) input.innerHTML = input.value
delay('state', 333, () => phlo.state.replace())
return false
})
on('submit', 'form.async', (form, e) => {
e.preventDefault()
const method = (form.attributes.method?.value ?? 'GET').toLowerCase()
const url = new URL(form.attributes.action?.value || location.href, document.baseURI)
const data = new FormData(form)
if (method === 'get'){
const query = new URLSearchParams
for (const [name, value] of data) query.append(name, typeof value === 'string' ? value : value.name)
url.search = query.toString()
return app.navigate(url.pathname.substr(1) + url.search)
}
return app[method](url.pathname.substr(1) + url.search, data)
})object
%image_resizer
/phlo/resources/DOM/image.resizer.phlo
view
script
line 8
将图像文件调整为指定的最大尺寸,同时保持纵横比,并通过回调函数返回调整后的图像作为数据URL。
const imageResizer = (file, maxWidth, maxHeight, cb, quality = .8) => {
const img = new Image
img.onload = () => {
let width = img.width, height = img.height
const aspectRatio = width / height
if (width > maxWidth || height > maxHeight){
if (width > height){
width = maxWidth
height = Math.round(maxWidth / aspectRatio)
}
else {
height = maxHeight
width = Math.round(maxHeight * aspectRatio)
}
}
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
canvas.getContext('2d').drawImage(img, 0, 0, width, height)
cb(canvas.toDataURL(file.type, quality))
}
img.src = URL.createObjectURL(file)
}object
%keyboard
/phlo/resources/DOM/keyboard.phlo
view
script
line 14
Every event is delegated from the body.
phlo.keyboard = {
layouts: {
qwerty: ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'],
azerty: ['azertyuiop', 'qsdfghjklm', 'wxcvbn'],
qwertz: ['qwertzuiop', 'asdfghjkl', 'yxcvbnm'],
},
digits: '1234567890',
shifted: {',': ';', '.': ':', '-': '_', "'": '"'},
labels: {shift: '↑', back: '←', space: ' ', enter: '↵', close: '×'},
open: null,
caps: false,
layout: el => phlo.keyboard.layouts[el?.dataset.keyboard] ? el.dataset.keyboard : (el?.closest('[data-keyboard-layout]')?.dataset.keyboardLayout || 'qwerty'),
key: (value, label, cls) => `<button class="keyboard__key${cls ? ' ' + cls : ''}" type="button" data-keyboard-key="${value}">${label ?? value}</button>`,
rows(name){
const layout = phlo.keyboard.layouts[name] || phlo.keyboard.layouts.qwerty
const cast = char => phlo.keyboard.caps ? (phlo.keyboard.shifted[char] ?? char.toUpperCase()) : char
const key = phlo.keyboard.key
let html = '<div class="keyboard__row">' + [...phlo.keyboard.digits].map(char => key(char)).join('') + key('back', phlo.keyboard.labels.back, 'keyboard__key--wide') + '</div>'
layout.forEach((row, index) => {
html += '<div class="keyboard__row">'
if (index === 2) html += key('shift', phlo.keyboard.labels.shift, 'keyboard__key--wide' + (phlo.keyboard.caps ? ' keyboard__key--on' : ''))
html += [...row].map(char => key(cast(char))).join('')
if (index === 2) html += key('enter', phlo.keyboard.labels.enter, 'keyboard__key--wide')
html += '</div>'
})
html += '<div class="keyboard__row">' + [key('-'), key(cast("'")), key(' ', phlo.keyboard.labels.space, 'keyboard__key--space'), key(cast(',')), key(cast('.')), key('close', phlo.keyboard.labels.close, 'keyboard__key--close')].join('') + '</div>'
return html
},
host(target){
const root = target?.closest('dialog[open]') || document.body
return obj('[data-keyboard-dock]', root) || root
},
render(){
const target = phlo.keyboard.open
if (!target) return
const host = phlo.keyboard.host(target)
const docked = host !== document.body && host.matches('[data-keyboard-dock]')
if (obj('#keyboard')?.parentElement !== host) obj('#keyboard')?.remove()
obj('#keyboard') || app.mod.append(host, '<div id="keyboard" class="keyboard' + (docked ? ' keyboard--docked' : '') + '" role="group" aria-label="On-screen keyboard"></div>')
app.mod.inner('#keyboard', phlo.keyboard.rows(phlo.keyboard.layout(target)))
},
show(target){
phlo.keyboard.open = target
phlo.keyboard.caps = false
phlo.keyboard.render()
},
hide(){
phlo.keyboard.open = null
obj('#keyboard')?.remove()
},
write(target, insert, back = false){
const start = target.selectionStart ?? target.value.length
const end = target.selectionEnd ?? start
const from = back && start === end ? Math.max(0, start - 1) : start
target.value = target.value.slice(0, from) + insert + target.value.slice(end)
const caret = from + insert.length
target.setSelectionRange?.(caret, caret)
target.dispatchEvent(new Event('input', {bubbles: true}))
},
press(name){
const target = phlo.keyboard.open
if (!target) return
if (!target.isConnected) return phlo.keyboard.hide()
if (name === 'close') return phlo.keyboard.hide()
if (name === 'shift'){
phlo.keyboard.caps = !phlo.keyboard.caps
return phlo.keyboard.render()
}
if (name === 'back') return phlo.keyboard.write(target, '', true)
if (name === 'enter'){
const form = target.closest('form')
phlo.keyboard.hide()
target.dispatchEvent(new Event('change', {bubbles: true}))
return form?.requestSubmit()
}
phlo.keyboard.write(target, name)
if (phlo.keyboard.caps){
phlo.keyboard.caps = false
phlo.keyboard.render()
}
},
}
app.keyboard = {
show: selector => phlo.keyboard.show(obj(selector)),
hide: () => phlo.keyboard.hide(),
}
on('focusin', 'body', (body, e) => {
if (!e.target.matches?.('[data-keyboard]')) return
if (phlo.keyboard.open === e.target) return
phlo.keyboard.show(e.target)
})
on('click', 'body', (body, e) => {
const el = e.target.closest?.('[data-keyboard-key]')
if (!el) return
e.preventDefault()
phlo.keyboard.press(el.dataset.keyboardKey)
phlo.keyboard.open?.focus({preventScroll: true})
})
on('click', 'body', (el, e) => {
if (!phlo.keyboard.open) return
if (!phlo.keyboard.open.isConnected) return phlo.keyboard.hide()
if (e.target.closest('#keyboard') || e.target === phlo.keyboard.open) return
const surface = phlo.keyboard.open.closest('dialog[open]')
if (surface && surface.contains(e.target)) return
phlo.keyboard.hide()
})
on('keydown', 'body', (el, e) => {
if (e.key === 'Escape') phlo.keyboard.hide()
})
on('close', 'dialog', dialog => {
if (phlo.keyboard.open && dialog.contains(phlo.keyboard.open)) phlo.keyboard.hide()
})view
style
line 135
.keyboard {
position: fixed
left: 0
right: 0
bottom: 0
z-index: 1000
display: grid
gap: var(--keyboard-gap, .3rem)
padding: var(--keyboard-pad, .5rem)
background: var(--keyboard-bg, #1c2029)
color: var(--keyboard-color, #f2f2f2)
box-shadow: 0 -2px 12px #0006
touch-action: manipulation
user-select: none
}
.keyboard--docked {
position: static
box-shadow: none
padding: var(--keyboard-dock-pad, 0)
background: var(--keyboard-dock-bg, transparent)
}
.keyboard__row {
display: flex
gap: var(--keyboard-gap, .3rem)
justify-content: center
}
.keyboard__key {
font: inherit
font-size: var(--keyboard-size, 1.1rem)
flex: 1 1 auto
max-width: var(--keyboard-key, 4rem)
padding: var(--keyboard-key-pad, .7rem .2rem)
border: 1px solid var(--keyboard-border, #ffffff26)
border-radius: var(--keyboard-radius, 6px)
background: var(--keyboard-key-bg, #ffffff14)
color: inherit
cursor: pointer
\:active: background: var(--keyboard-key-active, #ffffff2e)
}
.keyboard__key--wide {
max-width: var(--keyboard-wide, 6rem)
}
.keyboard__key--space {
max-width: var(--keyboard-space, 18rem)
}
.keyboard__key--on {
background: var(--keyboard-key-on, #ffffff33)
}object
%link
/phlo/resources/DOM/link.phlo
view
script
line 9
on('click', 'a', (a, e) => {
if (e.ctrlKey || e.shiftKey || e.metaKey || a.target || a.dataset.confirm) return false
const isAsync = a.classList.contains('async')
const [uri, hash] = (a.attributes.href?.value ?? '').split('#')
if (isAsync || hash) e.preventDefault()
phlo.anchor = hash ? `#${hash}` : ''
if (hash && (!uri || uri === location.pathname + location.search)) location.hash = phlo.anchor
else if (isAsync) app.navigate(uri.substr(1))
})object
%markdown
/phlo/resources/DOM/markdown.phlo
view
script
line 8
将Markdown文本解析为HTML,支持多种功能,如GitHub风格的Markdown、块元素、内联元素和引用链接。
function parse_markdown(md, opts = {}){
const o = {
gfm: opts.gfm !== false,
breaks: !!opts.breaks,
headerIds: opts.headerIds !== false,
headerPrefix: opts.headerPrefix || '',
smartypants: !!opts.smartypants
}
const unnull = x => (x == null ? '' : String(x))
let src = unnull(md).replace(/\r\n?/g, "\n")
const escHtml = s => s.replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c]))
const trimEndNL = s => s.replace(/\s+$/,'')
const isBlank = s => /^\s*$/.test(s)
const slugmap = new Map()
const slug = t => {
let s = t.toLowerCase().replace(/<\/?[^>]+>/g, '').replace(/[^\p{L}\p{N}\- _]+/gu, '').trim().replace(/[\s_]+/g, '-')
const base = o.headerPrefix + s
let k = base, i = 1
while (slugmap.has(k)) k = `${base}-${++i}`
slugmap.set(k, true)
return k
}
const smart = s => {
if (!o.smartypants) return s
return s.replace(/---/g, "-").replace(/--/g, "–").replace(/(^|[\s"(\[])(?=')/g, "$1‘").replace(/'/g, "’").replace(/(^|[\s(\[])(?=")/g, "$1“").replace(/"/g, "”").replace(/\.{3}/g, "…")
}
const refs = Object.create(null)
src = src.replace(
/^ {0,3}\[([^\]]+)\]:\s*<?([^\s>]+)>?(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]+)\)))?\s*$/gm,
(_, label, url, t1, t2, t3) => {
const key = label.trim().replace(/\s+/g, ' ').toLowerCase()
if (!refs[key]) refs[key] = { href: url, title: t1 || t2 || t3 || '' }
return ''
}
)
const tokens = []
const lines = src.split("\n")
function takeWhile(start, pred){
let end = start
while (end < lines.length && pred(lines[end], end)) end++
return { start, end }
}
function pushParagraph(buf){
const text = buf.join("\n").trimEnd()
if (text) tokens.push({ type: "paragraph", text })
buf.length = 0
}
function parseBlock(start = 0, end = lines.length){
const para = []
let l = start
while (l < end){
const line = lines[l]
if (isBlank(line)){
pushParagraph(para)
l++
continue
}
let m = line.match(/^ {0,3}(`{3,}|~{3,})([^\n]*)$/)
if (m){
pushParagraph(para)
const fenceLen = m[1].length
const info = (m[2] || '').trim()
let body = []
l++
while (l < end){
const s = lines[l]
const close = s.match(new RegExp(`^ {0,3}${m[1][0]}{${fenceLen},}\\s*$`))
if (close){
l++
break
}
body.push(s)
l++
}
tokens.push({ type: "code", lang: info.split(/\s+/)[0] || '', text: trimEndNL(body.join("\n")) })
continue
}
if (/^(?: {4}|\t)/.test(line)){
pushParagraph(para)
const { end: j } = takeWhile(l, s => /^(?: {4}|\t)/.test(s) || isBlank(s))
const block = lines.slice(l, j).map(s => s.replace(/^(?: {4}|\t)/, '')).join("\n")
tokens.push({ type: "code", lang: '', text: trimEndNL(block) })
l = j
continue
}
if (/^ {0,3}<(?:!--|\/?(?:html|head|body|pre|script|style|table|thead|tbody|tfoot|tr|td|th|div|p|h[1-6]|blockquote|ul|ol|li|section|article|aside|details|summary|figure|figcaption)\b)/i.test(line)){
pushParagraph(para)
const { end: j } = takeWhile(l, (s, idx) => !(idx > l && isBlank(lines[idx-1]) && isBlank(s)))
const html = lines.slice(l, j).join("\n")
tokens.push({ type: "html", text: html })
l = j
continue
}
if (/^ {0,3}(?:-+\s*|-{3,}|_{3,}|\*{3,})\s*$/.test(line)){
pushParagraph(para)
tokens.push({ type: "hr" })
l++
continue
}
m = line.match(/^ {0,3}(#{1,6})[ \t]*([^#\n]*?)[ \t#]*$/)
if (m){
pushParagraph(para)
tokens.push({ type: "heading", depth: m[1].length, text: m[2].trim() })
l++
continue
}
if (l + 1 < end && /^[^\s].*$/.test(line) && /^ {0,3}(=+|-+)\s*$/.test(lines[l + 1])){
pushParagraph(para)
const depth = lines[l + 1].trim().startsWith("=") ? 1 : 2
tokens.push({ type: "heading", depth, text: line.trim() })
l += 2
continue
}
if (/^ {0,3}>\s?/.test(line)){
pushParagraph(para)
const { end: j } = takeWhile(l, s => /^ {0,3}>\s?/.test(s) || isBlank(s))
const inner = lines.slice(l, j).map(s => s.replace(/^ {0,3}>\s?/, '')).join("\n")
const sub = parse_markdown(inner, { ...o })
tokens.push({ type: "blockquote", html: sub })
l = j
continue
}
m = line.match(/^ {0,3}((?:[*+-])|\d{1,9}[.)])\s+/)
if (m){
pushParagraph(para)
const bulletRe = /^ {0,3}((?:[*+-])|\d{1,9}[.)])\s+/
const { end: j } = takeWhile(l, (s, idx) =>
bulletRe.test(s) ||
(/^(?: {4}|\t)/.test(s)) ||
(!isBlank(s) && idx > l && !/^(?: {0,3}(?:[*+-]|\d{1,9}[.)])\s+)/.test(s))
)
const block = lines.slice(l, j)
const ordered = /^\d/.test(m[1])
const items = []
let cur = []
for (let k = 0; k < block.length; k++){
const ln = block[k]
const head = ln.match(bulletRe)
if (head){
if (cur.length) items.push(cur), cur = []
cur.push(ln.replace(bulletRe, ''))
} else {
cur.push(ln.replace(/^(?: {4}|\t)/, ''))
}
}
if (cur.length) items.push(cur)
const parsedItems = items.map(linesArr => {
let raw = linesArr.join("\n").replace(/\n\s+$/,'')
let checked = null
if (o.gfm){
const t = raw.match(/^\[([ xX])\][ \t]+/)
if (t){
checked = t[1].toLowerCase() === 'x'
raw = raw.replace(/^\[[ xX]\][ \t]+/, '')
}
}
const html = parse_markdown(raw, o)
return { html, checked }
})
tokens.push({ type: "list", ordered, items: parsedItems })
l = j
continue
}
if (o.gfm){
const hdr = line
const alignLn = lines[l + 1] || ''
if (/\|/.test(hdr) && /^ {0,3}\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/.test(alignLn)){
pushParagraph(para)
const aligns = alignLn
.trim().replace(/^(\|)|(\|)$/g,'')
.split("|").map(s => s.trim()).map(s => s.startsWith(":-") && s.endsWith("-:") ? "center" : s.endsWith("-:") ? "right" : s.startsWith(":-") ? "left" : null)
const headerCells = hdr.trim().replace(/^(\|)|(\|)$/g,'').split("|").map(s => s.trim())
l += 2
const rows = []
while (l < end && /\|/.test(lines[l]) && !isBlank(lines[l])){
rows.push(lines[l].trim().replace(/^(\|)|(\|)$/g,'').split("|").map(s => s.trim()))
l++
}
tokens.push({ type: "table", header: headerCells, aligns, rows })
continue
}
}
para.push(line)
const next = lines[l + 1] || ''
const endPara =
isBlank(next) ||
/^ {0,3}(?:`{3,}|~{3,})/.test(next) ||
/^(?: {4}|\t)/.test(next) ||
/^ {0,3}((?:[*+-])|\d{1,9}[.)])\s+/.test(next) ||
/^ {0,3}(#{1,6})/.test(next) ||
/^ {0,3}>\s?/.test(next) ||
/^ {0,3}(?:-+\s*|-{3,}|_{3,}|\*{3,})\s*$/.test(next) ||
(o.gfm && /\|/.test(next) && /^ {0,3}\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/.test(lines[l + 2] || ''))
if (endPara) pushParagraph(para)
l++
}
pushParagraph(para)
}
parseBlock(0, lines.length)
function renderInline(s){
if (!s) return ''
s = s.replace(/(`+)([^`]|[^`][\s\S]*?[^`])\1/g, (_, ticks, code) => `<code>${escHtml(code)}</code>`)
s = s.replace(/!\[([^\]]*)\]\(\s*<?([^\s)<>]+)>?\s*(?:(?:"([^"]*)"|'([^']*)'|\(([^)]+)\)))?\s*\)/g,
(_, alt, url, t1, t2, t3) => `<img src="${escHtml(url)}" alt="${escHtml(alt)}"${t1||t2||t3?` title="${escHtml(t1||t2||t3)}"`:''}>`)
s = s.replace(/!\[([^\]]*)\]\[([^\]]*)\]/g, (_, alt, id) => {
const ref = refs[(id || alt).trim().replace(/\s+/g,' ').toLowerCase()]
return ref ? `<img src="${escHtml(ref.href)}" alt="${escHtml(alt)}"${ref.title?` title="${escHtml(ref.title)}"`:''}>` : _
})
s = s.replace(/\[([^\]]+)\]\(\s*<?([^\s)<>]+)>?\s*(?:(?:"([^"]*)"|'([^']*)'|\(([^)]+)\)))?\s*\)/g,
(_, text, url, t1, t2, t3) => `<a href="${escHtml(url)}"${t1||t2||t3?` title="${escHtml(t1||t2||t3)}"`:''}>${text}</a>`)
s = s.replace(/\[([^\]]+)\]\s*\[([^\]]*)\]/g, (_, text, id) => {
const key = (id || text).trim().replace(/\s+/g,' ').toLowerCase()
const ref = refs[key]
return ref ? `<a href="${escHtml(ref.href)}"${ref.title?` title="${escHtml(ref.title)}"`:''}>${text}</a>` : _
})
s = s.replace(/<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^ <>"']+)>/g, (_, url) => `<a href="${escHtml(url)}">${escHtml(url)}</a>`)
s = s.replace(/<([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})>/g, (_, mail) => `<a href="mailto:${escHtml(mail)}">${escHtml(mail)}</a>`)
if (o.gfm){
s = s.replace(/(?:(?<=\s)|^)(https?:\/\/[^\s<]+)(?=\s|$)/g, '<a href="$1">$1</a>')
s = s.replace(/(?:(?<=\s)|^)(www\.[^\s<]+)(?=\s|$)/g, '<a href="http://$1">$1</a>')
}
s = s.replace(/\*\*([\s\S]+?)\*\*/g, '<strong>$1</strong>').replace(/__([\s\S]+?)__/g, '<strong>$1</strong>')
s = s.replace(/\*([^*\n]+?)\*/g, '<em>$1</em>').replace(/_([^_\n]+?)_/g, '<em>$1</em>')
if (o.gfm) s = s.replace(/~~([\s\S]+?)~~/g, '<del>$1</del>')
s = s.replace(/ {2,}\n/g, "<br>\n")
if (o.breaks) s = s.replace(/\n/g, "<br>\n")
s = s.replace(/&(?!#?\w+;)/g, "&").replace(/<(?!\/?[A-Za-z][^>]*>)/g, "<")
return smart(s)
}
let out = ''
for (const t of tokens){
switch (t.type){
case "paragraph":
out += `<p>${renderInline(t.text)}</p>\n`
break
case "heading": {
const text = renderInline(t.text)
const id = o.headerIds ? slug(text.replace(/<[^>]+>/g, '')) : null
out += id ? `<h${t.depth} id="${id}">${text}</h${t.depth}>\n` : `<h${t.depth}>${text}</h${t.depth}>\n`
break
}
case "code": {
const cls = t.lang ? ` class="language-${escHtml(t.lang)}"` : ''
out += `<pre><code${cls}>${escHtml(t.text)}</code></pre>\n`
break
}
case "blockquote":
out += `<blockquote>\n${t.html.trim()}\n</blockquote>\n`
break
case "list": {
const tag = t.ordered ? "ol" : "ul"
out += `<${tag}>\n`
for (const it of t.items){
const task = it.checked === null ? '' : `<input ${it.checked ? 'checked="" ' : ''}disabled="" type="checkbox"> `
const body = it.html.trim().replace(/^<p>/, task + "<p>")
out += `<li>${body}</li>\n`
}
out += `</${tag}>\n`
break
}
case "table": {
const ths = t.header.map((h, i) => {
const a = t.aligns[i]
return a ? `<th align="${a}">${renderInline(h)}</th>` : `<th>${renderInline(h)}</th>`
}).join("\n")
let body = ''
for (const row of t.rows){
const tds = row.map((cell, i) => {
const a = t.aligns[i]
return a ? `<td align="${a}">${renderInline(cell)}</td>` : `<td>${renderInline(cell)}</td>`
}).join("\n")
body += `<tr>\n${tds}\n</tr>\n`
}
out += `<table>\n<thead>\n<tr>\n${ths}\n</tr>\n</thead>\n` + (body ? `<tbody>\n${body}</tbody>\n` : '') + `</table>\n`
break
}
case "hr":
out += "<hr>\n"
break
case "html":
out += t.text + "\n"
break
}
}
return out.trim()
}object
%numpad
/phlo/resources/DOM/numpad.phlo
view
script
line 12
Keys and focus are handled on the body, since a pad or a field can appear after the binding
phlo.numpad = {
layouts: {
calculator: ['7', '8', '9', '4', '5', '6', '1', '2', '3'],
phone: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
},
labels: {back: '←', clear: 'C', enter: '↵'},
options: el => ({
layout: el.dataset.numpadLayout || 'calculator',
decimal: el.dataset.numpadDecimal ?? ',',
extra: el.dataset.numpadExtra ?? '',
keys: (el.dataset.numpadKeys ?? 'back,clear').split(',').map(key => key.trim()).filter(Boolean),
fresh: el.dataset.numpadFresh !== undefined,
max: parseInt(el.dataset.numpadMax) || 0,
}),
target: el => obj(el.dataset.numpad) || el.closest('form')?.querySelector('input, textarea') || null,
keys(options){
const key = (value, label, cls) => `<button class="numpad__key${cls ? ' ' + cls : ''}" type="button" data-numpad-key="${value}">${label ?? value}</button>`
let html = (phlo.numpad.layouts[options.layout] || phlo.numpad.layouts.calculator).map(value => key(value)).join('')
html += options.extra ? key(options.extra) : ''
html += key('0')
html += options.decimal ? key(options.decimal) : ''
options.keys.forEach(name => html += key(name, phlo.numpad.labels[name] ?? name, 'numpad__key--' + name))
return html
},
build(el){
if (el.dataset.numpadReady) return
el.dataset.numpadReady = '1'
el.classList.add('numpad')
if (!el.querySelector('[data-numpad-key]')) app.mod.inner(el, phlo.numpad.keys(phlo.numpad.options(el)))
},
write(target, value){
target.value = value
target.dispatchEvent(new Event('input', {bubbles: true}))
},
press(target, name, options){
if (!target) return
if (name === 'clear') return phlo.numpad.write(target, '')
if (name === 'back') return phlo.numpad.write(target, target.value.slice(0, -1))
if (name === 'enter'){
const form = target.closest('form')
target.dispatchEvent(new Event('change', {bubbles: true}))
return form?.requestSubmit()
}
let value = target.value
if (options.fresh && !target.dataset.numpadTyped){
value = ''
target.dataset.numpadTyped = '1'
}
if (options.decimal && name === options.decimal && value.includes(options.decimal)) return
if (options.max && (value + name).length > options.max) return
phlo.numpad.write(target, value + name)
},
}
app.numpad = (selector, options = {}) => `<div class="numpad" data-numpad="${selector}"${Object.entries(options).map(([key, value]) => ` data-numpad-${key.toLowerCase()}="${value}"`).join('')}></div>`
onExist('[data-numpad]', el => phlo.numpad.build(el))
on('click', 'body', (body, e) => {
const el = e.target.closest?.('[data-numpad-key]')
const pad = el?.closest('[data-numpad]')
if (!pad) return
const target = phlo.numpad.target(pad)
phlo.numpad.press(target, el.dataset.numpadKey, phlo.numpad.options(pad))
target?.focus({preventScroll: true})
})
on('focusin', 'body', (body, e) => {
if (e.relatedTarget?.closest?.('[data-numpad-key]')) return
if (e.target.dataset?.numpadTyped) delete e.target.dataset.numpadTyped
})view
style
line 86
.numpad {
display: grid
grid-template-columns: repeat(3, 1fr)
gap: var(--numpad-gap, .4rem)
}
.numpad__key {
font: inherit
font-size: var(--numpad-size, 1.2rem)
padding: var(--numpad-pad, .7rem)
border: 1px solid var(--numpad-border, #0002)
border-radius: var(--numpad-radius, 8px)
background: var(--numpad-bg, #0000000a)
color: inherit
cursor: pointer
touch-action: manipulation
user-select: none
\:active: background: var(--numpad-bg-active, #00000018)
}
.numpad__key--enter {
grid-column: span 3
}object
%shorthands
/phlo/resources/DOM/shorthands.phlo
view
script
line 9
定义了常见事件监听器的简写函数:onChange、onClick 和 onInput,简化了将事件处理程序附加到元素的过程。
function onChange(els, cb){ on('change', els, cb) }
function onClick(els, cb){ on('click', els, cb) }
function onInput(els, cb){ on('input', els, cb) }object
%store
/phlo/resources/DOM/store.phlo
view
script
line 9
phlo.store = {
signals: {},
listeners: {},
calcs: {},
calcDeps: {},
calcVals: {},
calcTick: false,
formats: {},
persists: {},
syncs: {},
quiet: 0,
scope: 'page',
split: path => path.replace(/\]/g, '').split(/\.|\[/),
get(path){
if (!path) return undefined
let ctx = phlo.store.signals
const keys = phlo.store.split(path)
for (let i = 0; i < keys.length; i++){
if (ctx == null) return undefined
ctx = ctx[keys[i]]
}
return ctx
},
setPath(path, value){
let keys = phlo.store.split(path)
let ctx = phlo.store.signals
while (keys.length > 1){
const k = keys.shift()
ctx[k] ??= isNaN(keys[0]) ? {} : []
ctx = ctx[k]
}
const k = keys[0]
const old = ctx[k]
if (old === value) return false
ctx[k] = value
return true
},
set(path, value){
if (!phlo.store.setPath(path, value)) return
phlo.store.notify(path, phlo.store.get(path))
phlo.store.recalc(path)
phlo.store.schedule()
phlo.store.save(path)
if (!phlo.store.quiet) phlo.store.push(path)
},
on(path, cb, el = null){
(phlo.store.listeners[path] ??= new Set).add(cb)
if (el) phlo.store.owners.set(cb, el)
},
off(path, cb){
phlo.store.listeners[path]?.delete(cb)
phlo.store.owners.delete(cb)
},
owners: new WeakMap,
sweep(){
Object.keys(phlo.store.listeners).forEach(path => {
phlo.store.listeners[path].forEach(cb => {
const el = phlo.store.owners.get(cb)
if (el && !el.isConnected) phlo.store.off(path, cb)
})
if (!phlo.store.listeners[path].size) delete phlo.store.listeners[path]
})
},
reset(prefix = ''){
if (!prefix){
phlo.store.signals = {}
phlo.store.listeners = {}
phlo.store.calcs = {}
phlo.store.calcDeps = {}
phlo.store.calcVals = {}
phlo.store.calcTick = false
return
}
const keys = phlo.store.split(prefix)
let ctx = phlo.store.signals
for (let i = 0; i < keys.length - 1; i++) ctx = ctx?.[keys[i]]
if (ctx) delete ctx[keys[keys.length - 1]]
phlo.store.notify(prefix, undefined)
Object.keys(phlo.store.listeners).forEach(path => phlo.store.match(prefix, path) && delete phlo.store.listeners[path])
},
replace(path, value){
const keys = phlo.store.split(path)
let ctx = phlo.store.signals
for (let i = 0; i < keys.length - 1; i++) ctx = ctx?.[keys[i]]
if (ctx) delete ctx[keys[keys.length - 1]]
phlo.store.set(path, value)
},
signal(path, initial){
if (phlo.store.get(path) === undefined) phlo.store.set(path, initial)
return { subscribe: cb => phlo.store.on(path, cb), unsubscribe: cb => phlo.store.off(path, cb) }
},
notify(path, val){
Object.keys(phlo.store.listeners).forEach(dep => {
if (!phlo.store.match(dep, path)) return
const set = phlo.store.listeners[dep]
if (!set) return
const value = dep === path ? val : phlo.store.get(dep)
;[...set].forEach(cb => {
try { cb(value) }
catch(e){ phlo.log('store binding', dep, e) }
})
})
},
match(dep, changed){
if (!dep) return false
if (dep === changed) return true
return changed.startsWith(dep + '.') || changed.startsWith(dep + '[') || dep.startsWith(changed + '.') || dep.startsWith(changed + '[')
},
depsReady(list){
const arr = Array.isArray(list) ? list : (list ? [list] : [])
return arr.every(d => phlo.store.get(d) !== undefined)
},
evalCalc(name){
const fn = phlo.store.calcs[name]
if (!fn) return
let deps = []
let val
try {
const out = fn()
if (Array.isArray(out) && out.length === 2) deps = out[0], val = out[1]
else val = out
}
catch(e){
deps = []
val = undefined
}
const list = Array.isArray(deps) ? deps : (deps ? [deps] : [])
phlo.store.calcDeps[name] = list
if (!phlo.store.depsReady(list)) return
const old = phlo.store.calcVals[name]
if (old !== val){
phlo.store.calcVals[name] = val
const p = `calc.${name}`
phlo.store.setPath(p, val)
phlo.store.notify(p, val)
}
},
recalc(changed){
const names = Object.keys(phlo.store.calcs)
for (let i = 0; i < names.length; i++){
const name = names[i]
const deps = phlo.store.calcDeps[name] || []
for (let j = 0; j < deps.length; j++){
if (phlo.store.match(deps[j], changed)){
phlo.store.evalCalc(name)
break
}
}
}
},
recalcAll(){
const names = Object.keys(phlo.store.calcs)
for (let i = 0; i < names.length; i++) phlo.store.evalCalc(names[i])
},
schedule(){
if (phlo.store.calcTick) return
phlo.store.calcTick = true
setTimeout(() => {
phlo.store.calcTick = false
phlo.store.recalcAll()
})
},
format(name, value){
const fn = phlo.store.formats[name]
return fn ? fn(value) : value
},
adapters: {
local: {
read: key => { try { return JSON.parse(localStorage.getItem('phlo.' + key)) } catch(e){ return undefined } },
write: (key, value) => { try { localStorage.setItem('phlo.' + key, JSON.stringify(value)) } catch(e){} },
},
session: {
read: key => { try { return JSON.parse(sessionStorage.getItem('phlo.' + key)) } catch(e){ return undefined } },
write: (key, value) => { try { sessionStorage.setItem('phlo.' + key, JSON.stringify(value)) } catch(e){} },
},
},
persist(path, adapter = 'local'){
const store = typeof adapter === 'string' ? phlo.store.adapters[adapter] : adapter
if (!store) return
phlo.store.persists[path] = store
const saved = store.read(path)
if (saved !== undefined && saved !== null) app.mod.store(path, saved)
},
save(changed){
Object.keys(phlo.store.persists).forEach(path => {
if (phlo.store.match(path, changed)) phlo.store.persists[path].write(path, phlo.store.get(path))
})
},
sync(path, options = {}){
phlo.store.syncs[path] = {ws: options.ws ?? true, post: options.post ?? null, delay: options.delay ?? 200}
},
push(changed){
Object.keys(phlo.store.syncs).forEach(path => {
if (!phlo.store.match(path, changed)) return
const sync = phlo.store.syncs[path]
delay('store-' + path, sync.delay, () => {
const value = phlo.store.get(path)
if (sync.ws && app.websocket?.ready) app.websocket.send({sync: {[path]: value}})
if (sync.post) app.post(sync.post, {path, value}, false)
})
})
},
mirror(path, value){
phlo.store.quiet++
try { app.mod.store(path, value) }
finally { phlo.store.quiet-- }
},
proxy(base){
return new Proxy({}, {
get(t, k){
if (typeof k === 'symbol') return undefined
const seg = /^\d+$/.test(k) ? `[${k}]` : (base ? `.${k}` : String(k))
const path = base + seg
const v = phlo.store.get(path)
if (v !== undefined && (typeof v !== 'object' || v === null)) return v
return phlo.store.proxy(path)
},
set(t, k, v){
const seg = /^\d+$/.test(k) ? `[${k}]` : (base ? `.${k}` : String(k))
phlo.store.set(base + seg, v)
return true
},
has(t, k){ return phlo.store.get(base + (base ? '.' : '') + String(k)) !== undefined },
ownKeys(){ return Object.keys(phlo.store.get(base) || {}) },
getOwnPropertyDescriptor(){ return { enumerable: true, configurable: true } }
})
}
}
app.store = phlo.store.proxy('')
app.mod.store = (key, value) => {
if (JSON.stringify(phlo.store.get(key)) === JSON.stringify(value)) return
const walk = (base, obj) => {
if (Array.isArray(obj)) return phlo.store.set(base, obj)
if (typeof obj !== 'object' || obj === null) return phlo.store.set(base, obj)
Object.entries(obj).forEach(([k, v]) => walk(isNaN(k) ? `${base}.${k}` : `${base}[${k}]`, v))
}
walk(key, value)
}
app.mod.sync = (key, value) => phlo.store.mirror(key, value)
phlo.calc = new Proxy({}, {
set(t, k, fn){
if (typeof fn !== 'function') return false
phlo.store.calcs[k] = fn
phlo.store.evalCalc(k)
setTimeout(() => phlo.store.evalCalc(k))
return true
},
get(t, k){ return phlo.store.calcs[k] },
has(t, k){ return k in phlo.store.calcs },
deleteProperty(t, k){
delete phlo.store.calcs[k]
delete phlo.store.calcDeps[k]
delete phlo.store.calcVals[k]
return true
}
})
app.calc = new Proxy({}, {
get(t, k){ return phlo.store.calcVals[k] },
has(t, k){ return k in phlo.store.calcVals },
ownKeys(){ return Object.keys(phlo.store.calcVals) },
getOwnPropertyDescriptor(){ return { enumerable: true, configurable: true } }
})
app.format = (name, fn) => phlo.store.formats[name] = fn
app.persist = (path, adapter) => phlo.store.persist(path, adapter)
app.sync = (path, options) => phlo.store.sync(path, options)
app.push = path => phlo.store.push(path)
app.replace = (path, value) => phlo.store.replace(path, value)
onExist('[data-bind]', el => {
const not = el.dataset.bind.startsWith('!')
const key = not ? el.dataset.bind.slice(1) : el.dataset.bind
const isCalc = key.startsWith('calc.')
const isInput = el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA'
const fromDom = isInput ? el.value : el.textContent
const fromStore = phlo.store.get(key)
const domNonEmpty = (fromDom ?? '').trim() !== ''
const storeEmpty = fromStore === undefined || (typeof fromStore === 'string' && fromStore.trim() === '')
const domLeads = !isCalc && domNonEmpty && storeEmpty
const format = el.dataset.bindFormat
const S = v => v == null ? '' : (typeof v === 'object' ? '' : String(v))
const apply = raw => {
const v = not ? !raw : raw
const s = S(format ? phlo.store.format(format, v) : v)
if (isInput) el.value = s
else el.textContent = s
}
phlo.store.on(key, apply, el)
if (domLeads) phlo.store.set(key, fromDom)
const initial = domLeads ? fromDom : fromStore
apply(initial)
if (!isCalc && isInput) el.oninput = e => phlo.store.set(key, e.target.value)
})
onExist('[data-bind-attr]', el => {
const spec = el.attributes['data-bind-attr']?.value
if (!spec) return
const BOOL = new Set(['disabled','checked','hidden','required','readonly','selected','autofocus','multiple'])
let meta = phlo.existing.get(el)
if (!meta || typeof meta !== 'object'){
meta = { exist: true }
phlo.existing.set(el, meta)
}
meta.attr || (meta.attr = {})
meta.attr.cls || (meta.attr.cls = [])
const format = el.dataset.bindFormat
const owned = (el.dataset.bindClass || '').split(/\s+/).filter(Boolean)
spec.split(/\s*,\s*/).filter(Boolean).forEach(pair => {
const m = pair.match(/^\s*([^:]+)\s*:\s*(.+)\s*$/)
if (!m) return
const name = m[1]
const not = m[2].startsWith('!')
const path = not ? m[2].slice(1) : m[2]
const isCalc = path.startsWith('calc.')
const isInputVal = name === 'value' && (el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA')
const domVal =
name === 'text' ? el.textContent :
name === 'html' ? el.innerHTML :
name === 'value' ? el.value :
(name === 'class' ? null : el.attributes[name]?.value ?? null)
const fromStore = phlo.store.get(path)
const domNonEmpty = (domVal ?? '').trim() !== ''
const storeEmpty = fromStore === undefined || (typeof fromStore === 'string' && fromStore.trim() === '')
const domLeads = !isCalc && name !== 'class' && domNonEmpty && storeEmpty
const S = v => v == null ? '' : (typeof v === 'object' ? '' : String(v))
const apply = raw => {
const v = not ? !raw : raw
if (name === 'text') el.textContent = S(format ? phlo.store.format(format, v) : v)
else if (name === 'html') app.mod.inner(el, S(v))
else if (name === 'value') app.mod.value(el, S(format ? phlo.store.format(format, v) : v))
else if (name === 'class'){
const next = Array.isArray(v) ? v : (v && typeof v === 'object') ? Object.keys(v).filter(k => v[k]) : String(v ?? '').split(/\s+/)
const uniq = [...new Set(next.filter(Boolean))]
const prev = [...new Set([...meta.attr.cls, ...owned])]
for (let i = 0; i < prev.length; i++) el.classList.remove(prev[i])
for (let i = 0; i < uniq.length; i++) el.classList.add(uniq[i])
meta.attr.cls = uniq
}
else if (BOOL.has(name)){
const on = !!v
app.mod.attr(el, { [name]: on ? '' : null })
if (name in el) el[name] = on
}
else app.mod.attr(el, { [name]: S(v) })
}
phlo.store.on(path, apply, el)
if (domLeads) phlo.store.set(path, domVal)
const initial = domLeads ? domVal : fromStore
apply(initial)
if (!isCalc && isInputVal) el.oninput = e => phlo.store.set(path, e.target.value)
})
})
onExist('[data-each]', el => {
const path = el.dataset.each
const templates = [...objects('template', el)]
if (!templates.length) return
const key = el.dataset.key ? (el.dataset.key.startsWith('.') ? el.dataset.key : '.' + el.dataset.key) : ''
const pick = el.dataset.eachTemplate ? (el.dataset.eachTemplate.startsWith('.') ? el.dataset.eachTemplate : '.' + el.dataset.eachTemplate) : ''
const fallback = templates.find(t => t.dataset.template === undefined) || templates[0]
const template = index => {
if (!pick) return fallback
const name = String(phlo.store.get(`${path}[${index}]${pick}`) ?? '')
return templates.find(t => t.dataset.template === name) || fallback
}
const rows = new Map
const address = (node, index) => {
const base = `${path}[${index}]`
const bound = [...objects('[data-bind], [data-bind-attr]', node)]
if (node.matches('[data-bind], [data-bind-attr]')) bound.push(node)
bound.forEach(item => {
if (item.dataset.bind !== undefined && item.dataset.eachBind === undefined) item.dataset.eachBind = item.dataset.bind
const attr = item.attributes['data-bind-attr']?.value
if (attr !== undefined && item.dataset.eachBindAttr === undefined) item.dataset.eachBindAttr = attr
if (item.dataset.eachBind !== undefined){
const not = item.dataset.eachBind.startsWith('!') ? '!' : ''
const rel = not ? item.dataset.eachBind.slice(1) : item.dataset.eachBind
item.dataset.bind = not + (rel === '.' ? base : base + rel)
}
if (item.dataset.eachBindAttr !== undefined) item.setAttribute('data-bind-attr', item.dataset.eachBindAttr.replace(/:\s*(!?)\./g, (all, not) => ': ' + not + base + '.'))
})
}
const draw = () => {
const list = phlo.store.get(path)
const items = Array.isArray(list) ? list : (list && typeof list === 'object' ? Object.values(list) : [])
let changed = false
items.forEach((item, index) => {
const id = key ? String(phlo.store.get(`${path}[${index}]${key}`) ?? index) : String(index)
const tpl = template(index)
const row = rows.get(index)
if (row && row.id === id && row.tpl === tpl) return
row?.node.remove()
const node = tpl.content.firstElementChild.cloneNode(true)
address(node, index)
rows.set(index, {id, tpl, node})
el.appendChild(node)
changed = true
})
for (const [index, row] of [...rows]){
if (index < items.length) continue
row.node.remove()
rows.delete(index)
changed = true
}
if (changed) app.update()
}
phlo.store.on(path, draw, el)
draw()
})
onExist('[data-store-post]', el => {
const path = el.dataset.bind || el.dataset.storePath
if (!path) return
phlo.store.sync(path, {ws: el.dataset.storeWs !== undefined, post: el.dataset.storePost, delay: parseInt(el.dataset.storeDelay) || 200})
})
app.updates.push(() => phlo.store.sweep())
addEventListener('popstate', () => phlo.store.reset(phlo.store.scope))object
%template
/phlo/resources/DOM/template.phlo
view
script
line 8
定义一个函数,将指定的模板应用于每一行数据,使用行中的值调用模板。
app.mod.template = (template, rows) => rows.forEach(row => templates[template](...Object.values(row)))
const templates = {}object
%timestamps
/phlo/resources/DOM/timestamps.phlo
view
script
line 8
更新具有 'data-ts' 属性的元素的文本内容,以人类可读的格式显示自时间戳以来经过的时间,每秒刷新一次。
app.tsBase = {seconds: 60, minutes: 60, hours: 24, days: 7, weeks: 4, months: 13, years: 1}
const tsUpdate = () => (ranges = app.tsLabels && (tsValues = Object.values(app.tsBase)) ? Object.fromEntries(app.tsLabels.map((k, i) => [k, tsValues[i]])) : app.tsBase) && objects('[data-ts]').forEach(el => {
let age = Math.round(Date.now() / 1000) - Number(el.dataset.ts), text = ''
const future = age < 0
if (future) age = -age
for (const [range, multiplier] of Object.entries(ranges)){
if (text) continue
if (age / multiplier < 1.6583) text = `${Math.round(age)} ${range}`
age /= multiplier
}
text ||= `${Math.round(age)} ${Object.keys(ranges).at(-1)}`
text = `${future ? '-' : ''}${text}`
el.innerText === text || (el.innerText = text)
})
setInterval(() => document.hidden || tsUpdate(), 1000)
setTimeout(tsUpdate, 1)object
%toasts
/phlo/resources/DOM/toasts.phlo
view
script
line 9
app.mod.toast = msg => {
obj('#toasts') || app.mod.append('body', '<div id="toasts"></div>')
const toast = document.createElement('div')
toast.textContent = msg
toast.onclick = () => toast.remove()
obj('#toasts').insertAdjacentElement('beforeend', toast)
setTimeout(() => toast.remove(), 4000)
}view
style
line 20
定义了吐司通知的CSS样式,将其固定在右上角,并具有特定的背景颜色、边框半径和文本样式。
#toasts {
position: fixed
right: 10px
top: 5px
z-index: 1001
> * {
background-color: #000A
border-radius: 10px
clear: both
color: white
cursor: zoom-out
float: right
margin-top: 5px
padding: 3px 6px
}
}object
%visible
/phlo/resources/DOM/visible.phlo
view
script
line 9
设置一个IntersectionObserver,当指定元素在视口中变得可见或隐藏时执行回调函数。
phlo.observe = []
phlo.observing = new WeakMap
const onVisible = (els, cbIn, cbOut) => onVisibleIn(els, null, cbIn, cbOut)
const onVisibleIn = (els, root, cbIn, cbOut) => phlo.observe.push({els, root, cbIn, cbOut})
app.updates.push(() => {
const observers = []
phlo.observe.forEach(item => objects(item.els).forEach(el => phlo.observing.has(el) || observers.push({el, root: item.root, cbIn: item.cbIn, cbOut: item.cbOut})))
observers.forEach(item => [phlo.observing.has(item.el) || phlo.observing.set(item.el, 'observe'), (observer = new IntersectionObserver(entries => entries.forEach(entry => entry.isIntersecting ? !item.cbIn && item.cbOut ? [observer.unobserve(entry.target), item.cbOut(entry.target)] : item.cbIn(entry.target) : item.cbIn && item.cbOut && item.cbOut(entry.target)), {root: obj(item.root), threshold: .1})).observe(item.el)])
})object
%websocket
/phlo/resources/DOM/websocket.phlo
view
script
line 9
app.websocket = {
get open(){
app.options.contains('wss') && delay('websocket', app.websocket.retry, () => {
phlo.wss?.close()
phlo.wss = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/${app.websocket.path}`)
phlo.wss.onmessage = e => [{trans, state, ...cmds} = JSON.parse(e.data), apply(cmds, trans, state)]
phlo.wss.onopen = e => [app.websocket.polling(false), app.websocket.emit('connect', e), phlo.log('🖧 Websocket connected', e), app.websocket.retry = 333]
phlo.wss.onerror = e => [app.websocket.emit('error', e), phlo.log('🖧 Websocket error', e)]
phlo.wss.onclose = e => [app.websocket.polling(true), app.websocket.emit('close', e), phlo.log('🖧 Websocket close', e), app.websocket.retry && [app.websocket.open, app.websocket.retry = Math.min(app.websocket.retry * 3, 30000)]]
})
},
path: 'websocket',
get ready(){ return phlo.wss?.readyState === 1 },
subs: {},
on(event, cb, el = null){
(app.websocket.subs[event] ??= []).push({cb, el})
event === 'connect' && app.websocket.ready && cb()
return () => app.websocket.off(event, cb)
},
off(event, cb){ app.websocket.subs[event] = (app.websocket.subs[event] || []).filter(sub => sub.cb !== cb) },
emit(event, e){
const single = app.websocket[event]
single && single(e)
app.websocket.subs[event] = (app.websocket.subs[event] || []).filter(sub => !sub.el || sub.el.isConnected)
app.websocket.subs[event].forEach(sub => {
try { sub.cb(e) }
catch(err){ phlo.log('🖧 Websocket ' + event, err) }
})
},
send(data){
if (phlo.wss?.readyState !== 1) return phlo.log('🖧 Could not send websocket data over closed socket', data), false
phlo.log('🖧 app.websocket.send', '\n', data)
phlo.wss.send(JSON.stringify(data))
return true
},
retry: 333,
poll: null,
pollEvery: 15000,
polling(on){
if (on) return app.websocket.poll && (app.websocket.timer ??= setInterval(() => phlo.request('GET', app.websocket.poll, null, false), app.websocket.pollEvery))
clearInterval(app.websocket.timer)
app.websocket.timer = null
},
}
app.websocket.open
addEventListener('online', () => phlo.wss?.readyState !== 1 && [app.websocket.retry = 333, app.websocket.open])
addEventListener('visibilitychange', () => !document.hidden && phlo.wss?.readyState !== 1 && [app.websocket.retry = 333, app.websocket.open])最近更新于 2026年10月29日