playground

package module
v0.0.0-...-1b85559 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: BSD-3-Clause Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package playground is a PDF editor that runs in a browser tab: a command ribbon, the page you are on, and a strip of page thumbnails beside it.

⛔ NOTHING IS UPLOADED, AND THAT IS A PROPERTY OF THE BUILD rather than a promise about our conduct: the whole tool is one WebAssembly module and a static page, and there is no endpoint to send a file to.

What is where

doc.go        the document and what may be done to it — no widgets here
actions.go    one toolkit.Action per command, the single source of truth
ribbon.go     the tabs and groups those actions are surfaced in
thumbs.go     the thumbnails, drawn when the strip asks and not before
scene.go      the widget tree

The split is the MVVM one this fleet uses everywhere a boundary is crossed: doc.go knows nothing about go-widgets, and scene.go knows nothing about go-pdfkit. A command is reached from the ribbon, from the keyboard and (one day) from a palette through the SAME Action, so the three cannot drift.

Index

Constants

View Source
const MaxPDF = 64 << 20

MaxPDF is how large a file may be. The whole document is held in the tab's memory, parsed, and held again as pages, so the ceiling is on what arrives rather than on what it becomes.

View Source
const MaxUndo = 20

MaxUndo is how many steps back the editor remembers.

⛔ Each step is a WHOLE SERIALISED DOCUMENT, because that is what ops works in, so this is a memory budget and not a preference: twenty states of a forty-megabyte scan is most of a browser tab. Small on purpose.

Variables

View Source
var Commands = []Command{

	{
		ID: "page.rotate.right", Label: "Rotate right", NeedsDoc: true,
		Tip: "Turn this page a quarter turn clockwise.",
		Run: onSpec(ThisPage, func(o *ops.Doc, spec string) error { return o.Rotate(spec, 90) }),
	},
	{
		ID: "page.rotate.left", Label: "Rotate left", NeedsDoc: true,
		Tip: "Turn this page a quarter turn anticlockwise.",
		Run: onSpec(ThisPage, func(o *ops.Doc, spec string) error { return o.Rotate(spec, -90) }),
	},
	{
		ID: "page.rotate.all", Label: "Rotate every page", NeedsDoc: true,
		Tip: "Turn the whole document a quarter turn clockwise.",
		Run: onSpec(AllPages, func(o *ops.Doc, spec string) error { return o.Rotate(spec, 90) }),
	},
	{
		ID: "page.delete", Label: "Delete page", NeedsDoc: true,
		Tip: "Remove the page being shown.",
		Run: onSpec(ThisPage, func(o *ops.Doc, spec string) error { return o.Delete(spec) }),
	},
	{
		ID: "page.insert", Label: "Insert blank", NeedsDoc: true,
		Tip: "Put an empty page in after this one.",
		Run: func(d *Doc) error {
			return d.Do(func(o *ops.Doc) error { return o.InsertBlank(d.Page()) })
		},
	},
	{
		ID: "page.move.up", Label: "Move earlier", NeedsDoc: true,
		Tip: "Swap this page with the one before it.",

		Run: func(d *Doc) error {
			if d == nil || d.doc == nil {
				return ErrNoDocument
			}
			if d.Page() <= 1 {
				return nil
			}
			return d.Do(func(o *ops.Doc) error { return o.Move(d.Page(), d.Page()-1) })
		},
	},
	{
		ID: "page.move.down", Label: "Move later", NeedsDoc: true,
		Tip: "Swap this page with the one after it.",
		Run: func(d *Doc) error {
			if d == nil || d.doc == nil {
				return ErrNoDocument
			}
			if d.Page() >= d.PageCount() {
				return nil
			}
			return d.Do(func(o *ops.Doc) error { return o.Move(d.Page(), d.Page()+1) })
		},
	},
	{
		ID: "page.select", Label: "Keep only…", NeedsDoc: true,
		Tip: "Throw away every page but the ones named.",
		Ask: &Ask{
			Title:   "Keep only these pages",
			Prompt:  "Which pages — 1, 2-4, 1,3-5, all, odd, even",
			Default: "1-2",
		},
		RunWith: func(d *Doc, spec string) error {
			return d.Do(func(o *ops.Doc) error { return o.Select(spec) })
		},
	},
	{
		ID: "page.delete.range", Label: "Delete…", NeedsDoc: true,
		Tip: "Remove the pages named, rather than only the one on screen.",
		Ask: &Ask{
			Title:   "Delete pages",
			Prompt:  "Which pages — 1, 2-4, 1,3-5, odd, even",
			Default: "1",
		},
		RunWith: func(d *Doc, spec string) error {
			return d.Do(func(o *ops.Doc) error { return o.Delete(spec) })
		},
	},
	{
		ID: "page.reverse", Label: "Reverse order", NeedsDoc: true,
		Tip: "Put the last page first and the first page last.",
		Run: simple(func(o *ops.Doc) error { o.Reverse(); return nil }),
	},

	{
		ID: "layout.nup2", Label: "Two to a sheet", NeedsDoc: true,
		Tip: "Lay the pages out two to a sheet, as for printing.",
		Run: simple(func(o *ops.Doc) error { return o.NUp(2) }),
	},
	{
		ID: "layout.nup4", Label: "Four to a sheet", NeedsDoc: true,
		Tip: "Lay the pages out four to a sheet.",
		Run: simple(func(o *ops.Doc) error { return o.NUp(4) }),
	},
	{
		ID: "layout.nup", Label: "N to a sheet…", NeedsDoc: true,
		Tip: "Lay the pages out however many to a sheet you ask for.",
		Ask: &Ask{
			Title:   "Pages to a sheet",
			Prompt:  "How many pages on each sheet",
			Default: "2",
		},
		RunWith: func(d *Doc, s string) error {
			n, err := strconv.Atoi(strings.TrimSpace(s))
			if err != nil {

				return fmt.Errorf("%q is not a number of pages", s)
			}
			return d.Do(func(o *ops.Doc) error { return o.NUp(n) })
		},
	},
	{
		ID: "layout.booklet", Label: "Booklet", NeedsDoc: true,
		Tip: "Order the pages so that folding the printed stack makes a booklet.",
		Run: simple(func(o *ops.Doc) error { return o.Booklet() }),
	},
	{
		ID: "layout.divide", Label: "Split in two", NeedsDoc: true,
		Tip: "Cut every sheet down the middle into two pages.",
		Run: simple(func(o *ops.Doc) error { return o.Divide(2, 1) }),
	},
	{
		ID: "layout.onepage", Label: "One long page", NeedsDoc: true,
		Tip: "Join every page into a single tall one.",
		Run: simple(func(o *ops.Doc) error { return o.OnePage() }),
	},

	{
		ID: "doc.watermark", Label: "Watermark", NeedsDoc: true,
		Tip: "Write a word across every page.",
		Ask: &Ask{
			Title:   "Watermark",
			Prompt:  "What to write across every page",
			Default: "DRAFT",
		},
		RunWith: func(d *Doc, text string) error {
			return d.Do(func(o *ops.Doc) error { return o.Watermark(string(AllPages), text) })
		},
	},
	{
		ID: "doc.numbers", Label: "Page numbers", NeedsDoc: true,
		Tip: "Number the pages along the foot.",
		Ask: &Ask{
			Title:   "Page numbers",
			Prompt:  "The format — %d is the page number",
			Default: "%d",
		},
		RunWith: func(d *Doc, format string) error {
			return d.Do(func(o *ops.Doc) error { return o.PageNumbers(string(AllPages), format) })
		},
	},
	{
		ID: "doc.flatten", Label: "Flatten", NeedsDoc: true,
		Tip: "Turn form fields and annotations into ordinary page content.",
		Run: simple(func(o *ops.Doc) error { o.Flatten(); return nil }),
	},
	{
		ID: "doc.sanitize", Label: "Sanitise", NeedsDoc: true,
		Tip: "Strip scripts, embedded files and anything else that can act.",
		Run: simple(func(o *ops.Doc) error { o.Sanitize(); return nil }),
	},
	{
		ID: "doc.compress", Label: "Compress", NeedsDoc: true,
		Tip: "Make the file smaller without changing what it draws.",
		Run: simple(func(o *ops.Doc) error { o.Compress(); return nil }),
	},
	{
		ID: "doc.deskew", Label: "Straighten", NeedsDoc: true,
		Tip: "Measure how far each scanned page leans and turn it back.",
		Run: simple(func(o *ops.Doc) error { _, err := o.Deskew(ops.DeskewOptions{}); return err }),
	},
	{
		ID: "doc.dropblank", Label: "Drop blank pages", NeedsDoc: true,
		Tip: "Remove the pages that have nothing on them.",
		Run: simple(func(o *ops.Doc) error { _, err := o.DropBlank(ops.BlankOptions{}); return err }),
	},
	{
		ID: "doc.annotations", Label: "Remove comments", NeedsDoc: true,
		Tip: "Take out every annotation: notes, highlights, stamps.",
		Run: simple(func(o *ops.Doc) error { o.RemoveAnnotations(); return nil }),
	},
	{
		ID: "doc.clearinfo", Label: "Clear details", NeedsDoc: true,
		Tip: "Forget the author, the producer and the other metadata.",
		Run: simple(func(o *ops.Doc) error { o.ClearInfo(); return nil }),
	},
}

Commands is every command the editor offers.

The set is chosen to be what somebody actually reaches for in a PDF editor, and every one of them is a method of ops.Doc — nothing here is invented for the playground, so what the buttons do is what the library does.

View Source
var ErrNoDocument = errors.New("there is no document open")

ErrNoDocument is returned by a command when there is nothing open.

Functions

func ExamplePDF

func ExamplePDF() ([]byte, error)

ExamplePDF builds the document the playground starts with.

Each page carries as many filled squares as its number, and a rule down the left edge.

⛔ SQUARES AND NOT THE WORD "Page 3". pdfkit sets text in EMBEDDED fonts — LoadFont takes the bytes of a real font — and there is no standard-14 shortcut, so printing a page number would mean carrying a typeface into a wasm binary that is already six megabytes. Counting squares needs no font, reads at thumbnail size, and the rule makes a rotation obvious, which text the same way up in a stamp-sized preview would not.

⛔ BUILT, NOT EMBEDDED. A committed binary fixture is a file nobody rereads and no test can explain; this is the library under test producing its own input, so it cannot drift from the writer.

func IsDarkColour

func IsDarkColour(css string) bool

IsDarkColour reads a CSS "rgb(r, g, b)" or "rgba(r, g, b, a)" and says whether it is closer to ink than to paper.

⛔ THE DECISION LIVES HERE AND THE PLUMBING LIVES IN THE COMMAND. Asking the browser for the page's computed background needs syscall/js and can only be built for js/wasm, which is why this was written inside the wasm main and went untested: there is no host build to run a test against. The part that can be wrong on its own is a string and a threshold, so it is a function of a string and lives in the package the tests already cover.

Anything it cannot read is light, which is the safer default: dark widgets on a light page are much harder to read than the other way round. A colour with fewer than three channels is not a colour it read — "rgb()" and "transparent" both end up here.

⛔ AND NEITHER IS A FULLY TRANSPARENT ONE. "rgba(0, 0, 0, 0)" is what the browser returns for a background nobody set, and reading its three zeroes as black made an unstyled page the darkest there is: the canvas would have gone dark on a white page, which is the one way round that cannot be read. The alpha is not used to judge the colour — a page is as dark as what shows through — but a zero alpha means there is nothing to judge.

func UseUIFont

func UseUIFont(scale float64)

UseUIFont installs the UI typeface at the given scale.

⛔ THE FACE IS PART OF THE SCALE. Installing it once at 14 and then doubling every metric leaves the type the only thing on the surface that did not grow: labels that fitted their controls at 1x rattle around inside them at 2x, and a ribbon measured from its font lays out for a face it is not drawing with.

A parse failure leaves whatever face is installed rather than refusing to start: an editor that opens with plain text beats one that does not open.

Types

type Ask

type Ask struct {
	// Title heads the dialog.
	Title string
	// Prompt says what to type, in words rather than in grammar.
	Prompt string
	// Default is what the box starts with, and is what the command does if
	// the reader presses straight through — so it is always something
	// sensible rather than empty.
	Default string
}

Ask describes one value a command needs.

type Command

type Command struct {
	// ID is stable and is what a keymap binds.
	ID string
	// Label is what the button says.
	Label string
	// Tip is the sentence under the name in the tooltip. It says what the
	// command DOES, not what it is called again.
	Tip string
	// NeedsDoc is true for everything that acts on a document; the ribbon
	// greys those out until one is open.
	NeedsDoc bool
	// Run does it.
	Run func(d *Doc) error

	// Ask, when set, is a value the command needs before it can run. The
	// command is then performed by RunWith rather than by Run.
	//
	// ⛔ IT IS DATA, NOT A WIDGET. A command that built its own dialog would
	// drag go-widgets into this file and make every command untestable
	// without a canvas. What a command knows is WHAT it needs to be told;
	// how it is asked belongs to whatever is running it — which is also what
	// lets the same command be driven from a test, and one day from a script.
	Ask *Ask
	// RunWith does it with the answer. Set exactly when Ask is.
	RunWith func(d *Doc, answer string) error
}

Command is one thing the editor can do to the document.

⛔ IT IS DECLARED HERE AND NOWHERE ELSE. The ribbon, the keyboard and the tests all reach a command through this table, so a button that does something no test covers cannot exist: the test iterates the table.

Each Run takes the Doc rather than the ops.Doc so that it can read the page being shown — "rotate this page" has to resolve `this` when it runs, not when the ribbon is built.

func CommandByID

func CommandByID(id string) (Command, bool)

CommandByID finds one, for the tests and for a keymap.

func (Command) Perform

func (c Command) Perform(d *Doc) error

Perform runs the command, answering its own question with the default when it has one.

⛔ IT IS WHAT A HOST THAT CANNOT ASK DOES, and that is not only tests: a keyboard accelerator, a script, a batch run. Every Ask therefore carries a Default that is worth doing, rather than an empty box — "watermark with nothing" is not a sensible reading of a key press.

type Doc

type Doc struct {

	// Name is what the file was called when it arrived, for the Save button.
	Name string
	// Repaired records that ops had to mend the file as it opened, which a
	// reader is told rather than left to wonder about.
	Repaired bool
	// contains filtered or unexported fields
}

Doc is the open document: the bytes, and the page you are on.

It is deliberately not a go-widgets anything. Everything here can be tested without a canvas, and is.

func Open

func Open(b []byte, name string) (*Doc, error)

Open reads b as a PDF and makes it the open document.

func (*Doc) Bytes

func (d *Doc) Bytes() []byte

Bytes is the document as it now stands, for rendering and for saving.

func (*Doc) CanRedo

func (d *Doc) CanRedo() bool

func (*Doc) CanUndo

func (d *Doc) CanUndo() bool

CanUndo and CanRedo say whether those commands would do anything.

func (*Doc) Do

func (d *Doc) Do(change func(*ops.Doc) error) error

Do runs one change on the document and keeps the state before it, so it can be undone.

⛔ THE SNAPSHOT IS TAKEN BEFORE, AND KEPT ONLY IF THE CHANGE SUCCEEDS. A failed command that had already pushed an undo state would leave a step that undoes nothing, and the second press of Undo would then skip a real one.

func (*Doc) Page

func (d *Doc) Page() int

Page is the page being shown, 1-based.

func (*Doc) PageCount

func (d *Doc) PageCount() int

PageCount is how many pages the document has, 0 when nothing is open.

func (*Doc) Redo

func (d *Doc) Redo() error

Redo steps forward again.

func (*Doc) Show

func (d *Doc) Show(n int)

Show moves to page n, clamped to the document.

⛔ Clamped rather than refused. Turning the page past the end is a thing people do with the keyboard held down, and an error for it would be noise.

func (*Doc) Undo

func (d *Doc) Undo() error

Undo steps back one change.

type Host

type Host interface {
	// Doc is the open document, nil when there is none.
	Doc() *Doc
	// Say puts a line in the status area — what a command did, or why it
	// would not.
	Say(string)
	// Changed tells the host the document has been edited, so the page and
	// the thumbnails are redrawn.
	Changed()
	// Open and Save go out to the browser; they are nil-safe no-ops in tests.
	Open()
	Save()
	// AskFor puts the command's question to the reader and runs it with the
	// answer. A host with no way to ask — a script, a test — may run it with
	// the default instead, which is why every Ask has one.
	AskFor(Command)
}

Host is what the ribbon needs from whatever is running it: the document, somewhere to say things, and a way to ask for a repaint.

⛔ AN INTERFACE AND NOT THE SCENE. The ribbon is built from the command table and tested without a canvas; a direct reference to the scene would make that impossible and would put the widget tree in every test's way.

type Scene

type Scene struct {

	// OpenFile and SaveFile are the browser bridges, nil in a test.
	OpenFile func()
	SaveFile func(name string, data []byte)
	// contains filtered or unexported fields
}

Scene is the whole editor: the widget tree, the document, and the bridge out to the browser for opening and saving.

func NewScene

func NewScene(w, h int) *Scene

NewScene builds the editor with nothing open.

func (*Scene) AskFor

func (s *Scene) AskFor(c Command)

AskFor puts a command's question to the reader.

⛔ ONE AT A TIME, AND THE SECOND ASK IS REFUSED RATHER THAN STACKED. Two modals over one another leave the reader answering a question they cannot see the top of, and the one underneath has no way to be cancelled.

func (*Scene) Changed

func (s *Scene) Changed()

Changed is called after every edit: the document's bytes are new, so the reader, the page and every thumbnail are stale.

func (*Scene) Char

func (s *Scene) Char(str string) bool

Char is text being typed, which only a dialog's field has any use for.

func (*Scene) Click

func (s *Scene) Click(x, y int) bool

func (*Scene) Context

func (s *Scene) Context(x, y int) bool

func (*Scene) Doc

func (s *Scene) Doc() *Doc

func (*Scene) Draw

func (s *Scene) Draw(buf []byte)

func (*Scene) KeyDown

func (s *Scene) KeyDown(k string) bool

KeyDown turns the keys a reader expects in a PDF viewer into commands.

func (*Scene) Load

func (s *Scene) Load(b []byte, name string)

Load takes a file the browser handed in.

func (*Scene) Move

func (s *Scene) Move(x, y int) bool

func (*Scene) Open

func (s *Scene) Open()

func (*Scene) Release

func (s *Scene) Release(x, y int) bool

func (*Scene) Resize

func (s *Scene) Resize(w, h int) (int, int)

func (*Scene) Save

func (s *Scene) Save()

func (*Scene) Say

func (s *Scene) Say(msg string)

func (*Scene) SetDark

func (s *Scene) SetDark(dark bool)

SetDark switches the editor between the light and dark themes.

⛔ THE CANVAS CANNOT INHERIT THE PAGE'S COLOURS. Everything around it is styled by landingkit's CSS tokens, which follow the reader's choice and the system setting; inside the canvas there is no CSS at all, so a light ribbon sits in a dark page looking like a bug until somebody is told it is not. The host reads the page's state and says so here.

func (*Scene) SetPixelRatio

func (s *Scene) SetPixelRatio(ratio float64)

SetPixelRatio tells the editor how many device pixels the display puts in a CSS pixel, and is webcanvas's [PixelRatioAware] contract.

⛔ IMPLEMENTING IT IS THE WHOLE FIX. A scene that omits this interface is handed CSS pixels and its canvas is sized in CSS pixels — webcanvas says so outright — and this editor omitted it while its wasm shell called SetMetricScale(devicePixelRatio) behind webcanvas's back. Every widget was therefore drawn twice as large onto a surface that had not grown, so on a Retina display the ribbon covered the page and there was nothing to see.

Saying so here instead gets the rest for free: webcanvas sizes the backing store to the CSS box times the ratio, hands Resize DEVICE pixels, and calls this again when the ratio changes — a browser zoom, or a window dragged to a display of another density. The shell's own call could not do that: it read the ratio once, at startup.

func (*Scene) Size

func (s *Scene) Size() (int, int)

func (*Scene) Tick

func (s *Scene) Tick()

Tick makes the thumbnails the strip has asked for, a few per frame.

⛔ BOUNDED BY TIME, NOT BY COUNT. Pages differ by orders of magnitude in what they cost to draw — the same corpus that renders most pages in milliseconds has one that takes minutes — so "three per frame" is a budget that means nothing. A deadline means the same thing on every document. ⛔ IT RETURNS NOTHING, AND THAT MATTERS. webcanvas.Ticker is `Tick()`; a `Tick() bool` does not satisfy it, the interface is not implemented, no timer is installed and this is never called — with no error anywhere, because nothing asked for the interface. The thumbnails stayed as numbered placeholders and everything compiled. cmd/playground-wasm now asserts the three webcanvas interfaces at compile time so the next such slip is a build failure rather than a missing feature.

type Spec

type Spec string

Spec is the page range a command applies to.

const (
	// ThisPage is the page being shown. It is resolved at the moment a
	// command runs, not when the ribbon is built.
	ThisPage Spec = ""
	// AllPages is every page.
	AllPages Spec = "all"
)

Directories

Path Synopsis
cmd
build command
Command build compiles the playground to WebAssembly and puts it, with the toolchain's own wasm_exec.js, where Hugo will publish it.
Command build compiles the playground to WebAssembly and puts it, with the toolchain's own wasm_exec.js, where Hugo will publish it.
pagecheck command
Command pagecheck serves the built site, drives a real browser at the playground, and READS THE PIXELS BACK.
Command pagecheck serves the built site, drives a real browser at the playground, and READS THE PIXELS BACK.
playground-wasm command
Command playground-wasm runs the PDF editor in a browser tab.
Command playground-wasm runs the PDF editor in a browser tab.
themecheck command
Command themecheck proves, in a real browser, that the canvas follows the page's theme — both when the reader chooses one and when the machine changes its mind underneath them.
Command themecheck proves, in a real browser, that the canvas follows the page's theme — both when the reader chooses one and when the machine changes its mind underneath them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL