Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions e2e/xlsx-links.spec.ts
Original file line number Diff line number Diff line change
@@ -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: `<hyperlinks><hyperlink ref="A2" r:id="rId1" tooltip="Find it"/><hyperlink ref="A3" location="'Other Sheet'!C5"/></hyperlinks>`,
},
{ name: 'Other Sheet', rows: rows([[1]]) },
],
parts: {
'xl/worksheets/_rels/sheet1.xml.rels': `<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${REL}/hyperlink" Target="https://search.test/?q=1" TargetMode="External"/></Relationships>`,
},
})
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<HTMLElement>('.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([])
})
})
57 changes: 57 additions & 0 deletions src/core/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion src/core/xlsx/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
113 changes: 113 additions & 0 deletions src/core/xlsx/links.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* The links of a cell: the one the file gives it (`<hyperlink>`, 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<SheetData, { key: string; at: (Merge | null)[] }>()

/** 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<CellLink | undefined> {
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<CellLink[]> {
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 })) : []
}
19 changes: 19 additions & 0 deletions src/core/xlsx/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<hyperlink>`), 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 {
Expand Down
Loading