From bf5305704dce28dda9c722d9354fd51bb9153454 Mon Sep 17 00:00:00 2001 From: Alexis Quintero Date: Sun, 4 Oct 2026 05:41:09 -0500 Subject: [PATCH] feat: mobile layout and coloured manual sequence editing (v0.4.0) - Compact layout (measured on the editor: narrow, portrait or short) with Map / Sequence / Build tabs; side rail in phone landscape; 44px touch targets, safe areas, dynamic viewport height, touch text selection. - Manual editing: paste or type FASTA or a plain sequence and the map, sites, length and GC% follow live (deferred). The text is coloured like the map through a synced backdrop; vector/insert regions move with each edit (shiftSpans) and mirror on reverse complement. Edits work on a copy; the cloning inputs stay untouched. - Editor and viewer lines fit the panel width. - Minimal themed scrollbars. - Core: gcContent, baseIndexAt, shiftSpans (28 tests). Co-Authored-By: Claude Opus 5.5 --- CITATION.cff | 2 +- README.md | 4 + app/app.css | 69 ++++++- app/index.html | 2 +- package.json | 2 +- src/core/fasta.ts | 34 ++++ src/core/index.ts | 5 +- src/core/regions.ts | 34 ++++ src/ui/FastaView.tsx | 44 ++++- src/ui/SequenceEditor.tsx | 198 +++++++++++++++++++ src/ui/VectorEditor.tsx | 187 +++++++++++++++--- src/ui/labels.ts | 38 ++++ src/ui/styles.css | 399 ++++++++++++++++++++++++++++++++++++-- src/ui/useCloning.ts | 129 +++++++----- test/core.test.ts | 48 +++++ 15 files changed, 1088 insertions(+), 107 deletions(-) create mode 100644 src/core/regions.ts create mode 100644 src/ui/SequenceEditor.tsx diff --git a/CITATION.cff b/CITATION.cff index 4ca2bcc..139488a 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,7 +2,7 @@ cff-version: 1.2.0 message: "Si usas este software, por favor cítalo así. / If you use this software, please cite it as below." title: "Vector editor: in-browser cloning simulator with REBASE enzymes" type: software -version: 0.3.1 +version: 0.4.0 authors: - family-names: "Quintero López" given-names: "Oscar Alexis" diff --git a/README.md b/README.md index 07fa272..f6b963d 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ Simulador de clonación en el navegador: elige enzimas de restricción comercial - **Digestión y ligación** con extremos reales (5', 3' o romos): comprueba la compatibilidad de ambas uniones, prueba las dos orientaciones del inserto y avisa si el vector puede religarse o si las enzimas cortan dentro del inserto. Funciona con enzimas tipo IIS (Golden Gate). - **Archivos**: FASTA, GenBank y SnapGene (`.dna`), leídos localmente con [seqparse](https://github.com/Lattice-Automation/seqparse). - **Mapa y FASTA vinculados**: el FASTA se colorea igual que el mapa circular ([SeqViz](https://github.com/Lattice-Automation/seqviz)) — vector, inserto y sitios de corte —; seleccionar bases en el FASTA marca el arco en el mapa, hacer clic en el mapa o en la leyenda resalta y lleva a esa secuencia. Copia o descarga el FASTA completo o solo la selección. +- **Edición manual coloreada**: pega o escribe una secuencia (FASTA o sola) y el mapa, los sitios de corte, la longitud y el %GC se actualizan en vivo; vector, inserto y sitios conservan su color y se desplazan con cada edición. Formatear y reverso complementario. +- **Móvil y pantallas verticales**: pestañas Mapa · Secuencia · Construir; en horizontal, riel lateral para dar toda la altura al mapa. - **Búsqueda de enzimas** en un desplegable con teclado (↑ ↓ Enter Esc), filtrable por proveedor y por si cortan vector e inserto. - **Exporta GenBank anotado** (vector, inserto con su orientación y sitios de restricción), listo para SnapGene, Benchling, ApE o Biopython, además de FASTA. - **Atajos**: `/` buscar enzima · `C` copiar (la selección si hay una) · `D` FASTA · `G` GenBank · `Esc` quitar selección. @@ -30,6 +32,8 @@ Simulador de clonación en el navegador: elige enzimas de restricción comercial - **Digestion and ligation** with real ends (5', 3' or blunt): checks both junctions, tries both insert orientations, and warns when the vector can self-ligate or the enzymes cut inside the insert. Works with type IIS enzymes (Golden Gate). - **Files**: FASTA, GenBank and SnapGene (`.dna`), parsed locally with [seqparse](https://github.com/Lattice-Automation/seqparse). - **Linked map and FASTA**: the FASTA is coloured like the circular map ([SeqViz](https://github.com/Lattice-Automation/seqviz)) — vector, insert and cut sites —; selecting bases in the FASTA marks the arc on the map, and clicking the map or the legend highlights and scrolls to that sequence. Copy or download the whole FASTA or just the selection. +- **Coloured manual editing**: paste or type a sequence (FASTA or plain) and the map, cut sites, length and GC% update live; vector, insert and sites keep their colours and move with every edit. Format and reverse complement. +- **Phones and portrait screens**: Map · Sequence · Build tabs; in landscape, a side rail gives the map the full height. - **Enzyme search** in a keyboard-friendly dropdown (↑ ↓ Enter Esc), filterable by supplier and by whether enzymes cut vector and insert. - **Annotated GenBank export** (vector, insert with its orientation and restriction sites), ready for SnapGene, Benchling, ApE or Biopython, plus FASTA. - **Shortcuts**: `/` search enzyme · `C` copy (the selection if any) · `D` FASTA · `G` GenBank · `Esc` clear selection. diff --git a/app/app.css b/app/app.css index 20e7c92..2242841 100644 --- a/app/app.css +++ b/app/app.css @@ -25,6 +25,33 @@ body { color: var(--bp-sterile); font-family: system-ui, -apple-system, 'Segoe UI', sans-serif; } +::-webkit-scrollbar { + width: 8px; + height: 8px; +} +::-webkit-scrollbar-track, +::-webkit-scrollbar-corner { + background: transparent; +} +::-webkit-scrollbar-button { + display: none; +} +::-webkit-scrollbar-thumb { + border: 2px solid transparent; + border-radius: 999px; + background: var(--bp-tissue); + background-clip: padding-box; +} +::-webkit-scrollbar-thumb:hover { + background: var(--bp-boundary); + background-clip: padding-box; +} +@supports not selector(::-webkit-scrollbar) { + html { + scrollbar-width: thin; + scrollbar-color: var(--bp-tissue) transparent; + } +} ::selection { background: var(--bp-bio); color: var(--bp-ink); @@ -33,6 +60,10 @@ body { display: grid; grid-template-rows: minmax(0, 1fr) auto; height: 100%; + /* Dynamic viewport height: the mobile browser bar never hides the tab bar. */ + height: 100dvh; + padding-left: env(safe-area-inset-left); + padding-right: env(safe-area-inset-right); } .ve { --ve-theme-bg: var(--bp-ink); @@ -51,6 +82,8 @@ body { --ve-theme-map-muted: var(--bp-boundary); --ve-theme-map-cut: var(--bp-pink); --ve-theme-map-selection: rgb(164 230 109 / 0.16); + --ve-theme-scroll-thumb: var(--bp-tissue); + --ve-theme-scroll-thumb-hover: var(--bp-boundary); } /* The map as a specimen under the microscope: reticle grid, vignette, glowing arcs. */ .ve-map { @@ -128,13 +161,37 @@ body { .app-footer a:hover { color: var(--bp-bio); } -@media (max-width: 1100px) { - /* On smaller screens the page scrolls instead of fitting the viewport. */ +@media (max-width: 640px) { + .app-tagline { + display: none; + } + .app-brand { + flex: 1; + border-right: 0; + } + .app-lang { + margin-left: auto; + } + .app-footer { + gap: 0.2rem 0.5rem; + padding: 0.35rem 0.75rem calc(0.35rem + env(safe-area-inset-bottom)); + font-size: 0.68rem; + } +} +@media (max-height: 520px) and (orientation: landscape) { + /* Every pixel of height goes to the map; the credit stays on the full layout. */ + .app-footer { + display: none; + } .app-shell { - height: auto; - min-height: 100%; + grid-template-rows: minmax(0, 1fr); + } + .app-tagline, + .app-brand strong { + display: none; } - .ve--app { - height: auto; + .app-brand { + border-right: 0; + padding-right: 0; } } diff --git a/app/index.html b/app/index.html index 0056c2b..a35af56 100644 --- a/app/index.html +++ b/app/index.html @@ -2,7 +2,7 @@ - + Vector Editor — simulador de clonación ') inHeader = true + if (char === '\n') { + inHeader = false + lineStart = true + continue + } + lineStart = false + if (!inHeader && valid.test(char)) index++ + } + return index +} diff --git a/src/core/index.ts b/src/core/index.ts index 9321162..cc313bd 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,8 +1,9 @@ export * from './types' -export { reverseComplement } from './iupac' +export { reverseComplement, IUPAC_LETTERS } from './iupac' export { commercialEnzymes, suppliers, rebaseVersion, parseEnzyme, formatSite } from './enzymes' export { findSites, findCuts, findAllCuts } from './sites' export { digest, topStrand, fragmentLength, leftEnd, rightEnd, flip } from './digest' export { ligate, compatible, canSelfLigate } from './ligate' -export { parseSequence, toFasta } from './fasta' +export { parseSequence, toFasta, gcContent, baseIndexAt } from './fasta' export { toGenBank, type Feature } from './genbank' +export { shiftSpans, type Span } from './regions' diff --git a/src/core/regions.ts b/src/core/regions.ts new file mode 100644 index 0000000..f4d1e90 --- /dev/null +++ b/src/core/regions.ts @@ -0,0 +1,34 @@ +export interface Span { + start: number + end: number +} + +/** + * Moves half-open spans after an edit that turned `before` into `after`. + * The edit is the part between their common prefix and suffix: text typed + * inside a span grows it, deleted text shrinks it, spans after it shift. + */ +export function shiftSpans(spans: T[], before: string, after: string): T[] { + let prefix = 0 + const shortest = Math.min(before.length, after.length) + while (prefix < shortest && before[prefix] === after[prefix]) prefix++ + let suffix = 0 + while ( + suffix < shortest - prefix && + before[before.length - 1 - suffix] === after[after.length - 1 - suffix] + ) + suffix++ + const oldEnd = before.length - suffix + const newEnd = after.length - suffix + const delta = after.length - before.length + // Boundaries before the edit stay; text typed at a boundary joins the span that starts + // there; boundaries inside the replaced stretch move to its new end. + const move = (position: number) => { + if (position <= prefix) return position + if (position >= oldEnd) return position + delta + return newEnd + } + return spans + .map((span) => ({ ...span, start: move(span.start), end: move(span.end) })) + .filter((span) => span.end > span.start) +} diff --git a/src/ui/FastaView.tsx b/src/ui/FastaView.tsx index 978c4a2..d708745 100644 --- a/src/ui/FastaView.tsx +++ b/src/ui/FastaView.tsx @@ -23,6 +23,8 @@ interface Props { range: SeqRange | null rangeSource: RangeSource | null onRange: (range: SeqRange) => void + /** False while the panel is hidden (compact layout); re-scrolls when shown again. */ + active?: boolean /** Fixed bases per line; by default it fits the panel width (multiples of 10). */ width?: number label: string @@ -44,6 +46,7 @@ export function FastaView({ rangeSource, onRange, width: fixedWidth, + active = true, label }: Props) { const box = useRef(null) @@ -119,13 +122,13 @@ export function FastaView({ // Follow selections made on the map or the legend. useEffect(() => { - if (!range || rangeSource === 'fasta' || !box.current) return + if (!active || !range || rangeSource === 'fasta' || !box.current) return const line = box.current.querySelector( `[data-line="${Math.floor(range.start / width) * width}"]` ) // The view is the offsetParent of its lines (position: relative). if (line) box.current.scrollTop = line.offsetTop - 24 - }, [range, rangeSource, width]) + }, [range, rangeSource, width, active]) const positionOf = (node: Node | null, offset: number): number | null => { const element = node instanceof Element ? node : node?.parentElement @@ -134,16 +137,43 @@ export function FastaView({ return Number(run.dataset.start) + (node instanceof Text ? offset : 0) } - const onMouseUp = () => { + const readSelection = (): SeqRange | null => { const selection = window.getSelection() - if (!selection || selection.isCollapsed) return + if (!selection || selection.isCollapsed) return null const a = positionOf(selection.anchorNode, selection.anchorOffset) const b = positionOf(selection.focusNode, selection.focusOffset) - if (a === null || b === null || a === b) return - onRange({ start: Math.min(a, b), end: Math.max(a, b) }) - selection.removeAllRanges() + if (a === null || b === null || a === b) return null + return { start: Math.min(a, b), end: Math.max(a, b) } } + const onMouseUp = () => { + const next = readSelection() + if (!next) return + onRange(next) + window.getSelection()?.removeAllRanges() + } + + // Touch: long-press selection has no mouseup, and its handles keep moving, so follow + // selection changes (debounced) and leave the native selection in place. + const latest = useRef(onRange) + latest.current = onRange + useEffect(() => { + if (!window.matchMedia('(pointer: coarse)').matches) return + let timer = 0 + const onChange = () => { + window.clearTimeout(timer) + timer = window.setTimeout(() => { + const next = readSelection() + if (next) latest.current(next) + }, 250) + } + document.addEventListener('selectionchange', onChange) + return () => { + window.clearTimeout(timer) + document.removeEventListener('selectionchange', onChange) + } + }, []) + return (
{header}
diff --git a/src/ui/SequenceEditor.tsx b/src/ui/SequenceEditor.tsx new file mode 100644 index 0000000..43f1f8d --- /dev/null +++ b/src/ui/SequenceEditor.tsx @@ -0,0 +1,198 @@ +import React, { useEffect, useMemo, useRef, useState } from 'react' +import { baseIndexAt, gcContent, IUPAC_LETTERS, parseSequence, toFasta, type Site } from '../core' +import { inRange, type Region, type SeqRange } from './FastaView' +import type { Labels } from './labels' + +interface Props { + value: string + onChange: (value: string) => void + /** Bases selected in the text, reported so the map can mark them. */ + onSelectRange: (range: SeqRange | null) => void + /** Reverse-complements the sequence (mirroring regions); lines fit `columns`. */ + onReverse: (columns: number) => void + regions: Region[] + sites: Site[] + range: SeqRange | null + labels: Labels +} + +const VALID = new RegExp(`[${IUPAC_LETTERS}]`, 'i') + +/** + * Colour runs for the text exactly as typed: the header line, then each base with the + * colour of its region, its recognition sites and the current selection. + */ +function colourRuns(text: string, regions: Region[], sites: Site[], range: SeqRange | null, length: number) { + const kind = new Uint8Array(length) + const site = new Uint8Array(length) + for (const region of regions) { + for (let i = region.start; i < region.end && i < length; i++) kind[i] = region.kind === 'insert' ? 2 : 1 + } + for (const s of sites) { + for (let i = s.start; i < s.start + s.length; i++) if (length) site[i % length] = 1 + } + const runs: Array<{ text: string; className: string }> = [] + let base = 0 + let inHeader = false + let lineStart = true + for (const char of text) { + let className = '' + if (lineStart && char === '>') inHeader = true + if (char === '\n') { + inHeader = false + lineStart = true + } else { + lineStart = false + if (inHeader) className = 'is-header' + else if (VALID.test(char) && base < length) { + className = [ + kind[base] === 1 ? 'is-vector' : kind[base] === 2 ? 'is-insert' : '', + site[base] ? 'is-site' : '', + range && inRange(range, base) ? 'is-selected' : '' + ] + .filter(Boolean) + .join(' ') + base++ + } else if (!/\s|\d/.test(char)) className = 'is-invalid' + } + const last = runs[runs.length - 1] + if (last && last.className === className) last.text += char + else runs.push({ text: char, className }) + } + return runs +} + +/** Paste or type a sequence (FASTA or raw); colours and the map follow as you type. */ +export function SequenceEditor({ + value, + onChange, + onSelectRange, + onReverse, + regions, + sites, + range, + labels +}: Props) { + const area = useRef(null) + const backdrop = useRef(null) + const parsed = parseSequence(value, 'sequence') + const gc = gcContent(parsed.seq) + // Null until measured; the one-time reflow waits for the real width. + const [measured, setMeasured] = useState(null) + const columns = measured ?? 60 + + // Lines that fit the box (blocks of ten), so FASTA never wraps mid-line on a phone. + useEffect(() => { + const element = area.current + if (!element || typeof ResizeObserver === 'undefined') return + const probe = document.createElement('span') + probe.textContent = 'ACGTACGTAC' + const style = getComputedStyle(element) + probe.style.cssText = `position:absolute;top:0;left:-9999px;visibility:hidden;white-space:pre;font:${style.font}` + document.body.appendChild(probe) + const measure = () => { + const charWidth = probe.getBoundingClientRect().width / 10 + const inner = element.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) + if (charWidth > 0 && inner > 0) setMeasured(Math.min(80, Math.max(20, Math.floor(inner / charWidth / 10) * 10))) + } + measure() + const observer = new ResizeObserver(measure) + observer.observe(element) + return () => { + observer.disconnect() + probe.remove() + } + }, []) + + // When the editor opens on generated FASTA that is wider than the box, reflow it once. + const reflowed = useRef(false) + useEffect(() => { + if (reflowed.current || measured === null || !parsed.seq) return + const widest = Math.max( + ...value + .split('\n') + .filter((line) => !line.startsWith('>')) + .map((line) => line.length) + ) + if (widest > columns) onChange(toFasta(parsed.name, parsed.seq, '', columns)) + reflowed.current = true + }, [measured]) + + const runs = useMemo( + () => colourRuns(value, regions, sites, range, parsed.seq.length), + [value, regions, sites, range, parsed.seq.length] + ) + + const syncScroll = () => { + if (area.current && backdrop.current) { + backdrop.current.scrollTop = area.current.scrollTop + backdrop.current.scrollLeft = area.current.scrollLeft + } + } + useEffect(syncScroll, [value]) + + const reportSelection = () => { + const element = area.current + if (!element) return + const start = baseIndexAt(value, element.selectionStart) + const end = baseIndexAt(value, element.selectionEnd) + onSelectRange(end > start ? { start, end } : null) + } + + return ( +
+
+ +