{"schemaVersion":1,"slug":"component-local-file-vault","kind":"component","version":"0.1.0","files":[{"path":"Component.jsx","content":"'use client'\nimport React from 'react'\nimport Example from './local-file-vault.jsx'\nimport './collection.css'\nimport './family.css'\nexport default function Component(props) {\n  return <div className=\"lq-component\" data-family=\"workflow\"><Example {...props}/></div>\n}\n","sha256":"64b2b4a4b937f3254ad5e9d131c4ddee3dcb244ae72cd0ae2aff7c64266adbd6"},{"path":"local-file-vault.jsx","content":"'use client'\nimport React, { useEffect, useId, useRef, useState } from 'react'\nimport { words, Summary } from './shared.jsx'\n\nconst types = { txt: 'text/plain', png: 'image/png', pdf: 'application/pdf' }\nconst maximum = 2 * 1024 * 1024\nasync function matchesFile(file) {\n  const extension = file.name.toLowerCase().split('.').pop()\n  if (!file.name.includes('.') || types[extension] !== file.type) return false\n  if (file.type === 'text/plain') {\n    const bytes = new Uint8Array(await file.arrayBuffer())\n    if (bytes.includes(0)) return false\n    try {\n      new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n      return true\n    } catch {\n      return false\n    }\n  }\n  const bytes = new Uint8Array(await file.slice(0, 8).arrayBuffer())\n  const signature =\n    file.type === 'image/png'\n      ? [137, 80, 78, 71, 13, 10, 26, 10]\n      : [37, 80, 68, 70, 45]\n  return signature.every((value, index) => bytes[index] === value)\n}\n\nfunction openVault() {\n  return new Promise((resolve, reject) => {\n    const request = indexedDB.open('layq-example-file-vault-v1', 1)\n    request.onupgradeneeded = () =>\n      request.result.createObjectStore('files', { keyPath: 'id' })\n    request.onerror = () => reject(request.error)\n    request.onsuccess = () => resolve(request.result)\n  })\n}\nasync function access(mode, operation) {\n  const db = await openVault()\n  try {\n    return await new Promise((resolve, reject) => {\n      const tx = db.transaction('files', mode)\n      const result = operation(tx.objectStore('files'))\n      tx.oncomplete = () => resolve(result.result)\n      tx.onabort = () => reject(tx.error)\n      tx.onerror = () => reject(tx.error)\n    })\n  } finally {\n    db.close()\n  }\n}\nexport default function FileVault({ locale = 'en' }) {\n  const t = words(\n    locale,\n    'Choose a sample file|TXT, PNG or PDF · up to 2 MiB per file · saved on this device|Remove|No stored files|File type is unsupported.|Maximum file size is 2 MiB.|Storage is unavailable. Check browser storage and retry.|Saved on this device.|File removed.|Loading stored files…|Inspect|bytes|First bytes (hex)|Empty file|Close preview',\n    '选择示例文件|TXT、PNG 或 PDF · 每份最多 2 MiB · 保存在本机|删除|暂无已存文件|不支持此文件类型。|每份文件最大 2 MiB。|本地存储不可用，请检查浏览器后重试。|已保存到本机。|文件已删除。|正在读取文件…|查看内容|字节|起始字节（十六进制）|空文件|关闭预览',\n    'Elegir archivo de ejemplo|TXT, PNG o PDF · hasta 2 MiB por archivo · guardado en este dispositivo|Eliminar|No hay archivos guardados|Tipo de archivo no admitido.|El límite por archivo es de 2 MiB.|El almacenamiento no está disponible. Revísalo y vuelve a intentar.|Guardado en este dispositivo.|Archivo eliminado.|Cargando archivos…|Inspeccionar|bytes|Primeros bytes (hex)|Archivo vacío|Cerrar vista',\n    'サンプルファイルを選択|TXT、PNG、PDF · 1 件 2 MiB まで · この端末に保存|削除|保存済みファイルはありません|対応していない形式です。|1 件の上限は 2 MiB です。|保存領域にアクセスできません。ブラウザの設定を確認してください。|この端末に保存しました。|ファイルを削除しました。|ファイルを読み込み中…|内容を確認|バイト|先頭のバイト（16進数）|空のファイル|プレビューを閉じる',\n  )\n  const [rows, setRows] = useState([]),\n    [state, setState] = useState(9),\n    [busy, setBusy] = useState(true),\n    [preview, setPreview] = useState(null)\n  const id = useId(),\n    mounted = useRef(false)\n  useEffect(() => {\n    let active = true\n    mounted.current = true\n    access('readonly', (store) => store.getAll())\n      .then((files) => {\n        if (active) {\n          setRows(files)\n          setState(null)\n        }\n      })\n      .catch(() => active && setState(6))\n      .finally(() => active && setBusy(false))\n    return () => {\n      active = false\n      mounted.current = false\n    }\n  }, [])\n  async function change(operation, message) {\n    setBusy(true)\n    try {\n      await access('readwrite', operation)\n      const updated = await access('readonly', (store) => store.getAll())\n      if (mounted.current) {\n        setRows(updated)\n        setPreview(null)\n        setState(message)\n      }\n    } catch {\n      if (mounted.current) setState(6)\n    } finally {\n      if (mounted.current) setBusy(false)\n    }\n  }\n  async function upload(event) {\n    const file = event.target.files?.[0]\n    event.target.value = ''\n    if (!file) return\n    if (file.size > maximum) {\n      setState(5)\n      return\n    }\n    setBusy(true)\n    try {\n      if (!(await matchesFile(file))) {\n        if (mounted.current) {\n          setState(4)\n          setBusy(false)\n        }\n        return\n      }\n    } catch {\n      if (mounted.current) {\n        setState(6)\n        setBusy(false)\n      }\n      return\n    }\n    if (!mounted.current) return\n    await change(\n      (store) =>\n        store.add({\n          id: crypto.randomUUID(),\n          name: file.name,\n          type: file.type,\n          blob: file,\n        }),\n      7,\n    )\n  }\n  async function inspect(row) {\n    try {\n      const bytes = new Uint8Array(await row.blob.slice(0, 64).arrayBuffer())\n      setPreview({\n        id: row.id,\n        name: row.name,\n        text:\n          row.type === 'text/plain'\n            ? new TextDecoder().decode(bytes)\n            : Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(\n                ' ',\n              ),\n        binary: row.type !== 'text/plain',\n      })\n    } catch {\n      setState(6)\n    }\n  }\n  return (\n    <section className=\"wf-demo\">\n      <label htmlFor={id}>{t[0]}</label>\n      <p>{t[1]}</p>\n      <input\n        id={id}\n        type=\"file\"\n        accept=\".txt,.png,.pdf,text/plain,image/png,application/pdf\"\n        disabled={busy}\n        onChange={upload}\n      />\n      <ul>\n        {rows.map((row) => (\n          <li key={row.id}>\n            <strong>{row.name}</strong>{' '}\n            <small>\n              {row.blob.size} {t[11]}\n            </small>{' '}\n            <button disabled={busy} onClick={() => inspect(row)}>\n              {t[10]}\n            </button>{' '}\n            <button\n              disabled={busy}\n              onClick={() => change((store) => store.delete(row.id), 8)}\n            >\n              {t[2]}\n            </button>\n          </li>\n        ))}\n      </ul>\n      {preview && (\n        <div>\n          <strong>{preview.name}</strong>\n          {preview.binary && <p>{t[12]}</p>}\n          <pre style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>\n            {preview.text || t[13]}\n          </pre>\n          <button onClick={() => setPreview(null)}>{t[14]}</button>\n        </div>\n      )}\n      {!busy && !rows.length && <p>{t[3]}</p>}\n      <Summary>{state === null ? '' : t[state]}</Summary>\n    </section>\n  )\n}\n","sha256":"9bc5e38d0f09317fc5be70893a444a03e5cebad1e464b1d35dbb8caeb3726080"},{"path":"collection.css","content":"/* Portable styles for the optional wrapper in Component.jsx. */\n.lq-component {\n  --cc-ink:#162632; --cc-muted:#526572; --cc-stroke:#cbd5dc; --cc-tint:#edf3f6;\n  --cc-blue:#426981; --cc-surface:#fff; --cc-inverse:#fff;\n  font:400 15px/1.55 system-ui,sans-serif; color:var(--cc-ink);\n  min-width:0; width:100%; overflow-wrap:anywhere; color-scheme:light;\n}\n.lq-component *, .lq-component *::before,.lq-component *::after { box-sizing:border-box; }\n.lq-component :is(h2,h3,h4,p,ul,ol,dl,form,fieldset,figure,table) { margin:0 0 .85em; }\n.lq-component :is(h2,h3) { font-size:clamp(20px,2vw,29px); line-height:1.18; letter-spacing:-.035em; }\n.lq-component h4 {font-size:1rem}\n.lq-component :is(ol,ul){padding-inline-start:1.4em}\n.lq-component label { display:inline-flex; flex-direction:column; gap:4px; max-width:100%; font-size:14px; font-weight:550; }\n.lq-component label:has(input[type=checkbox]),.lq-component label:has(input[type=radio]) {flex-direction:row;align-items:center}\n.lq-component :is(input,select,textarea,button){font:inherit;max-width:100%;accent-color:var(--cc-blue)}\n.lq-component :is(input:not([type=checkbox],[type=radio],[type=range],[type=file]),select,textarea){\n  color:var(--cc-ink); background:var(--cc-surface); border:1px solid #a9bac5; border-radius:6px; padding:7px 10px;min-width:0;\n}\n.lq-component textarea{min-height:64px}\n.lq-component :is(button,summary){cursor:pointer;}\n.lq-component button{\n  color:var(--cc-ink);background:var(--cc-tint);border:1px solid var(--cc-stroke);\n  border-radius:6px;min-height:35px;padding:5px 11px;font-weight:600;font-size:14px;\n}\n.lq-component button:disabled{opacity:.5;cursor:default}\n.lq-component button[aria-pressed=true],.lq-component [role=tab][aria-selected=true]{background:var(--cc-ink);color:var(--cc-inverse)}\n.lq-component :focus-visible{outline:2px solid var(--cc-blue);outline-offset:2px}\n.lq-component output {display:block;color:var(--cc-ink);font-weight:650;font-variant-numeric:tabular-nums}\n.lq-component :is(.collection-actions,.collection-row,.demo-actions){display:flex;align-items:end;gap:9px;flex-wrap:wrap;margin-block:12px}\n.lq-component :is(.collection-fields,.form-fields){display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr));gap:14px;margin-block:14px}\n.lq-component :is(.collection-output,.demo-output){padding:12px;border-inline-start:3px solid var(--cc-blue);background:var(--cc-tint);margin-block:14px}\n.lq-component fieldset {border:1px solid var(--cc-stroke);border-radius:8px;padding:12px;min-width:0}\n.lq-component .collection-demo>*,.lq-component .viz-study>*{max-width:100%}\n.lq-component :is(form,fieldset)>label {margin:0 10px 10px 0}\n.lq-component :is(button+button,label+button) {margin-inline-start:3px}\n.lq-component table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}\n.lq-component :is(th,td){padding:6px;text-align:start;border-bottom:1px solid var(--cc-stroke)}\n.lq-component dialog{max-width:min(90vw,500px);border:1px solid var(--cc-stroke);border-radius:10px;padding:20px;color:var(--cc-ink);background:white}\n.lq-component dialog::backdrop{background:rgb(17 29 39/.45)}\n.lq-component :is(svg,canvas,img){max-width:100%}\n@media(hover:hover){.lq-component button:not(:disabled):hover{border-color:var(--cc-blue)}}\n@media(pointer:coarse){.lq-component button,.lq-component select,.lq-component input[type=range]{min-height:44px}}\n@media(prefers-reduced-motion:reduce){.lq-component *, .lq-component *::before,.lq-component *::after{animation-duration:0s!important;transition-duration:0s!important;scroll-behavior:auto!important}}\n.lq-component :is(.viz-study,.wf-demo,.collection-demo)>label {margin:0 16px 12px 0}\n.lq-component .viz-study>svg[role=img]{display:block;margin:6px 0 14px}\n.lq-component .viz-study>output{border-top:1px solid var(--cc-stroke);padding:12px 0 0;font-variant-numeric:tabular-nums}\n.lq-component :is(.wf-demo,.collection-demo) form{display:flex;align-items:end;flex-wrap:wrap;gap:9px 14px}\n.lq-component :is(.wf-demo,.collection-demo) label textarea{width:min(100%,34rem)}\n.lq-component :is(.wf-demo,.collection-demo)>:is(output,[role=status]){display:block;margin-top:12px;color:var(--cc-blue);font-weight:600}\n.lq-component .collection-fields>.collection-row,.lq-component .collection-fields>.collection-output,.lq-component .collection-fields>svg{grid-column:1/-1}\n","sha256":"9a629a50c65fc07377b3d164b571ed33b8bd54c392ff4dab06c4fd317c0864ab"},{"path":"shared.jsx","content":"import React from 'react'\n\nconst languages = ['en', 'zh-CN', 'es', 'ja']\nexport function words(locale, ...lines) {\n  return lines[Math.max(0, languages.indexOf(locale))].split('|')\n}\nexport function Field({ label, children }) {\n  return (\n    <label className=\"wf-field\">\n      <span>{label}</span>\n      {children}\n    </label>\n  )\n}\nexport function Summary({ children }) {\n  return (\n    <p className=\"wf-result\" role=\"status\">\n      <strong>{children}</strong>\n    </p>\n  )\n}\nexport function Grid({ head, children }) {\n  return (\n    <div className=\"wf-table-wrap\">\n      <table>\n        <thead>\n          <tr>\n            {head.map((h) => (\n              <th key={h} scope=\"col\">\n                {h}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>{children}</tbody>\n      </table>\n    </div>\n  )\n}\n","sha256":"21bf7e0a7355d4442b52eadf9f0ee29636edd0920b8fad548cf141eece8e3370"},{"path":"family.css","content":"/* Layout and feedback for the portable workflow examples. Shared colors and\n   focus outlines come from the collection wrapper. */\n.lq-component .wf-demo { max-inline-size: 54rem; min-inline-size: 0; }\n.lq-component .wf-demo > .wf-field {\n  display: inline-flex;\n  margin: 0 1rem .85rem 0;\n  vertical-align: top;\n  max-inline-size: min(100%, 24rem);\n}\n.lq-component .wf-demo :is(form, .wf-field) > :is(input, select, textarea) {\n  min-inline-size: 0;\n}\n.lq-component .wf-demo .wf-field:has(textarea) { display: flex; max-inline-size: 38rem; }\n.lq-component .wf-demo > .wf-result {\n  margin-block: .9rem .25rem;\n  padding: .65rem .8rem;\n  border-inline-start: 3px solid var(--cc-blue);\n  background: var(--cc-tint);\n  color: var(--cc-ink);\n  font-variant-numeric: tabular-nums;\n}\n.lq-component .wf-demo > .wf-result:has(strong:empty) { display: none; }\n.lq-component .wf-demo .wf-table-wrap { overflow-x: auto; }\n.lq-component .wf-demo [role=\"treegrid\"] { table-layout: fixed; }\n.lq-component .wf-demo [role=\"treegrid\"] th:last-child { inline-size: 30%; }\n.lq-component .wf-demo [role=\"treegrid\"] tr:focus-visible {\n  outline-offset: -2px;\n  background: var(--cc-tint);\n}\n.lq-component .wf-demo > :is(ol, ul) { padding-inline-start: 1.2rem; }\n.lq-component .wf-demo li { margin-block: .35rem; }\n.lq-component .wf-demo li > p { color: var(--cc-muted); margin-block: .12rem .4rem; }\n.lq-component .wf-demo progress { display: block; width: min(20rem,100%); accent-color: var(--cc-blue); }\n.lq-component .wf-demo [type=\"file\"] { width: 100%; padding-block: .4rem; }\n.lq-component .wf-demo [type=\"file\"]::file-selector-button {\n  border: 1px solid var(--cc-stroke);\n  background: var(--cc-tint);\n  color: var(--cc-ink);\n  padding: .42rem .7rem;\n  margin-inline-end: .65rem;\n  border-radius: .38rem;\n  cursor: pointer;\n}\n@media (pointer: coarse) {\n  .lq-component .wf-demo [role=\"treegrid\"] td { height: 44px; }\n  .lq-component .wf-demo [type=\"file\"]::file-selector-button { min-height: 44px; }\n}\n","sha256":"05234d1dddf1437947ba23aa6008f45adecf9e6723c994819d7d9ab284137775"},{"path":"README.md","content":"# Local file vault\n\nStore a sample file on this device, inspect its bytes after a refresh and remove it.\n\nImport the default export from Component.jsx into a React client entry. The locale prop accepts en, zh-CN, es and ja. Use your host’s existing React dependency and test and build commands. The sample runs locally.\n","sha256":"03b0cee42c39b9c3f501cb5c5e3e787b5aceb4e84abaaadce56dd5705a7b57be"}]}
