diff --git a/e2e/xlsx-links.spec.ts b/e2e/xlsx-links.spec.ts new file mode 100644 index 0000000..b32506f --- /dev/null +++ b/e2e/xlsx-links.spec.ts @@ -0,0 +1,137 @@ +import { describe, expect, test } from 'bun:test' +import { book, rows } from '../test/xlsx-builder' +import { useBrowser, viewer, type Viewer } from './harness' + +useBrowser() + +const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' + +/** a workbook with an address typed in a cell, links of the file (to a page, to a place) and a plain cell */ +async function open(editable = true) { + const blob = await book({ + sheets: [ + { + name: 'Links', + rows: rows([['https://site.test/page'], ['Search'], ['To C5'], ['plain'], ['mail ann@mail.test or see www.site.test/x.']]), + tail: ``, + }, + { name: 'Other Sheet', rows: rows([[1]]) }, + ], + parts: { + 'xl/worksheets/_rels/sheet1.xml.rels': ``, + }, + }) + const b64 = Buffer.from(await blob.arrayBuffer()).toString('base64') + const v = await viewer( + { src: `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,${b64}`, name: 'links.xlsx', editable }, + { + setup: async (v) => { + await v.ctx.grantPermissions(['clipboard-read', 'clipboard-write']) + // (no page of the tests is on the network) + await v.ctx.route(/\.test\//, (r) => r.fulfill({ body: 'ok', contentType: 'text/plain' })) + }, + }, + ) + return v +} + +const card = (v: Viewer) => v.page.locator('.de-linkcard') + +/** selects a cell: the card of the one selected, over the cells under it, is put away first (Escape) */ +async function select(v: Viewer, ref: string) { + if (await card(v).count()) { + await v.page.keyboard.press('Escape') + await card(v).waitFor({ state: 'detached' }) + } + await v.clickCell(ref) +} + +/** the card of the selected cell, once its links are in */ +async function cardOf(v: Viewer, ref: string) { + await select(v, ref) + await card(v).waitFor({ timeout: 5000 }) + return card(v) +} + +describe('xlsx: links of cells', () => { + test('an address typed in a cell is a link: underlined, in the color of links, only where it is', async () => { + const v = await open() + const look = await v.page.evaluate(() => + [...document.querySelectorAll('.de-xlink')].map((x) => ({ t: x.textContent, deco: getComputedStyle(x).textDecorationLine, color: getComputedStyle(x).color })), + ) + expect(look).toEqual([ + { t: 'https://site.test/page', deco: 'underline', color: 'rgb(17, 85, 204)' }, + { t: 'ann@mail.test', deco: 'underline', color: 'rgb(17, 85, 204)' }, + { t: 'www.site.test/x', deco: 'underline', color: 'rgb(17, 85, 204)' }, + ]) + // the rest of the text is as it was + expect(await v.shown('A5')).toBe('mail ann@mail.test or see www.site.test/x.') + expect(v.errors).toEqual([]) + }) + + test('selecting a cell with a link shows a card under it; it opens the page in a new tab, the selection stays', async () => { + const v = await open() + const c = await cardOf(v, 'A1') + const cell = await v.cellPoint('A1') + const box = (await c.boundingBox())! + expect(box.y).toBeGreaterThan(cell.y) + const a = c.locator('a') + expect(await a.getAttribute('href')).toBe('https://site.test/page') + expect(await a.getAttribute('target')).toBe('_blank') + expect(await a.getAttribute('rel')).toContain('noopener') + const [tab] = await Promise.all([v.ctx.waitForEvent('page'), a.click()]) + await tab.waitForLoadState() + expect(tab.url()).toBe('https://site.test/page') + await tab.close() + expect(await v.page.locator('.de-fx-ref').textContent()).toBe('A1') + // it is over the cells under the one selected: a click there is not one on them + await v.clickCell('A3') + expect(await v.page.locator('.de-fx-ref').textContent()).toBe('A1') + // the keyboard moves the selection, and the card with it: none on a cell without a link + await v.page.keyboard.press('ArrowDown') + await v.page.waitForFunction(() => document.querySelector('.de-linkcard a')?.getAttribute('href') === 'https://search.test/?q=1') + await v.page.keyboard.press('ArrowDown') + await v.page.keyboard.press('ArrowDown') + await card(v).waitFor({ state: 'detached' }) + // Escape puts it away, until another cell is selected + await cardOf(v, 'A1') + await v.page.keyboard.press('Escape') + await card(v).waitFor({ state: 'detached' }) + await v.clickCell('A2') + await card(v).waitFor() + expect(await v.page.locator('.de-fx-ref').textContent()).toBe('A2') + expect(v.errors).toEqual([]) + }) + + test('a link of the file: its hint, copied; one to a place in the workbook goes there', async () => { + const v = await open() + const c = await cardOf(v, 'A2') + expect(await c.locator('a').getAttribute('href')).toBe('https://search.test/?q=1') + expect(await c.locator('.de-linkcard-hint').textContent()).toBe('Find it') + // (the file's link is not the cell's text: it is not edited with it) + expect(await c.locator('button[title="Edit link"]').count()).toBe(0) + await c.locator('button[title="Copy link"]').click() + await v.page.getByText('Link copied').waitFor() + expect(await v.page.evaluate(() => navigator.clipboard.readText())).toBe('https://search.test/?q=1') + const to = await cardOf(v, 'A3') + await to.locator('.de-linkcard-goto').click() + await v.page.waitForFunction(() => document.querySelector('.de-fx-ref')?.textContent === 'C5') + expect(await v.page.locator('[role=tab][aria-selected=true]').textContent()).toBe('Other Sheet') + expect(v.errors).toEqual([]) + }) + + test('the link of a text is edited with the cell; a view that cannot edit shows the card without it', async () => { + const v = await open() + const c = await cardOf(v, 'A1') + await c.locator('button[title="Edit link"]').click() + await v.page.locator('textarea.de-cell-edit').waitFor() + expect(await v.page.locator('textarea.de-cell-edit').inputValue()).toBe('https://site.test/page') + expect(await card(v).count()).toBe(0) + await v.page.keyboard.press('Escape') + const ro = await open(false) + const rc = await cardOf(ro, 'A1') + expect(await rc.locator('button[title="Edit link"]').count()).toBe(0) + expect(await rc.locator('button[title="Copy link"]').count()).toBe(1) + expect(ro.errors).toEqual([]) + }) +}) diff --git a/src/core/url.ts b/src/core/url.ts index 46e7381..5d7be6b 100644 --- a/src/core/url.ts +++ b/src/core/url.ts @@ -22,3 +22,60 @@ export function safeHref(href: string | null | undefined): string | undefined { const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url)?.[1].toLowerCase() return !scheme || SAFE_SCHEMES.has(scheme) ? href : undefined } + +/** a web or mail address written in a text: where it is (`start` ≤ i < `end`), and the link it makes */ +export interface TextLink { + start: number + end: number + href: string +} + +/** what may be an address: a scheme, a www. host, an e-mail address; what ends it is checked after (`trimLink`) */ +const LINKISH = /\b(?:(?:https?|ftps?):\/\/[^\s<>"]+|www\.[^\s<>"]+|mailto:[^\s<>"]+|[\p{L}\p{N}._%+-]+@[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*\.\p{L}{2,}\b)/giu +/** the parts of an address a sentence puts after it: a stop, a comma, quotes */ +const TRAILING = /[.,;:!?'"*_~]$/ + +const count = (s: string, ch: string) => s.split(ch).length - 1 + +/** an address without what the sentence around it put at its end: a stop, a bracket it opened before it */ +function trimLink(s: string): string { + for (;;) { + const last = s[s.length - 1] + if (TRAILING.test(last)) s = s.slice(0, -1) + else if (last === ')' && count(s, ')') > count(s, '(')) s = s.slice(0, -1) + else if (last === ']' && count(s, ']') > count(s, '[')) s = s.slice(0, -1) + else if (last === '}' && count(s, '}') > count(s, '{')) s = s.slice(0, -1) + else return s + } +} + +/** + * The web and mail addresses a text holds, as a reader takes them: `https://…`, `ftp://…`, `www.…` (a web link), + * `mailto:…` and `name@host.tld` (a mail link). What a sentence puts after one (a stop, a closing bracket it did not + * open) is not part of it. At most `max` of them. + */ +export function findLinks(text: string, max = 20): TextLink[] { + // (most texts have none: the look for them is skipped) + if (!text || (text.indexOf(':') < 0 && text.indexOf('@') < 0 && !/www\./i.test(text))) return [] + const out: TextLink[] = [] + LINKISH.lastIndex = 0 + for (let m = LINKISH.exec(text); m && out.length < max; m = LINKISH.exec(text)) { + const s = trimLink(m[0]) + const low = s.toLowerCase() + let href: string + if (/^(?:https?|ftps?):\/\//.test(low)) { + // a host after the scheme + if (!/^[a-z]+:\/\/[^/?#\s]/.test(low)) continue + href = s + } else if (low.startsWith('www.')) { + // a host of two names at least after www. + if (!/^www\.[^./?#\s]+\.[^./?#\s]/.test(low)) continue + href = 'https://' + s + } else if (low.startsWith('mailto:')) { + if (s.length < 8) continue + href = s + } else href = 'mailto:' + s + out.push({ start: m.index, end: m.index + s.length, href }) + } + return out +} diff --git a/src/core/xlsx/editor.ts b/src/core/xlsx/editor.ts index 871c80a..9b96202 100644 --- a/src/core/xlsx/editor.ts +++ b/src/core/xlsx/editor.ts @@ -1472,7 +1472,7 @@ export class XlsxEditor { const cells = at ? [at] : await this.wb.find(sheet, query, opts, 1e9) for (const { r, c } of cells) { const f = d.formulas.get(r * MAX_COL + c) - const raw = opts.formulas && f ? '=' + f : (await this.wb.cell(sheet, r, c))?.value + const raw = opts.formulas && f ? '=' + f : (await this.wb.cell(sheet, r, c, false))?.value if (raw === undefined || (f && !opts.formulas)) continue // (the text to put, as it is: "$&" and "$1" mean nothing here) const next = raw.replace(re, () => by) diff --git a/src/core/xlsx/links.ts b/src/core/xlsx/links.ts new file mode 100644 index 0000000..7ab6b18 --- /dev/null +++ b/src/core/xlsx/links.ts @@ -0,0 +1,113 @@ +/** + * The links of a cell: the one the file gives it (``, to an address outside the file or to a place in the + * workbook), the HYPERLINK function its formula calls, or the web and mail addresses written in its text. + */ +import { findLinks } from '../url' +import { parseFormula, renameSheetInFormula, shiftFormula, type Ast } from './formula' +import { shiftSqref } from './follow' +import type { CellLink, Merge } from './types' +import { parseRange, type SheetData, type XlsxWorkbook } from './workbook' + +/** where the links of the file are now, by sheet: worked out again when rows / columns moved since (`shifts`) */ +const placed = new WeakMap() + +/** the cells each link of the file is on now (null: they were deleted) */ +function linkRanges(d: SheetData): (Merge | null)[] { + const key = JSON.stringify(d.shifts) + const had = placed.get(d) + if (had && had.key === key && had.at.length === d.links.length) return had.at + const at = d.links.map((l) => { + const ref = d.shifts.length ? shiftSqref(l.ref, d.shifts) : l.ref + // (a link is on one range: the first, of a list a file wrote) + const rg = ref ? parseRange(ref.trim().split(/\s+/)[0]) : undefined + return rg && rg.r0 >= 0 && rg.c0 >= 0 && rg.r1 >= rg.r0 && rg.c1 >= rg.c0 ? rg : null + }) + placed.set(d, { key, at }) + return at +} + +/** a place of the workbook as written in a link (`'Sheet 2'!B3`, `A1`, a defined name): its sheet and first cell */ +function placeOf(wb: XlsxWorkbook, text: string, sheet: number, depth = 0): CellLink['goto'] { + let ast: Ast + try { + ast = parseFormula(text.replace(/^#/, '')) + } catch { + return undefined + } + if (ast.type === 'name' && depth === 0) { + // a defined name: the one local to the sheet first, else the workbook's + const defs = wb.names.get(ast.name.toLowerCase()) ?? [] + const def = defs.find((n) => n.local === sheet) ?? defs.find((n) => n.local === undefined) + return def ? placeOf(wb, def.text, sheet, 1) : undefined + } + if (ast.type !== 'ref') return undefined + const { ref } = ast + const at = ref.sheet === undefined ? sheet : wb.sheets.findIndex((s) => s.name.toLowerCase() === ref.sheet!.toLowerCase()) + return at < 0 ? undefined : { sheet: at, r: ref.r0, c: ref.c0 } +} + +/** the place a link names, as it is named now: after the sheets renamed and the rows / columns of its own sheet moved */ +function locationNow(d: SheetData, sheetName: string, text: string): string { + for (const [from, to] of d.renames) text = renameSheetInFormula(text, from, to) + for (const s of d.shifts) text = shiftFormula(text, { sheet: sheetName, formulaSheet: sheetName, ...s }) + return text +} + +/** the link the file gives cell (r, c) of a sheet, if any */ +async function fileLink(wb: XlsxWorkbook, sheet: number, d: SheetData, r: number, c: number): Promise { + if (!d.links.length) return undefined + const ranges = linkRanges(d) + // (the last one of the file wins, as in Excel, where two are on a cell) + let i = ranges.length - 1 + for (; i >= 0; i--) { + const g = ranges[i] + if (g && r >= g.r0 && r <= g.r1 && c >= g.c0 && c <= g.c1) break + } + if (i < 0) return undefined + const l = d.links[i] + const info = wb.sheets[sheet] + const out: CellLink = { from: 'file' } + if (l.rid) { + const rel = (await wb.pkg.rels(info.path).catch(() => undefined))?.get(l.rid) + // (an address outside the file: a part of the package is none to open) + if (rel?.external && rel.target) out.href = l.location ? `${rel.target}#${l.location}` : rel.target + } + if (!out.href && l.location) { + out.location = locationNow(d, info.name, l.location) + out.goto = placeOf(wb, out.location, sheet) + } + if (l.tooltip) out.tooltip = l.tooltip + return out.href || out.location ? out : undefined +} + +/** the link a formula makes calling HYPERLINK with a text: `=HYPERLINK("https://…", "name")`, `=HYPERLINK("#Sheet2!A1")` */ +function formulaLink(wb: XlsxWorkbook, sheet: number, formula: string): CellLink | undefined { + if (!/HYPERLINK\s*\(/i.test(formula)) return undefined + let ast: Ast + try { + ast = parseFormula(formula.replace(/^=/, '')) + } catch { + return undefined + } + if (ast.type !== 'call' || ast.name.toUpperCase().replace(/^_XLFN\./, '') !== 'HYPERLINK') return undefined + const to = ast.args[0] + if (to?.type !== 'str' || !to.value.trim()) return undefined + const target = to.value.trim() + if (target.startsWith('#')) { + const location = target.slice(1) + return { from: 'formula', location, goto: placeOf(wb, location, sheet) } + } + return { from: 'formula', href: target } +} + +/** + * The links of cell (r, c): the file's, else its formula's HYPERLINK, else the addresses its text holds (`text`: its + * value, when it is a text). None: an empty list. + */ +export async function linksAt(wb: XlsxWorkbook, sheet: number, d: SheetData, r: number, c: number, formula: string | undefined, text: string | undefined): Promise { + const own = await fileLink(wb, sheet, d, r, c) + if (own) return [own] + const f = formula ? formulaLink(wb, sheet, formula) : undefined + if (f) return [f] + return text ? findLinks(text, 5).map((l) => ({ from: 'text' as const, href: l.href })) : [] +} diff --git a/src/core/xlsx/types.ts b/src/core/xlsx/types.ts index 77a7f1f..88ab9e9 100644 --- a/src/core/xlsx/types.ts +++ b/src/core/xlsx/types.ts @@ -104,6 +104,25 @@ export interface CellDetail { value: string formula?: string type: string + /** where the cell links to, when it does (see `CellLink`) */ + links?: CellLink[] +} + +/** + * A link of a cell: one the file gives it (``), the HYPERLINK function of its formula, or a web or mail + * address written in its text. It leads to an address (`href`), to a place in the workbook (`location`), or both. + */ +export interface CellLink { + /** a web, mail or phone address as the file or the text has it; another file's path when it has no scheme */ + href?: string + /** a place in the workbook as the file names it: a cell or range (`'Sheet 2'!A1`), a defined name */ + location?: string + /** that place, when it is a sheet of the workbook: its first cell */ + goto?: { sheet: number; r: number; c: number } + /** the hint the file gives for it */ + tooltip?: string + /** a link of the file, the HYPERLINK function of the cell's formula, or an address in its text */ + from: 'file' | 'formula' | 'text' } export interface CellInput { diff --git a/src/core/xlsx/workbook.ts b/src/core/xlsx/workbook.ts index 1c20af7..1d805b9 100644 --- a/src/core/xlsx/workbook.ts +++ b/src/core/xlsx/workbook.ts @@ -11,6 +11,7 @@ import { parseSheetStyles, type SheetStyles } from './styles' import { expandShared, formulaAt } from './structure' import { stripFunctionPrefixes, type PivotInfo, type TableInfo } from './formula' import { readPivots } from './pivot' +import { linksAt } from './links' import { isoToSerial } from './formula/dates' import type { Shift } from './follow' import { MAX_COL, MAX_ROWS, MAX_COL_WIDTH, MAX_ROW_HEIGHT_PT, ooxmlCapped, ooxmlInt, ooxmlNumber } from './limits' @@ -154,6 +155,11 @@ export class SheetData { maxCol = -1 formulas = new Map() merges: Merge[] = [] + /** + * The links the file gives its cells (``), as read: where each is now is where `shifts` moved its `ref`, + * as the sheet's XML is when it is saved (see `linksAt`). + */ + links: FileLink[] = [] colInfo: ColInfo[] = [] defaultColW = 64 defaultRowH = 20 @@ -164,6 +170,17 @@ export class SheetData { loading?: Promise } +/** a `` of a sheet: the cells it is on, its relationship (an address outside the file), a place in the workbook */ +export interface FileLink { + ref: string + rid?: string + location?: string + tooltip?: string +} + +/** links of a sheet past which the rest are not read (Excel keeps 65,530 at most) */ +const MAX_LINKS = 100_000 + /** attributes of / the model does not edit but a rewrite of the element must keep */ const ROW_KEEP = ['s', 'customFormat', 'outlineLevel', 'collapsed', 'thickTop', 'thickBot', 'ph'] const COL_KEEP = ['style', 'outlineLevel', 'collapsed', 'bestFit', 'phonetic'] @@ -320,6 +337,9 @@ class SheetHandler implements SaxHandler { } return } + case 'hyperlink': + if (a.ref && this.d.links.length < MAX_LINKS) this.d.links.push({ ref: a.ref, rid: a['r:id'] || undefined, location: a.location || undefined, tooltip: a.tooltip || undefined }) + return true case 'extLst': case 'conditionalFormatting': case 'dataValidations': @@ -1048,23 +1068,29 @@ export class XlsxWorkbook { return out } - async cell(sheet: number, r: number, c: number): Promise { + /** what cell (r, c) holds, and where it links to (`withLinks`) */ + async cell(sheet: number, r: number, c: number, withLinks = true): Promise { const d = this.sheetsData.get(sheet) if (d) await this.ensure(d, r, r) const row = d?.rows[r] // as it is typed: without the prefixes the file gives the functions newer than its format const text = d && formulaAt(d, r * MAX_COL + c) const formula = text && stripFunctionPrefixes(text) - if (!row) return formula ? { value: '', formula: '=' + formula, type: 'formula' } : undefined - for (let k = 0; k < row.length; k += 4) { + let out: CellDetail | undefined = formula ? { value: '', formula: '=' + formula, type: 'formula' } : undefined + let t = T_EMPTY + for (let k = 0; row && k < row.length; k += 4) { if (row[k] !== c) continue - const t = row[k + 1] as number + t = row[k + 1] as number const v = row[k + 2] const value = t === T_SST ? this.sst[v as number] ?? '' : t === T_BOOL ? (v ? 'TRUE' : 'FALSE') : String(v) const type = ['number', 'string', 'string', 'boolean', 'error', 'date', 'empty'][t] - return { value, formula: formula ? '=' + formula : undefined, type } + out = { value, formula: formula ? '=' + formula : undefined, type } + break } - return formula ? { value: '', formula: '=' + formula, type: 'formula' } : undefined + if (!d || !withLinks) return out + const links = await linksAt(this, sheet, d, r, c, formula || undefined, t === T_SST || t === T_STR ? out?.value : undefined) + if (!links.length) return out + return { ...(out ?? { value: '', type: 'empty' }), links } } unload(sheet: number) { diff --git a/src/react/strings/de.ts b/src/react/strings/de.ts index 8cf94c5..e04d7d0 100644 --- a/src/react/strings/de.ts +++ b/src/react/strings/de.ts @@ -171,6 +171,8 @@ export const de: Strings = { editLink: 'Link bearbeiten', linkPlaceholder: 'https://…', openLink: 'Link öffnen', + copyLink: 'Link kopieren', + linkCopied: 'Link kopiert', editLinkMenu: 'Link bearbeiten…', insertLinkMenu: 'Link einfügen…', removeLink: 'Link entfernen', diff --git a/src/react/strings/en.ts b/src/react/strings/en.ts index 911801d..56748d1 100644 --- a/src/react/strings/en.ts +++ b/src/react/strings/en.ts @@ -177,6 +177,8 @@ export const en = { editLink: 'Edit link', linkPlaceholder: 'https://…', openLink: 'Open link', + copyLink: 'Copy link', + linkCopied: 'Link copied', editLinkMenu: 'Edit link…', insertLinkMenu: 'Insert link…', removeLink: 'Remove link', diff --git a/src/react/styles.css b/src/react/styles.css index 3b74e35..c774f62 100644 --- a/src/react/styles.css +++ b/src/react/styles.css @@ -87,6 +87,8 @@ --de-page: #fff; --de-page-ink: #000; --de-sheet-ink: #1d2127; + /* a web or mail address in a cell's text */ + --de-sheet-link: #1155cc; --de-skeleton: #eef0f2; --de-ph-border: #b8bec6; --de-ph-a: #f6f7f9; @@ -1106,6 +1108,36 @@ .de-fhint { padding: 6px 10px; font-family: var(--de-font-mono); } .de-fhint .de-fsug-desc { font-family: var(--de-font); } .de-fhint b { color: var(--de-accent); } +/* XLSX: the addresses in a cell's text, and the card of the selected cell's links (under it) */ +.de-xlink { text-decoration: underline; color: var(--de-sheet-link); } +.de-xlink-own { color: inherit; } +.de-linkcard { + position: absolute; + z-index: 30; + box-sizing: border-box; + padding: 6px 4px 6px 10px; + background: var(--de-pop); + border: 1px solid var(--de-border); + border-radius: 10px; + box-shadow: var(--de-pop-shadow); + font: 13px/1.4 var(--de-font); + color: var(--de-text); + text-align: left; + white-space: normal; + cursor: default; +} +.de-linkcard-row { display: flex; align-items: center; gap: 8px; min-height: 36px; } +.de-linkcard-icon { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; background: var(--de-hover-soft); color: var(--de-muted); } +.de-linkcard-text { flex: 1; min-width: 0; } +.de-linkcard-text > a, +.de-linkcard-text > span, +.de-linkcard-goto { display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; } +.de-linkcard-text > a, +.de-linkcard-goto { color: var(--de-accent); text-decoration: none; } +.de-linkcard-text > a:hover, +.de-linkcard-goto:hover { text-decoration: underline; } +.de-linkcard-goto { padding: 0; border: 0; background: none; font: inherit; font-weight: 500; cursor: pointer; text-align: left; } +.de-linkcard-hint { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--de-muted); font-size: 12px; } /* docx: picture selection, outline, dialogs */ .de-img-sel { position: absolute; z-index: 4; border: 1.5px solid var(--de-accent); pointer-events: none; } diff --git a/src/react/theme.ts b/src/react/theme.ts index 4663396..2e9b7d3 100644 --- a/src/react/theme.ts +++ b/src/react/theme.ts @@ -26,7 +26,7 @@ export const THEME_TOKENS = [ 'tip-bg', 'tip-ink', 'present-bg', 'present-ink', 'status-idle', 'status-live', 'status-busy', 'status-error', // paper: pages, slides and sheets (the same in both modes, as documents keep their own colors) - 'page', 'page-ink', 'sheet-ink', 'skeleton', 'ph-border', 'ph-a', 'ph-b', 'ph-ink', 'ph-outline', 'ph-hint', + 'page', 'page-ink', 'sheet-ink', 'sheet-link', 'skeleton', 'ph-border', 'ph-a', 'ph-b', 'ph-ink', 'ph-outline', 'ph-hint', // source editor and code view (Markdown, HTML, diagrams, source files) 'src-bg', 'src-gutter', 'src-sel', 'src-font', 'src-comment', 'src-keyword', 'src-string', 'src-operator', 'src-number', 'src-heading', 'src-attr', 'src-tag', 'src-meta', 'src-function', 'src-type', diff --git a/src/react/xlsx/XlsxView.tsx b/src/react/xlsx/XlsxView.tsx index 93b27b1..c6ed79c 100644 --- a/src/react/xlsx/XlsxView.tsx +++ b/src/react/xlsx/XlsxView.tsx @@ -1,5 +1,5 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type MutableRefObject, type ReactNode } from 'react' -import type { BookOp, CellDetail, ClipCell, CellInput, CellOut, FindMatch, FindOptions, FmtPatch, Merge, Range, SheetOp, SheetProgress, TextRun, WorkbookMeta, XlsxClip, XlsxEditResult } from '../../core/xlsx/types' +import type { BookOp, CellDetail, CellLink, ClipCell, CellInput, CellOut, FindMatch, FindOptions, FmtPatch, Merge, Range, SheetOp, SheetProgress, TextRun, WorkbookMeta, XlsxClip, XlsxEditResult } from '../../core/xlsx/types' import { parseTsv, shiftedClip, tsvCell } from '../../core/xlsx/clip' import { colName, MAX_ROWS } from '../../core/xlsx/workbook' import { detectSeparator, parseCsv } from '../../core/convert' @@ -18,7 +18,8 @@ import { ContextMenu, MOD, type MenuItem } from '../common/ContextMenu' import { ConfirmDialog, Toast } from '../common/Dialog' import { FindBar } from '../docx/FindBar' import { XlsxToolbar, type MergeMode } from './XlsxToolbar' -import { Icon } from '../edit/Toolbar' +import { Btn, Icon } from '../edit/Toolbar' +import { findLinks, safeHref, type TextLink } from '../../core/url' import { useLocale } from '../common/locale' import { numberText } from '../../core/number-input' import { Axis } from './axis' @@ -698,6 +699,95 @@ function runCss(r: TextRun): CSSProperties | undefined { return css } +/** a cell's text with the addresses in it underlined: in the color of links, unless the cell has a color of its own */ +function linked(text: string, links: TextLink[], own: boolean): ReactNode[] { + const out: ReactNode[] = [] + let at = 0 + for (const l of links) { + if (l.start > at) out.push(text.slice(at, l.start)) + out.push( + + {text.slice(l.start, l.end)} + , + ) + at = l.end + } + if (at < text.length) out.push(text.slice(at)) + return out +} + +/** the address of a link a click may open: one with a scheme that runs no code (not another file's path, not `javascript:`) */ +function openable(l: CellLink): string | undefined { + const href = safeHref(l.href) + return href && /^[a-z][a-z0-9+.-]*:/i.test(href) ? href : undefined +} + +/** the width of the card of a cell's links */ +const LINK_CARD_W = 340 + +/** + * The links of the selected cell, under it (as in Google Sheets): each opens (a web page in a new tab, a mail to + * write, a place in the workbook), and is copied; a link of the text or of a formula is edited with the cell. No icon + * of the site: one would be fetched from the site's own server, which would learn the sheet was looked at. + */ +function LinkCard(props: { + links: CellLink[] + style: CSSProperties + /** the sheets a place may be on (a hidden one is not gone to) */ + sheets: WorkbookMeta['sheets'] + onGoto: (to: NonNullable) => void + onCopy: (text: string) => void + /** the cell can be edited: the link of its text or formula with it */ + onEdit?: () => void +}) { + const str = useStrings() + return ( +
{ + e.stopPropagation() + e.preventDefault() + }} + onDoubleClick={(e) => e.stopPropagation()} + onContextMenu={(e) => e.stopPropagation()} + > + {props.links.map((l, i) => { + const href = openable(l) + const text = l.href ? l.href.replace(/^mailto:/i, '') : (l.location ?? '') + const to = l.goto && !props.sheets[l.goto.sheet]?.hidden ? l.goto : undefined + return ( +
+ + + +
+ {href ? ( + + {text} + + ) : to ? ( + + ) : ( + {text} + )} + {l.tooltip &&
{l.tooltip}
} +
+ props.onCopy(l.href ?? l.location ?? '')} /> + {props.onEdit && l.from !== 'file' && } +
+ ) + })} +
+ ) +} + /** the tallest a row grows to show its text (Excel's limit: 409 pt) */ const MAX_FIT_ROW = 545 @@ -785,6 +875,18 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g const [detailState, setDetail] = useState<{ r: number; c: number; d?: CellDetail } | null>(null) const detail = detailState && detailState.r === act.r && detailState.c === act.c ? detailState.d : undefined const [detailTick, setDetailTick] = useState(0) + /** + * the card of the selected cell's links is put away: until a cell is selected (the one selected when the sheet + * shows has none, it was not picked), and again after Escape until another one is, or a click + */ + const [linkOff, setLinkOff] = useState(true) + const linkCell = useRef(`${act.r}:${act.c}`) + useEffect(() => { + const k = `${act.r}:${act.c}` + if (linkCell.current === k) return + linkCell.current = k + setLinkOff(false) + }, [act.r, act.c]) const dragging = useRef(false) const editRef = useRef(null) const hlRef = useRef(null) @@ -1058,9 +1160,15 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g const w = textWidth(text, css, meta.baseFont as Record, basePx) if (w > cw - 6) shrink = { transform: `scale(${Math.max(0.2, (cw - 6) / w)})`, transformOrigin: justify === 'flex-end' ? 'right center' : justify === 'center' ? 'center' : 'left center', whiteSpace: 'nowrap', flex: 'none' } } + // the web and mail addresses of a text: links, as the card under the cell says when it is selected + const links = kind === 0 && !runs && text ? findLinks(text) : undefined return (
- {text && {runs ? runs.map((x, i) => {x.t}) : text}} + {text && ( + + {runs ? runs.map((x, i) => {x.t}) : links?.length ? linked(text, links, !!(css.color || color)) : text} + + )}
) } @@ -1290,6 +1398,23 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g scrollIntoView(g.r, g.c) }, [gotoN]) // eslint-disable-line react-hooks/exhaustive-deps + /** the cell a link of the workbook leads to: selected and in view, on its sheet */ + const gotoPlace = (to: { sheet: number; r: number; c: number }) => { + const r = Math.min(Math.max(0, to.r), MAX_ROW) + const c = Math.min(Math.max(0, to.c), MAX_COL) + if (to.sheet === sheet) { + setSel({ ar: r, ac: c, fr: r, fc: c }) + scrollIntoView(r, c) + focusGrid() + return + } + const t = store.sheet(to.sheet) + t.sel = { ar: r, ac: c, fr: r, fc: c } + t.goto = { r, c, n: (t.goto?.n ?? 0) + 1 } + store.focusGrid = true + onSheet(to.sheet) + } + const cellAt = (clientX: number, clientY: number, el: HTMLElement) => { const b = el.getBoundingClientRect() const x = clientX - b.left - HW @@ -1906,6 +2031,7 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g setPainter(null) return } + if (e.key === 'Escape' && linkCard) setLinkOff(true) const pageRows = Math.max(1, Math.floor(mainH / rowAxis.def) - 1) const moves: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1], @@ -2078,6 +2204,7 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g else if (e.shiftKey) setSelState({ ...sel, fr: r, fc: c, whole: undefined }) else { setSel({ ar: r, ac: c, fr: r, fc: c }) + setLinkOff(false) // a cell with a comment shows its thread const id = cmAt(r, c) if (id) cm?.select(id, false) @@ -2524,6 +2651,38 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g return top + 200 > size.h && (edStyle.top as number) > 200 ? { left: edStyle.left as number, bottom: size.h - (edStyle.top as number) + 2 } : { left: edStyle.left as number, top } })() + // the links of the selected cell: a card under it (above it, where there is no room under it) + let linkCard: ReactNode = null + const cellLinks = !edit && oneCell && !sel.whole && !linkOff && !ctx && !resizing && !fillTo ? detail?.links : undefined + if (cellLinks?.length) { + const b = cellBox(act.r, act.c) + // (a cell scrolled under the frozen rows / columns, or out of the view, has none) + const shown = b.x + b.w > HW + (act.c >= fc ? fw : 0) && b.x < size.w && b.y + b.h > HH + (act.r >= fr ? fh : 0) && b.y < size.h + if (shown) { + // (no wider than the view: a phone's is narrower than the card) + const w = Math.max(160, Math.min(LINK_CARD_W, size.w - HW - 8)) + const left = Math.max(HW, Math.min(b.x, size.w - w - 8)) + const tall = 12 + cellLinks.length * 44 + const pos: CSSProperties = b.y + b.h + 4 + tall > size.h && b.y - HH > tall ? { left, bottom: size.h - b.y + 4 } : { left, top: b.y + b.h + 4 } + linkCard = ( + { + void navigator.clipboard?.writeText(text).then( + () => setToast(str.edit.linkCopied), + () => {}, + ) + focusGrid() + }} + onEdit={editable ? () => void startEdit() : undefined} + /> + ) + } + } + return ( <>
@@ -2664,6 +2823,7 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g {assist}
)} + {linkCard} diff --git a/test/xlsx-links.test.ts b/test/xlsx-links.test.ts new file mode 100644 index 0000000..ea2784e --- /dev/null +++ b/test/xlsx-links.test.ts @@ -0,0 +1,143 @@ +/** + * Links of cells: the file's ``s, the HYPERLINK function, and the web / mail addresses written in a text. + */ +import { describe, expect, test } from 'bun:test' +import { findLinks } from '../src/core/url' +import { at, book, openBook, rows } from './xlsx-builder' + +const hrefs = (text: string) => findLinks(text).map((l) => [text.slice(l.start, l.end), l.href]) + +describe('findLinks', () => { + test('web addresses with a scheme or www., mail addresses with mailto: or as name@host', () => { + expect(hrefs('https://www.google.com/')).toEqual([['https://www.google.com/', 'https://www.google.com/']]) + expect(hrefs('see http://a.example/x?q=1#f and ftp://files.example/a')).toEqual([ + ['http://a.example/x?q=1#f', 'http://a.example/x?q=1#f'], + ['ftp://files.example/a', 'ftp://files.example/a'], + ]) + expect(hrefs('www.example.org/path')).toEqual([['www.example.org/path', 'https://www.example.org/path']]) + expect(hrefs('mail an.ton+x@mail.example.de bitte')).toEqual([['an.ton+x@mail.example.de', 'mailto:an.ton+x@mail.example.de']]) + expect(hrefs('mailto:a@b.co')).toEqual([['mailto:a@b.co', 'mailto:a@b.co']]) + }) + + test('what a sentence puts after an address is not part of it', () => { + expect(hrefs('Go to https://example.com/a.')).toEqual([['https://example.com/a', 'https://example.com/a']]) + expect(hrefs('(see https://example.com/a), then')).toEqual([['https://example.com/a', 'https://example.com/a']]) + expect(hrefs('https://en.wikipedia.org/wiki/Foo_(bar)')).toEqual([['https://en.wikipedia.org/wiki/Foo_(bar)', 'https://en.wikipedia.org/wiki/Foo_(bar)']]) + expect(hrefs('"https://example.com"')).toEqual([['https://example.com', 'https://example.com']]) + }) + + test('no address: nothing', () => { + for (const t of ['', 'plain text', '12:30', 'https://', 'www.', 'www.example', 'a@b', 'x@localhost', 'Ratio 1:2', 'javascript:alert(1)', 'xhttps://a.b']) + expect(hrefs(t), t).toEqual([]) + }) +}) + +const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' +const linked = (sheetRels: string, tail: string, more: Partial[0]> = {}) => + book({ + sheets: [ + { name: 'Data', rows: rows([['Google', 'Two'], ['To B3', 'x'], ['plain']]), tail }, + { name: 'Other Sheet', rows: rows([[1]]) }, + ], + parts: { 'xl/worksheets/_rels/sheet1.xml.rels': `${sheetRels}` }, + ...more, + }) + +const linksOf = async (o: Awaited>, sheet: number, ref: string) => { + const { r, c } = at(ref) + return ((await o.engine.call('xlsx.cell', [sheet, r, c])) as { links?: unknown[] } | undefined)?.links +} + +describe('xlsx: the links of a cell', () => { + test('a link of the file to a web address, with its hint; one to a place in the workbook', async () => { + const o = await openBook( + await linked( + ``, + ``, + ), + ) + expect(await linksOf(o, 0, 'A1')).toEqual([{ from: 'file', href: 'https://www.google.com/', tooltip: 'Search' }]) + expect(await linksOf(o, 0, 'A2')).toEqual([{ from: 'file', location: "'Other Sheet'!B3", goto: { sheet: 1, r: 2, c: 1 } }]) + expect(await linksOf(o, 0, 'A3')).toBeUndefined() + // the cell's value is told as before + expect(((await o.engine.call('xlsx.cell', [0, 0, 0])) as { value: string }).value).toBe('Google') + }) + + test('a link on a range is on each of its cells, an empty one too; a fragment goes with the address', async () => { + const o = await openBook( + await linked( + ``, + ``, + ), + ) + for (const ref of ['B1', 'B2', 'C1', 'C2']) expect(await linksOf(o, 0, ref), ref).toEqual([{ from: 'file', href: 'https://example.com/page#part' }]) + expect(await linksOf(o, 0, 'D1')).toBeUndefined() + }) + + test('a link follows its cell when rows are inserted or deleted, and goes with it', async () => { + const o = await openBook( + await linked(``, ``), + ) + await o.engine.call('xlsx.sheetOp', [0, { op: 'insertRows', at: 0, n: 2 }]) + expect(await linksOf(o, 0, 'A2')).toBeUndefined() + expect(await linksOf(o, 0, 'A4')).toEqual([{ from: 'file', href: 'https://example.com/' }]) + await o.engine.call('xlsx.undo', []) + expect(await linksOf(o, 0, 'A2')).toEqual([{ from: 'file', href: 'https://example.com/' }]) + await o.engine.call('xlsx.sheetOp', [0, { op: 'deleteRows', at: 1, n: 1 }]) + expect(await linksOf(o, 0, 'A2')).toBeUndefined() + }) + + test('the place a link names follows a renamed sheet; a defined name leads to its cell', async () => { + const o = await openBook( + await linked('', ``, { + names: `'Other Sheet'!$D$7`, + }), + ) + await o.engine.call('xlsx.bookOp', [{ op: 'rename', index: 1, name: 'Renamed' }]) + expect(await linksOf(o, 0, 'A1')).toEqual([{ from: 'file', location: 'Renamed!C5', goto: { sheet: 1, r: 4, c: 2 } }]) + expect(await linksOf(o, 0, 'B1')).toEqual([{ from: 'file', location: 'Target', goto: { sheet: 1, r: 6, c: 3 } }]) + }) + + test('a link to another file or of an unknown relationship: shown as it is, with no place to go', async () => { + const o = await openBook( + await linked(``, ``), + ) + expect(await linksOf(o, 0, 'A1')).toEqual([{ from: 'file', href: 'other.xlsx' }]) + // (a relationship the file does not have: no link, the text of the cell is looked at) + expect(await linksOf(o, 0, 'B1')).toBeUndefined() + }) + + test('the HYPERLINK function of a formula', async () => { + const o = await openBook( + await book({ + sheets: [ + { name: 'S', rows: rows([[{ f: 'HYPERLINK("https://example.com/a","Example")', v: 'Example' }, { f: 'HYPERLINK("#S!C3","Go")', v: 'Go' }, { f: 'HYPERLINK(A3)', v: 'x' }], [], ['https://example.com/b']]) }, + ], + }), + ) + expect(await linksOf(o, 0, 'A1')).toEqual([{ from: 'formula', href: 'https://example.com/a' }]) + expect(await linksOf(o, 0, 'B1')).toEqual([{ from: 'formula', location: 'S!C3', goto: { sheet: 0, r: 2, c: 2 } }]) + // (not a text: no link told; its value is not one either) + expect(await linksOf(o, 0, 'C1')).toBeUndefined() + }) + + test('the addresses written in a text, typed or read', async () => { + const o = await openBook(await book({ sheets: [{ name: 'S', rows: rows([['see www.example.org.', 'a@b.example', 12, 'none here']]) }] })) + expect(await linksOf(o, 0, 'A1')).toEqual([{ from: 'text', href: 'https://www.example.org' }]) + expect(await linksOf(o, 0, 'B1')).toEqual([{ from: 'text', href: 'mailto:a@b.example' }]) + expect(await linksOf(o, 0, 'C1')).toBeUndefined() + expect(await linksOf(o, 0, 'D1')).toBeUndefined() + await o.set(0, 'C1', 'https://example.com/x') + expect(await linksOf(o, 0, 'C1')).toEqual([{ from: 'text', href: 'https://example.com/x' }]) + }) + + test('a link of the file is saved where its cell is', async () => { + const o = await openBook( + await linked(``, ``), + ) + await o.engine.call('xlsx.sheetOp', [0, { op: 'insertRows', at: 0, n: 1 }]) + const xml = await (await o.save()).text('xl/worksheets/sheet1.xml') + expect(xml).toContain('') + expect(await linksOf(o, 0, 'A3')).toEqual([{ from: 'file', href: 'https://example.com/' }]) + }) +})