Skip to content
Ben Soyka edited this page Jan 1, 2024 · 8 revisions

Morebits : object

A library full of lots of goodness for user scripts on MediaWiki wikis, including Wikipedia.

The highlights include:

  • api - make calls to the MediaWiki API
  • page - modify pages on the wiki (edit, revert, delete, etc.)
  • date - enhanced date object processing, sort of a light moment.js
  • quickForm - generate quick HTML forms on the fly
  • simpleWindow - a wrapper for jQuery UI Dialog with a custom look and extra features
  • status - a rough-and-ready status message displayer, used by the Morebits.wiki classes
  • wikitext - utilities for dealing with wikitext
  • string - utilities for manipulating strings
  • array - utilities for manipulating arrays
  • ip - utilities to help process IP addresses

Dependencies:

  • The whole thing relies on jQuery. But most wikis should provide this by default.
  • quickForm, simpleWindow, and status rely on the "morebits.css" file for their styling.
  • simpleWindow and quickForm tooltips rely on jQuery UI Dialog (from ResourceLoader module name 'jquery.ui').
  • To create a gadget based on morebits.js, use this syntax in MediaWiki:Gadgets-definition:
    • *GadgetName[ResourceLoader|dependencies=mediawiki.user,mediawiki.util,mediawiki.Title,jquery.ui]|morebits.js|morebits.css|GadgetName.js
  • Alternatively, you can configure morebits.js as a hidden gadget in MediaWiki:Gadgets-definition:
    • *morebits[ResourceLoader|dependencies=mediawiki.user,mediawiki.util,mediawiki.Title,jquery.ui|hidden]|morebits.js|morebits.css and then load ext.gadget.morebits as one of the dependencies for the new gadget.

All the stuff here works on all browsers for which MediaWiki provides JavaScript support.

This library is maintained by the maintainers of Twinkle. For queries, suggestions, help, etc., head to Wikipedia talk:Twinkle on English Wikipedia. The latest development source is available at GitHub.

Kind: global namespace

Morebits.quickForm

Kind: static class of Morebits

new quickForm(event, [eventType])

Creation of simple and standard forms without much specific coding.

Param Type Default Description
event event

Function to execute when form is submitted.

[eventType] string "submit"

Type of the event.

quickForm.render() ⇒ HTMLElement

Renders the HTML output of the quickForm.

Kind: instance method of quickForm

quickForm.append(data) ⇒ element

Append element to the form.

Kind: instance method of quickForm
Returns: element - - Same as what is passed to the function.

Param Type Description
data object | element

A quickform element, or the object with which a quickform element is constructed.

quickForm.element

Kind: static class of quickForm

new Morebits.quickForm.element(data)

Create a new element for the the form.

Index to Morebits.quickForm.element types:

  • Global attributes: id, className, style, tooltip, extra, adminonly
  • select: A combo box (aka drop-down).
    • Attributes: name, label, multiple, size, list, event, disabled
  • option: An element for a combo box.
    • Attributes: value, label, selected, disabled
  • optgroup: A group of "option"s.
    • Attributes: label, list
  • field: A fieldset (aka group box).
    • Attributes: name, label, disabled
  • checkbox: A checkbox. Must use "list" parameter.
    • Attributes: name, list, event
    • Attributes (within list): name, label, value, checked, disabled, event, subgroup
  • radio: A radio button. Must use "list" parameter.
    • Attributes: name, list, event
    • Attributes (within list): name, label, value, checked, disabled, event, subgroup
  • input: A text box.
    • Attributes: name, label, value, size, disabled, required, readonly, maxlength, event
  • dyninput: A set of text boxes with "Remove" buttons and an "Add" button.
    • Attributes: name, label, min, max, sublabel, value, size, maxlength, event
  • hidden: An invisible form field.
    • Attributes: name, value
  • header: A level 5 header.
    • Attributes: label
  • div: A generic placeholder element or label.
    • Attributes: name, label
  • submit: A submit button. Morebits.simpleWindow moves these to the footer of the dialog.
    • Attributes: name, label, disabled
  • button: A generic button.
    • Attributes: name, label, disabled, event
  • textarea: A big, multi-line text box.
    • Attributes: name, label, value, cols, rows, disabled, required, readonly
  • fragment: A DocumentFragment object.
    • No attributes, and no global attributes except adminonly.
Param Type Description
data object

Object representing the quickform element. Should specify one of the available types from the index above, as well as any relevant and available attributes.

Example

new Morebits.quickForm.element({
    name: 'target',
    type: 'input',
    label: 'Your target:',
    tooltip: 'Enter your target. Required.',
    required: true
});

element.append(data) ⇒ element

Appends an element to current element.

Kind: instance method of element
Returns: element - The same element passed in.

Param Type Description
data element

A quickForm element or the object required to create the quickForm element.

element.render() ⇒ HTMLElement

Renders the HTML output for the quickForm element. This should be called without parameters: form.render().

Kind: instance method of element

element.compute()

Kind: instance method of element

element.id : number

Kind: static property of element

element.generateTooltip(node, data)

Create a jQuery UI-based tooltip.

Kind: static method of element
Requires: module:jquery.ui

Param Type Description
node HTMLElement

The HTML element beside which a tooltip is to be generated.

data object

Tooltip-related configuration data.

quickForm.getInputData(form) ⇒ object

Returns an object containing all filled form data entered by the user, with the object keys being the form element names. Disabled fields will be ignored, but not hidden fields.

Kind: static method of quickForm
Returns: object - With field names as keys, input data as values.

Param Type
form HTMLFormElement

quickForm.getElements(form, fieldName) ⇒ Array.<HTMLElement>

Returns all form elements with a given field name or ID.

Kind: static method of quickForm
Returns: Array.<HTMLElement> - - Array of matching form elements.

Param Type Description
form HTMLFormElement
fieldName string

The name or id of the fields.

quickForm.getCheckboxOrRadio(elementArray, value) ⇒ HTMLInputElement

Searches the array of elements for a checkbox or radio button with a certain value attribute, and returns the first such element. Returns null if not found.

Kind: static method of quickForm

Param Type Description
elementArray Array.<HTMLInputElement>

Array of checkbox or radio elements.

value string

Value to search for.

quickForm.getElementContainer(element) ⇒ HTMLElement

Returns the <div> containing the form element, or the form element itself May not work as expected on checkboxes or radios.

Kind: static method of quickForm

Param Type
element HTMLElement

quickForm.getElementLabelObject(element) ⇒ HTMLElement

Gets the HTML element that contains the label of the given form element (mainly for internal use).

Kind: static method of quickForm

Param Type
element HTMLElement | element

quickForm.getElementLabel(element) ⇒ string

Gets the label text of the element.

Kind: static method of quickForm

Param Type
element HTMLElement | element

quickForm.setElementLabel(element, labelText) ⇒ boolean

Sets the label of the element to the given text.

Kind: static method of quickForm
Returns: boolean - True if succeeded, false if the label element is unavailable.

Param Type
element HTMLElement | element
labelText string

quickForm.overrideElementLabel(element, temporaryLabelText) ⇒ boolean

Stores the element's current label, and temporarily sets the label to the given text.

Kind: static method of quickForm
Returns: boolean - true if succeeded, false if the label element is unavailable.

Param Type
element HTMLElement | element
temporaryLabelText string

quickForm.resetElementLabel(element) ⇒ boolean

Restores the label stored by overrideElementLabel.

Kind: static method of quickForm
Returns: boolean - True if succeeded, false if the label element is unavailable.

Param Type
element HTMLElement | element

quickForm.setElementVisibility(element, [visibility])

Shows or hides a form element plus its label and tooltip.

Kind: static method of quickForm

Param Type Description
element HTMLElement | jQuery | string

HTML/jQuery element, or jQuery selector string.

[visibility] boolean

Skip this to toggle visibility.

quickForm.setElementTooltipVisibility(element, [visibility])

Shows or hides the question mark icon (which displays the tooltip) next to a form element.

Kind: static method of quickForm

Param Type Description
element HTMLElement | jQuery
[visibility] boolean

Skip this to toggle visibility.

Morebits.unbinder

Kind: static class of Morebits

new Morebits.unbinder(string)

Temporarily hide a part of a string while processing the rest of it. Used by Morebits.wikitext.page.commentOutImage.

Param Type Description
string string

The initial text to process.

Example

var u = new Morebits.unbinder('Hello world <!-- world --> world');
u.unbind('<!--', '-->'); // text inside comment remains intact
u.content = u.content.replace(/world/g, 'earth');
u.rebind(); // gives 'Hello earth <!-- world --> earth'

unbinder.content

The text being processed.

Kind: instance property of unbinder

unbinder.unbind(prefix, postfix)

Hide the region encapsulated by the prefix and postfix from string processing. prefix and postfix will be used in a RegExp, so items that need escaping should be use \\.

Kind: instance method of unbinder
Throws:

  • If either prefix or postfix is missing.
Param Type
prefix string
postfix string

unbinder.rebind() ⇒ string

Restore the hidden portion of the content string.

Kind: instance method of unbinder
Returns: string - The processed output.

unbinder.getCallback()

Kind: static method of unbinder

Morebits.date

Kind: static class of Morebits

new Morebits.date()

Create a date object with enhanced processing capabilities, a la moment.js. MediaWiki timestamp format is also acceptable, in addition to everything that JS Date() accepts.

date.isValid() ⇒ boolean

Kind: instance method of date

date.isBefore(date) ⇒ boolean

Kind: instance method of date

Param Type
date Date | date

date.isAfter(date) ⇒ boolean

Kind: instance method of date

Param Type
date Date | date

date.getUTCMonthName() ⇒ string

Kind: instance method of date

date.getUTCMonthNameAbbrev() ⇒ string

Kind: instance method of date

date.getMonthName() ⇒ string

Kind: instance method of date

date.getMonthNameAbbrev() ⇒ string

Kind: instance method of date

date.getUTCDayName() ⇒ string

Kind: instance method of date

date.getUTCDayNameAbbrev() ⇒ string

Kind: instance method of date

date.getDayName() ⇒ string

Kind: instance method of date

date.getDayNameAbbrev() ⇒ string

Kind: instance method of date

date.add(number, unit) ⇒ date

Add a given number of minutes, hours, days, months or years to the date. This is done in-place. The modified date object is also returned, allowing chaining.

Kind: instance method of date
Throws:

  • If invalid or unsupported unit is given.
Param Type Description
number number

Should be an integer.

unit string

date.subtract(number, unit) ⇒ date

Subtracts a given number of minutes, hours, days, months or years to the date. This is done in-place. The modified date object is also returned, allowing chaining.

Kind: instance method of date
Throws:

  • If invalid or unsupported unit is given.
Param Type Description
number number

Should be an integer.

unit string

date.format(formatstr, [zone]) ⇒ string

Format the date into a string per the given format string. Replacement syntax is a subset of that in moment.js:

Syntax Output
H Hours (24-hour)
HH Hours (24-hour, padded)
h Hours (12-hour)
hh Hours (12-hour, padded)
A AM or PM
m Minutes
mm Minutes (padded)
s Seconds
ss Seconds (padded)
SSS Milliseconds fragment, padded
d Day number of the week (Sun=0)
ddd Abbreviated day name
dddd Full day name
D Date
DD Date (padded)
M Month number (0-indexed)
MM Month number (0-indexed, padded)
MMM Abbreviated month name
MMMM Full month name
Y Year
YY Final two digits of year (20 for 2020, 42 for 1942)
YYYY Year (same as Y)

Kind: instance method of date

Param Type Default Description
formatstr string

Format the date into a string, using the replacement syntax. Use [ and ] to escape items. If not provided, will return the ISO-8601-formatted string.

[zone] string | number "system"

system (for browser-default time zone), utc, or specify a time zone as number of minutes relative to UTC.

date.calendar([zone]) ⇒ string

Gives a readable relative time string such as "Yesterday at 6:43 PM" or "Last Thursday at 11:45 AM". Similar to calendar in moment.js, but with time zone support.

Kind: instance method of date

Param Type Default Description
[zone] string | number "system"

'system' (for browser-default time zone), 'utc' (for UTC), or specify a time zone as number of minutes past UTC.

date.monthHeaderRegex() ⇒ RegExp

Get a regular expression that matches wikitext section titles, such as ==December 2019== or === Jan 2018 ===.

Kind: instance method of date

date.monthHeader([level]) ⇒ string

Creates a wikitext section header with the month and year.

Kind: instance method of date

Param Type Default Description
[level] number 2

Header level. Pass 0 for just the text with no wikitext markers (==).

date.unitMap : object.<string, string>

Map units with getter/setter function names, for add and subtract methods.

Kind: static property of date

Morebits.userspaceLogger

Kind: static class of Morebits

new Morebits.userspaceLogger(logPageName)

Handles logging actions to a userspace log. Used in CSD, PROD, and XFD.

Param Type Description
logPageName string

Title of the subpage of the current user's log.

userspaceLogger.initialText : string

The text to prefix the log with upon creation, defaults to empty.

Kind: instance property of userspaceLogger

userspaceLogger.headerLevel : number

The header level to use for months, defaults to 3 (===).

Kind: instance property of userspaceLogger

userspaceLogger.log(logText, summaryText) ⇒ JQuery.Promise

Log the entry.

Kind: instance method of userspaceLogger

Param Type Description
logText string

Doesn't include leading # or *.

summaryText string

Edit summary.

Morebits.status

Kind: static class of Morebits

new Morebits.status(text, stat, [type])

Create and show status messages of varying urgency. Morebits.status.init() must be called before any status object is created, otherwise those statuses won't be visible.

Param Type Default Description
text string

Text before the the colon :.

stat string

Text after the colon :.

[type] string "status"

Determine the font color of the status line, allowable values are: status (blue), info (green), warn (red), or error (bold red).

status.link()

Add the status element node to the DOM.

Kind: instance method of status

status.unlink()

Remove the status element node from the DOM.

Kind: instance method of status

status.codify(obj) ⇒ DocumentFragment

Create a document fragment with the status text, parsing as HTML. Runs upon construction for text (part before colon) and upon render/update for status (part after colon).

Kind: instance method of status

Param Type
obj string | Element | Array

status.update(status, type)

Update the status.

Kind: instance method of status

Param Type Description
status string

Part of status message after colon.

type string

'status' (blue), 'info' (green), 'warn' (red), or 'error' (bold red).

status.generate()

Produce the html for first part of the status message.

Kind: instance method of status

status.render()

Complete the html, for the second part of the status message.

Kind: instance method of status

status.init(root)

Specify an area for status message elements to be added to.

Kind: static method of status
Throws:

  • If root is not an HTMLElement.
Param Type Description
root HTMLElement

Usually a div element.

status.onError(handler)

Kind: static method of status
Throws:

  • When handler is not a function.
Param Type Description
handler function

Function to execute on error.

status.status(text, status) ⇒ status

Kind: static method of status
Returns: status - - status-type (blue)

Param Type Description
text string

Before colon

status string

After colon

status.info(text, status) ⇒ status

Kind: static method of status
Returns: status - - info-type (green)

Param Type Description
text string

Before colon

status string

After colon

status.warn(text, status) ⇒ status

Kind: static method of status
Returns: status - - warn-type (red)

Param Type Description
text string

Before colon

status string

After colon

status.error(text, status) ⇒ status

Kind: static method of status
Returns: status - - error-type (bold red)

Param Type Description
text string

Before colon

status string

After colon

status.actionCompleted(text)

For the action complete message at the end, create a status line without a colon separator.

Kind: static method of status

Param Type
text string

status.printUserText(comments, message)

Display the user's rationale, comments, etc. Back to them after a failure, so that they may re-use it.

Kind: static method of status

Param Type
comments string
message string

Morebits.batchOperation

Kind: static class of Morebits

new Morebits.batchOperation([currentAction])

Iterates over a group of pages (or arbitrary objects) and executes a worker function for each.

setPageList(pageList): Sets the list of pages to work on. It should be an array of page names strings.

setOption(optionName, optionValue): Sets a known option:

  • chunkSize (integer): The size of chunks to break the array into (default 50). Setting this to a small value (<5) can cause problems.
  • preserveIndividualStatusLines (boolean): Keep each page's status element visible when worker is complete? See note below.

run(worker, postFinish): Runs the callback worker for each page in the list. The callback must call workerSuccess when succeeding, or workerFailure when failing. If using api or page, this is easily done by passing these two functions as parameters to the methods on those objects: for instance, page.save(batchOp.workerSuccess, batchOp.workerFailure). Make sure the methods are called directly if special success/failure cases arise. If you omit to call these methods, the batch operation will stall after the first chunk! Also ensure that either workerSuccess or workerFailure is called no more than once. The second callback postFinish is executed when the entire batch has been processed.

If using preserveIndividualStatusLines, you should try to ensure that the workerSuccess callback has access to the page title. This is no problem for page objects. But when using the API, please set the |pageName| property on the api object.

There are sample batchOperation implementations using Morebits.wiki.page in twinklebatchdelete.js, twinklebatchundelete.js, and twinklebatchprotect.js.

Param Type
[currentAction] string

batchOperation.setPageList(pageList)

Sets the list of pages to work on.

Kind: instance method of batchOperation

Param Type Description
pageList Array

Array of objects over which you wish to execute the worker function This is usually the list of page names (strings).

batchOperation.setOption(optionName, optionValue)

Sets a known option.

Kind: instance method of batchOperation

Param Type Description
optionName string

Name of the option:

  • chunkSize (integer): The size of chunks to break the array into (default 50). Setting this to a small value (<5) can cause problems.
  • preserveIndividualStatusLines (boolean): Keep each page's status element visible when worker is complete?
optionValue number | boolean

Value to which the option is to be set. Should be an integer for chunkSize and a boolean for preserveIndividualStatusLines.

batchOperation.run(worker, [postFinish])

Runs the first callback for each page in the list. The callback must call workerSuccess when succeeding, or workerFailure when failing. Runs the optional second callback when the whole batch has been processed.

Kind: instance method of batchOperation

Param Type
worker function
[postFinish] function

batchOperation.workerSuccess(arg)

To be called by worker before it terminates succesfully.

Kind: instance method of batchOperation

Param Type Description
arg page | api | string

This should be the Morebits.wiki.page or Morebits.wiki.api object used by worker (for the adjustment of status lines emitted by them). If no Morebits.wiki.* object is used (e.g. you're using mw.Api() or something else), and preserveIndividualStatusLines option is on, give the page name (string) as argument.

Morebits.taskManager

Kind: static class of Morebits

new Morebits.taskManager()

Given a set of asynchronous functions to run along with their dependencies, figure out an efficient sequence of running them so that multiple functions that don't depend on each other are triggered simultaneously. Where dependencies exist, it ensures that the dependency functions finish running before the dependent function runs. The values resolved by the dependencies are made available to the dependant as arguments.

taskManager.add(func, deps)

Register a task along with its dependencies (tasks which should have finished execution before we can begin this one). Each task is a function that must return a promise. The function will get the values resolved by the dependency functions as arguments.

Kind: instance method of taskManager

Param Type Description
func function

A task.

deps Array.<function()>

Its dependencies.

taskManager.execute() ⇒ promise

Run all the tasks. Multiple tasks may be run at once.

Kind: instance method of taskManager
Returns: promise - - A jQuery promise object that is resolved or rejected with the api object.

Morebits.simpleWindow

Kind: static class of Morebits
Requires: module:jquery.ui.dialog

new Morebits.simpleWindow(width, height)

A simple draggable window, now a wrapper for jQuery UI's dialog feature.

Param Type Description
width number
height number

The maximum allowable height for the content area.

simpleWindow.focus() ⇒ simpleWindow

Focuses the dialog. This might work, or on the contrary, it might not.

Kind: instance method of simpleWindow

simpleWindow.close([event]) ⇒ simpleWindow

Closes the dialog. If this is set as an event handler, it will stop the event from doing anything more.

Kind: instance method of simpleWindow

Param Type
[event] event

simpleWindow.display() ⇒ simpleWindow

Shows the dialog. Calling display() on a dialog that has previously been closed might work, but it is not guaranteed.

Kind: instance method of simpleWindow

simpleWindow.setTitle(title) ⇒ simpleWindow

Sets the dialog title.

Kind: instance method of simpleWindow

Param Type
title string

simpleWindow.setScriptName(name) ⇒ simpleWindow

Sets the script name, appearing as a prefix to the title to help users determine which user script is producing which dialog. For instance, Twinkle modules set this to "Twinkle".

Kind: instance method of simpleWindow

Param Type
name string

simpleWindow.setWidth(width) ⇒ simpleWindow

Sets the dialog width.

Kind: instance method of simpleWindow

Param Type
width number

simpleWindow.setHeight(height) ⇒ simpleWindow

Sets the dialog's maximum height. The dialog will auto-size to fit its contents, but the content area will grow no larger than the height given here.

Kind: instance method of simpleWindow

Param Type
height number

simpleWindow.setContent(content) ⇒ simpleWindow

Sets the content of the dialog to the given element node, usually from rendering a quickForm. Re-enumerates the footer buttons, but leaves the footer links as they are. Be sure to call this at least once before the dialog is displayed...

Kind: instance method of simpleWindow

Param Type
content HTMLElement

simpleWindow.addContent(content) ⇒ simpleWindow

Adds the given element node to the dialog content.

Kind: instance method of simpleWindow

Param Type
content HTMLElement

simpleWindow.purgeContent() ⇒ simpleWindow

Removes all contents from the dialog, barring any footer links.

Kind: instance method of simpleWindow

simpleWindow.addFooterLink(text, wikiPage, [prep]) ⇒ simpleWindow

Adds a link in the bottom-right corner of the dialog. This can be used to provide help or policy links. For example, Twinkle's CSD module adds a link to the CSD policy page, as well as a link to Twinkle's documentation.

Kind: instance method of simpleWindow

Param Type Default Description
text string

Display text.

wikiPage string

Link target.

[prep] boolean false

Set true to prepend rather than append.

simpleWindow.setModality([modal]) ⇒ simpleWindow

Sets whether the window should be modal or not. Modal dialogs create an overlay below the dialog but above other page elements. This must be used (if necessary) before calling display().

Kind: instance method of simpleWindow

Param Type Default Description
[modal] boolean false

If set to true, other items on the page will be disabled, i.e., cannot be interacted with.

simpleWindow.setButtonsEnabled(enabled)

Enables or disables all footer buttons on all simpleWindows in the current page. This should be called with false when the button(s) become irrelevant (e.g. just before init is called). This is not an instance method so that consumers don't have to keep a reference to the original Morebits.simpleWindow object sitting around somewhere. Anyway, most of the time there will only be one Morebits.simpleWindow open, so this shouldn't matter.

Kind: static method of simpleWindow

Param Type
enabled boolean

Morebits.userIsSysop : boolean

Hardcodes whether the user is a sysop, used a lot.

Kind: static property of Morebits

Morebits.pageNameNorm : string

Stores a normalized (underscores converted to spaces) version of the wgPageName variable.

Kind: static property of Morebits

Morebits.ip : object

Utilities to help process IP addresses.

Kind: static namespace of Morebits

ip.sanitizeIPv6(address) ⇒ string

Converts an IPv6 address to the canonical form stored and used by MediaWiki. JavaScript translation of the IP::sanitizeIP() function from the IPUtils library. Adddresses are verbose, uppercase, normalized, and expanded to 8 words.

Kind: static method of ip

Param Type Description
address string

The IPv6 address, with or without CIDR.

ip.isRange(ip) ⇒ boolean

Determine if the given IP address is a range. Just conjoins mw.util.isIPAddress with and without the allowBlock option.

Kind: static method of ip
Returns: boolean - - True if given a valid IP address range, false otherwise.

Param Type
ip string

ip.validCIDR() ⇒ boolean

Check that an IP range is within the CIDR limits. Most likely to be useful in conjunction with wgRelevantUserName. CIDR limits are harcoded as /16 for IPv4 and /32 for IPv6.

Kind: static method of ip
Returns: boolean - - True for valid ranges within the CIDR limits, otherwise false (ranges outside the limit, single IPs, non-IPs).

ip.get64(ipv6) ⇒ boolean | string

Get the /64 subnet for an IPv6 address.

Kind: static method of ip
Returns: boolean | string - - False if not IPv6 or bigger than a 64, otherwise the (sanitized) /64 address.

Param Type Description
ipv6 string

The IPv6 address, with or without a subnet.

Morebits.string : object

Helper functions to manipulate strings.

Kind: static namespace of Morebits

string.toUpperCaseFirstChar(str) ⇒ string

Kind: static method of string

Param Type
str string

string.toLowerCaseFirstChar(str) ⇒ string

Kind: static method of string

Param Type
str string

string.splitWeightedByKeys(str, start, end, [skiplist]) ⇒ Array.<string>

Gives an array of substrings of str - starting with start and ending with end - which is not in skiplist. Intended for use on wikitext with templates or links.

Kind: static method of string
Throws:

  • If the start and end strings aren't of the same length.
  • If skiplist isn't an array or string
Param Type
str string
start string
end string
[skiplist] Array.<string> | string

string.formatReasonText(str, [addSig]) ⇒ string

Formats freeform "reason" (from a textarea) for deletion/other templates that are going to be substituted, (e.g. PROD, XFD, RPP). Handles | outside a nowiki tag. Optionally, also adds a signature if not present already.

Kind: static method of string

Param Type
str string
[addSig] boolean

string.formatReasonForLog(str) ⇒ string

Formats a "reason" (from a textarea) for inclusion in a userspace log. Replaces newlines with {{Pb}}, and adds an extra # before list items for proper formatting.

Kind: static method of string

Param Type
str string

string.safeReplace(string, pattern, replacement) ⇒ string

Like String.prototype.replace(), but escapes any dollar signs in the replacement string. Useful when the the replacement string is arbitrary, such as a username or freeform user input, and could contain dollar signs.

Kind: static method of string

Param Type Description
string string

Text in which to replace.

pattern string | RegExp
replacement string

string.isInfinity(expiry) ⇒ boolean

Determine if the user-provided expiration will be considered an infinite-length by MW.

Kind: static method of string
See: https://phabricator.wikimedia.org/T68646

Param Type
expiry string

string.escapeRegExp(text) ⇒ string

Escapes a string to be used in a RegExp, replacing spaces and underscores with [_ ] as they are often equivalent. Replaced RegExp.escape September 2020.

Kind: static method of string
Returns: string - - The escaped text.

Param Type Description
text string

String to be escaped.

Morebits.array : object

Helper functions to manipulate arrays.

Kind: static namespace of Morebits

array.uniq(arr) ⇒ Array

Remove duplicated items from an array.

Kind: static method of array
Returns: Array - A copy of the array with duplicates removed.
Throws:

  • When provided a non-array.
Param Type
arr Array

array.dups(arr) ⇒ Array

Remove non-duplicated items from an array.

Kind: static method of array
Returns: Array - A copy of the array with the first instance of each value removed; subsequent instances of those values (duplicates) remain.
Throws:

  • When provided a non-array.
Param Type
arr Array

array.chunk(arr, size) ⇒ Array.<Array>

Break up an array into smaller arrays.

Kind: static method of array
Returns: Array.<Array> - An array containing the smaller, chunked arrays.
Throws:

  • When provided a non-array.
Param Type Description
arr Array
size number

Size of each chunk (except the last, which could be different).

Morebits.select2 : object

Utilities to enhance select2 menus. See twinklewarn, twinklexfd, twinkleblock for sample usages.

Kind: static namespace of Morebits
Requires: module:jquery.select2
See: https://select2.org/

select2.highlightSearchMatches()

Underline matched part of options.

Kind: static method of select2

select2.queryInterceptor()

Intercept query as it is happening, for use in highlightSearchMatches.

Kind: static method of select2

select2.autoStart()

Open dropdown and begin search when the .select2-selection has focus and a key is pressed.

Kind: static method of select2
See: https://github.com/select2/select2/issues/3279#issuecomment-442524147

Morebits.wiki : object

Various objects for wiki editing and API access, including api and page.

Kind: static namespace of Morebits

wiki.api

Kind: static class of wiki

new Morebits.wiki.api(currentAction, query, [onSuccess], [statusElement], [onError])

An easy way to talk to the MediaWiki API. Accepts either json or xml (default) formats; if json is selected, will default to formatversion=2 unless otherwise specified. Similarly, enforces newer errorformats, defaulting to html if unspecified. uselang enforced to the wiki's content language.

In new code, the use of the last 3 parameters should be avoided, instead use setStatusElement() to bind the status element (if needed) and use .then() or .catch() on the promise returned by post(), rather than specify the onSuccess or onFailure callbacks.

Param Type Description
currentAction string

The current action (required).

query object

The query (required).

[onSuccess] function

The function to call when request is successful.

[statusElement] status

A Morebits.status object to use for status messages.

[onError] function

The function to call if an error occurs.

api.setParent(parent)

Keep track of parent object for callbacks.

Kind: instance method of api

Param Type
parent *

api.setStatusElement(statusElement)

Kind: instance method of api

Param Type
statusElement status

api.post(callerAjaxParameters) ⇒ promise

Carry out the request.

Kind: instance method of api
Returns: promise - - A jQuery promise object that is resolved or rejected with the api object.

Param Type Description
callerAjaxParameters object

Do not specify a parameter unless you really really want to give jQuery some extra parameters.

api.morebitsWikiChangeTag : string

Change/revision tag applied to Morebits actions when no other tags are specified. Unused by default per EnWiki consensus.

Kind: static constant of api

api.setApiUserAgent([ua])

Set the custom user agent header, which is used for server-side logging. Note that doing so will set the useragent for every Morebits.wiki.api process performed thereafter.

Kind: static method of api
See: https://lists.wikimedia.org/pipermail/mediawiki-api-announce/2014-November/000075.html for original announcement.

Param Type Default Description
[ua] string "morebits.js ([[w:WT:TW]])"

User agent. The default value of morebits.js ([[w:WT:TW]]) will be appended to any provided value.

api.getToken() ⇒ string

Get a new CSRF token on encountering token errors.

Kind: static method of api
Returns: string - MediaWiki CSRF token.

wiki.page

Kind: static class of wiki

new Morebits.wiki.page(pageName, [status])

Use the MediaWiki API to load a page and optionally edit it, move it, etc.

Callers are not permitted to directly access the properties of this class! All property access is through the appropriate get___() or set___() method.

Callers should set notice and redirect before the first call to Morebits.wiki.page.load().

Each of the callback functions takes one parameter, which is a reference to the Morebits.wiki.page object that registered the callback. Callback functions may invoke any Morebits.wiki.page prototype method using this reference.

Call sequence for common operations (optional final user callbacks not shown):

  • Edit current contents of a page (no edit conflict): .load(userTextEditCallback) -> ctx.loadApi.post() -> ctx.loadApi.post.success() -> ctx.fnLoadSuccess() -> userTextEditCallback() -> .save() -> ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()

  • Edit current contents of a page (with edit conflict): .load(userTextEditCallback) -> ctx.loadApi.post() -> ctx.loadApi.post.success() -> ctx.fnLoadSuccess() -> userTextEditCallback() -> .save() -> ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveError() -> ctx.loadApi.post() -> ctx.loadApi.post.success() -> ctx.fnLoadSuccess() -> userTextEditCallback() -> .save() -> ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()

  • Append to a page (similar for prepend and newSection): .append() -> ctx.loadApi.post() -> ctx.loadApi.post.success() -> ctx.fnLoadSuccess() -> ctx.fnAutoSave() -> .save() -> ctx.saveApi.post() -> ctx.loadApi.post.success() -> ctx.fnSaveSuccess()

Notes:

  1. All functions following Morebits.wiki.api.post() are invoked asynchronously from the jQuery AJAX library.
  2. The sequence for append/prepend/newSection could be slightly shortened, but it would require significant duplication of code for little benefit.
Param Type Description
pageName string

The name of the page, prefixed by the namespace (if any). For the current page, use mw.config.get('wgPageName').

[status] string | status

A string describing the action about to be undertaken, or a Morebits.status object

page.load(onSuccess, [onFailure])

Loads the text for the page.

Kind: instance method of page

Param Type Description
onSuccess function

Callback function which is called when the load has succeeded.

[onFailure] function

Callback function which is called when the load fails.

page.save([onSuccess], [onFailure])

Saves the text for the page to Wikipedia. Must be preceded by successfully calling load().

Warning: Calling save() can result in additional calls to the previous load() callbacks to recover from edit conflicts! In this case, callers must make the same edit to the new pageText and reinvoke save(). This behavior can be disabled with setMaxConflictRetries(0).

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function which is called when the save has succeeded.

[onFailure] function

Callback function which is called when the save fails.

page.append([onSuccess], [onFailure])

Adds the text provided via setAppendText() to the end of the page. Does not require calling load() first, unless a watchlist expiry is used.

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function which is called when the method has succeeded.

[onFailure] function

Callback function which is called when the method fails.

page.prepend([onSuccess], [onFailure])

Adds the text provided via setPrependText() to the start of the page. Does not require calling load() first, unless a watchlist expiry is used.

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function which is called when the method has succeeded.

[onFailure] function

Callback function which is called when the method fails.

page.newSection([onSuccess], [onFailure])

Creates a new section with the text provided by setNewSectionText() and section title from setNewSectionTitle(). If editSummary is provided, that will be used instead of the autogenerated "->Title (new section" edit summary. Does not require calling load() first, unless a watchlist expiry is used.

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function which is called when the method has succeeded.

[onFailure] function

Callback function which is called when the method fails.

page.getPageName() ⇒ string

Kind: instance method of page
Returns: string - The name of the loaded page, including the namespace

page.getPageText() ⇒ string

Kind: instance method of page
Returns: string - The text of the page after a successful load()

page.setPageText(pageText)

Kind: instance method of page

Param Type Description
pageText string

Updated page text that will be saved when save() is called

page.setAppendText(appendText)

Kind: instance method of page

Param Type Description
appendText string

Text that will be appended to the page when append() is called

page.setPrependText(prependText)

Kind: instance method of page

Param Type Description
prependText string

Text that will be prepended to the page when prepend() is called

page.setNewSectionText(newSectionText)

Kind: instance method of page

Param Type Description
newSectionText string

Text that will be added in a new section on the page when newSection() is called

page.setNewSectionTitle(newSectionTitle)

Kind: instance method of page

Param Type Description
newSectionTitle string

Title for the new section created when newSection() is called If missing, ctx.editSummary will be used. Issues may occur if a substituted template is used.

page.setEditSummary(summary)

Set the edit summary that will be used when save() is called. Unnecessary if editMode is 'new' and newSectionTitle is provided.

Kind: instance method of page

Param Type
summary string

page.setChangeTags(tags)

Set any custom tag(s) to be applied to the API action. A number of actions don't support it, most notably watch, review, and stabilize (T247721), and pagetriageaction (T252980).

Kind: instance method of page

Param Type Description
tags string | Array.<string>

String or array of tag(s).

page.setCreateOption([createOption])

Kind: instance method of page

Param Type Default Description
[createOption] string null

Can take the following four values:

  • recreate: create the page if it does not exist, or edit it if it exists.
  • createonly: create the page if it does not exist, but return an error if it already exists.
  • nocreate: don't create the page, only edit it if it already exists.
  • null: create the page if it does not exist, unless it was deleted in the moment between loading the page and saving the edit (default).

page.setMinorEdit(minorEdit)

Kind: instance method of page

Param Type Description
minorEdit boolean

Set true to mark the edit as a minor edit.

page.setBotEdit(botEdit)

Kind: instance method of page

Param Type Description
botEdit boolean

Set true to mark the edit as a bot edit

page.setPageSection(pageSection)

Kind: instance method of page

Param Type Description
pageSection number

Integer specifying the section number to load or save. If specified as null, the entire page will be retrieved.

page.setMaxConflictRetries(maxConflictRetries)

Kind: instance method of page

Param Type Description
maxConflictRetries number

Number of retries for save errors involving an edit conflict or loss of token. Default: 2.

page.setMaxRetries(maxRetries)

Kind: instance method of page

Param Type Description
maxRetries number

Number of retries for save errors not involving an edit conflict or loss of token. Default: 2.

page.setWatchlist([watchlistOption])

Kind: instance method of page

Param Type Default Description
[watchlistOption] boolean | string false

Basically a mix of MW API and Twinkley options available pre-expiry:

  • true|'yes': page will be added to the user's watchlist when the action is called
  • false|'no'|'nochange': watchlist status of the page will not be changed.
  • 'default'|'preferences': watchlist status of the page will be set based on the user's preference settings when the action is called. Ignores ability of default + expiry.
  • 'unwatch': explicitly unwatch the page
  • {string|number}: watch page until the specified time (relative or absolute datestring)

page.setWatchlistExpiry(watchlistExpiry)

Set an expiry. setWatchlist can handle this by itself if passed a string, so this is here largely for completeness and compatibility.

Kind: instance method of page

Param Type Description
watchlistExpiry string

A date-like string or array of strings Can be relative (2 weeks) or other similarly date-like (i.e. NOT "potato"): ISO 8601: 2038-01-09T03:14:07Z MediaWiki: 20380109031407 UNIX: 2147483647 SQL: 2038-01-09 03:14:07 Can also be infinity or infinity-like (infinite, indefinite, and never). See https://phabricator.wikimedia.org/source/mediawiki-libs-Timestamp/browse/master/src/ConvertibleTimestamp.php;4e53b859a9580c55958078f46dd4f3a44d0fcaa0$57-109?as=source&blame=off

page.setWatchlistFromPreferences([watchlistOption])

Deprecated

Kind: instance method of page

Param Type Default Description
[watchlistOption] boolean false
  • True: page watchlist status will be set based on the user's preference settings when save() is called.
  • False: watchlist status of the page will not be changed.

Watchlist notes:

  1. The MediaWiki API value of 'unwatch', which explicitly removes the page from the user's watchlist, is not used.
  2. If both setWatchlist() and setWatchlistFromPreferences() are called, the last call takes priority.
  3. Twinkle modules should use the appropriate preference to set the watchlist options.
  4. Most Twinkle modules use setWatchlist(). setWatchlistFromPreferences() is only needed for the few Twinkle watchlist preferences that accept a string value of default.

page.setFollowRedirect([followRedirect], [followCrossNsRedirect])

Kind: instance method of page

Param Type Default Description
[followRedirect] boolean false
  • true: a maximum of one redirect will be followed. In the event of a redirect, a message is displayed to the user and the redirect target can be retrieved with getPageName().
  • false: (default) the requested pageName will be used without regard to any redirect.
[followCrossNsRedirect] boolean true

Not applicable if followRedirect is not set true.

  • true: (default) follow redirect even if it is a cross-namespace redirect
  • false: don't follow redirect if it is cross-namespace, edit the redirect itself.

page.setLookupNonRedirectCreator(flag)

Kind: instance method of page

Param Type Description
flag boolean

If set true, the author and timestamp of the first non-redirect version of the page is retrieved.

Warning:

  1. If there are no revisions among the first 50 that are non-redirects, or if there are less 50 revisions and all are redirects, the original creation is retrived.
  2. Revisions that the user is not privileged to access (revdeled/suppressed) will be treated as non-redirects.
  3. Must not be used when the page has a non-wikitext contentmodel such as Modulespace Lua or user JavaScript/CSS.

page.setMoveDestination(destination)

Kind: instance method of page

Param Type
destination string

page.setMoveTalkPage(flag)

Kind: instance method of page

Param Type
flag boolean

page.setMoveSubpages(flag)

Kind: instance method of page

Param Type
flag boolean

page.setMoveSuppressRedirect(flag)

Kind: instance method of page

Param Type
flag boolean

page.setEditProtection(level, [expiry])

Kind: instance method of page

Param Type Default Description
level string

The right required for the specific action e.g. autoconfirmed, sysop, templateeditor, extendedconfirmed (enWiki-only).

[expiry] string "infinity"

page.getCurrentID() ⇒ string

Kind: instance method of page
Returns: string - The current revision ID of the page

page.getRevisionUser() ⇒ string

Kind: instance method of page
Returns: string - Last editor of the page

page.getLastEditTime() ⇒ string

Kind: instance method of page
Returns: string - ISO 8601 timestamp at which the page was last edited.

page.setCallbackParameters(callbackParameters)

Define an object for use in a callback function.

callbackParameters is for use by the caller only. The parameters allow a caller to pass the proper context into its callback function. Callers must ensure that any changes to the callbackParameters object within a load() callback still permit a proper re-entry into the load() callback if an edit conflict is detected upon calling save().

Kind: instance method of page

Param Type
callbackParameters object

page.getCallbackParameters() ⇒ object

Kind: instance method of page
Returns: object - - The object previously set by setCallbackParameters().

page.setStatusElement(statusElement)

Kind: instance method of page

Param Type
statusElement status

page.getStatusElement() ⇒ status

Kind: instance method of page
Returns: status - Status element created by the constructor.

page.setFlaggedRevs(level, [expiry])

Kind: instance method of page

Param Type Default Description
level string

The right required for edits not to require review. Possible options: none, autoconfirmed, review (not on enWiki).

[expiry] string "infinity"

page.exists() ⇒ boolean

Kind: instance method of page
Returns: boolean - True if the page existed on the wiki when it was last loaded.

page.getPageID() ⇒ string

Kind: instance method of page
Returns: string - Page ID of the page loaded. 0 if the page doesn't exist.

page.getContentModel() ⇒ string

Kind: instance method of page
Returns: string - - Content model of the page. Possible values include (but may not be limited to): wikitext, javascript, css, json, Scribunto, sanitized-css, MassMessageListContent. Also gettable via mw.config.get('wgPageContentModel').

page.getWatched() ⇒ boolean | string

Kind: instance method of page
Returns: boolean | string - - Watched status of the page. Boolean unless it's being watched temporarily, in which case returns the expiry string.

page.getLoadTime() ⇒ string

Kind: instance method of page
Returns: string - ISO 8601 timestamp at which the page was last loaded.

page.getCreator() ⇒ string

Kind: instance method of page
Returns: string - The user who created the page following lookupCreation().

page.getCreationTimestamp() ⇒ string

Kind: instance method of page
Returns: string - The ISOString timestamp of page creation following lookupCreation().

page.canEdit() ⇒ boolean

Kind: instance method of page
Returns: boolean - whether or not you can edit the page

page.lookupCreation(onSuccess)

Retrieves the username of the user who created the page as well as the timestamp of creation. The username can be retrieved using the getCreator() function; the timestamp can be retrieved using the getCreationTimestamp() function. Prior to June 2019 known as lookupCreator().

Kind: instance method of page

Param Type Description
onSuccess function

Callback function to be called when the username and timestamp are found within the callback.

page.revert([onSuccess], [onFailure])

Reverts a page to revertOldID set by setOldID.

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function to run on success.

[onFailure] function

Callback function to run on failure.

page.move([onSuccess], [onFailure])

Moves a page to another title.

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function to run on success.

[onFailure] function

Callback function to run on failure.

page.patrol()

Marks the page as patrolled, using rcid (if available) or revid.

Patrolling as such doesn't need to rely on loading the page in question; simply passing a revid to the API is sufficient, so in those cases just using api is probably preferable.

No error handling since we don't actually care about the errors.

Kind: instance method of page

page.triage()

Marks the page as reviewed by the PageTriage extension.

Will, by it's nature, mark as patrolled as well. Falls back to patrolling if not in an appropriate namespace.

Doesn't inherently rely on loading the page in question; simply passing a pageid to the API is sufficient, so in those cases just using api is probably preferable.

Will first check if the page is queued via fnProcessTriageList.

No error handling since we don't actually care about the errors.

Kind: instance method of page
See: https://www.mediawiki.org/wiki/Extension:PageTriage Referred to as "review" on-wiki.

page.deletePage([onSuccess], [onFailure])

Deletes a page (for admins only).

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function to run on success.

[onFailure] function

Callback function to run on failure.

page.undeletePage([onSuccess], [onFailure])

Undeletes a page (for admins only).

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function to run on success.

[onFailure] function

Callback function to run on failure.

page.protect([onSuccess], [onFailure])

Protects a page (for admins only).

Kind: instance method of page

Param Type Description
[onSuccess] function

Callback function to run on success.

[onFailure] function

Callback function to run on failure.

page.stabilize([onSuccess], [onFailure])

Apply FlaggedRevs protection settings. Only works on wikis where the extension is installed ($wgFlaggedRevsProtection = true i.e. where FlaggedRevs settings appear on the "protect" tab).

Kind: instance method of page
See: https://www.mediawiki.org/wiki/Extension:FlaggedRevs Referred to as "pending changes" on-wiki.

Param Type
[onSuccess] function
[onFailure] function

page~fnCanUseMwUserToken([action]) ⇒ boolean

Determines whether we can save an API call by using the csrf token sent with the page HTML, or whether we need to ask the server for more info (e.g. protection or watchlist expiry).

Currently used for append, prepend, newSection, move, stabilize, deletePage, and undeletePage. Not used for protect since it always needs to request protection status.

Kind: inner method of page

Param Type Default Description
[action] string "edit"

The action being undertaken, e.g. "edit" or "delete". In practice, only "edit" or "notedit" matters.

page~fnNeedTokenInfoQuery(action) ⇒ object

When functions can't use fnCanUseMwUserToken or require checking protection or watched status, maintain the query in one place. Used for delete, undelete, {@link* Morebits.wiki.page#protect|protect}, stabilize, and move (basically, just not load).

Kind: inner method of page
Returns: object - Appropriate query.

Param Type Description
action string

The action being undertaken, e.g. "edit" or "delete".

page~fnPreflightChecks(action, onFailure) ⇒ boolean

Common checks for action methods. Used for move, undelete, delete, protect, stabilize.

Kind: inner method of page

Param Type Description
action string

The action being checked.

onFailure string

Failure callback.

page~fnProcessChecks(action, onFailure, response) ⇒ boolean

Common checks for fnProcess functions (fnProcessDelete, fnProcessMove, etc. Used for move, undelete, delete, protect, stabilize.

Kind: inner method of page

Param Type Description
action string

The action being checked.

onFailure string

Failure callback.

response string

The response document from the API call.

wiki.preview

Kind: static class of wiki

new Morebits.wiki.preview(previewbox)

Use the API to parse a fragment of wikitext and render it as HTML.

The suggested implementation pattern (in simpleWindow and quickForm situations) is to construct a Morebits.wiki.preview object after rendering a Morebits.quickForm, and bind the object to an arbitrary property of the form (e.g. |previewer|). For an example, see twinklewarn.js.

Param Type Description
previewbox HTMLElement

The element that will contain the rendered HTML, usually a

element.

preview.beginRender(wikitext, [pageTitle], [sectionTitle])

Displays the preview box, and begins an asynchronous attempt to render the specified wikitext.

Kind: instance method of preview

Param Type Description
wikitext string

Wikitext to render; most things should work, including subst: and ~~~~.

[pageTitle] string

Optional parameter for the page this should be rendered as being on, if omitted it is taken as the current page.

[sectionTitle] string

If provided, render the text as a new section using this as the title.

preview.closePreview()

Hides the preview box and clears it.

Kind: instance method of preview

wiki.numberOfActionsLeft : number

Kind: static property of wiki

wiki.nbrOfCheckpointsLeft : number

Kind: static property of wiki

wiki.isPageRedirect() ⇒ boolean

Deprecated

Kind: static method of wiki

wiki.actionCompleted()

Display message and/or redirect to page upon completion of tasks.

Every call to Morebits.wiki.api.post() results in the dispatch of an asynchronous callback. Each callback can in turn make an additional call to Morebits.wiki.api.post() to continue a processing sequence. At the conclusion of the final callback of a processing sequence, it is not possible to simply return to the original caller because there is no call stack leading back to the original context. Instead, Morebits.wiki.actionCompleted.event() is called to display the result to the user and to perform an optional page redirect.

The determination of when to call Morebits.wiki.actionCompleted.event() is managed through the globals Morebits.wiki.numberOfActionsLeft and Morebits.wiki.nbrOfCheckpointsLeft. Morebits.wiki.numberOfActionsLeft is incremented at the start of every Morebits.wiki.api call and decremented after the completion of a callback function. If a callback function does not create a new Morebits.wiki.api object before exiting, it is the final step in the processing chain and Morebits.wiki.actionCompleted.event() will then be called.

Optionally, callers may use Morebits.wiki.addCheckpoint() to indicate that processing is not complete upon the conclusion of the final callback function. This is used for batch operations. The end of a batch is signaled by calling Morebits.wiki.removeCheckpoint().

Kind: static method of wiki

actionCompleted.timeOut

Kind: static property of actionCompleted

actionCompleted.redirect

Kind: static property of actionCompleted

actionCompleted.notice

Kind: static property of actionCompleted

actionCompleted.event()

Kind: static method of actionCompleted

wiki.addCheckpoint()

Kind: static method of wiki

wiki.removeCheckpoint()

Kind: static method of wiki

Morebits.wikitext : object

Wikitext manipulation.

Kind: static namespace of Morebits

wikitext.page

Kind: static class of wikitext

new Morebits.wikitext.page(text)

Adjust and manipulate the wikitext of a page.

Param Type Description
text string

Wikitext to be manipulated.

page.removeLink(link_target) ⇒ page

Removes links to link_target from the page text.

Kind: instance method of page

Param Type
link_target string

page.commentOutImage(image, [reason]) ⇒ page

Comments out images from page text; if used in a gallery, deletes the whole line. If used as a template argument (not necessarily with File: prefix), the template parameter is commented out.

Kind: instance method of page

Param Type Description
image string

Image name without File: prefix.

[reason] string

Reason to be included in comment, alongside the commented-out image.

page.addToImageComment(image, data) ⇒ page

Converts uses of [[File:image]] to [[File:image|data]].

Kind: instance method of page

Param Type Description
image string

Image name without File: prefix.

data string

The display options.

page.removeTemplate(template) ⇒ page

Remove all transclusions of a template from page text.

Kind: instance method of page

Param Type Description
template string

Page name whose transclusions are to be removed, include namespace prefix only if not in template namespace.

page.insertAfterTemplates(tag, regex, [flags], [preRegex]) ⇒ page

Smartly insert a tag atop page text but after specified templates, such as hatnotes, short description, or deletion and protection templates. Notably, does not insert a newline after the tag.

Kind: instance method of page

Param Type Default Description
tag string

The tag to be inserted.

regex string | Array.<string>

Templates after which to insert tag, given as either as a (regex-valid) string or an array to be joined by pipes.

[flags] string "i"

Regex flags to apply. '' to provide no flags; other falsey values will default to i.

[preRegex] string | Array.<string>

Optional regex string or array to match before any template matches (i.e. before {{), such as html comments.

page.getText() ⇒ string

Get the manipulated wikitext.

Kind: instance method of page

wikitext.parseTemplate(text, [start]) ⇒ object

Get the value of every parameter found in the wikitext of a given template.

Kind: static method of wikitext
Returns: object - {name: templateName, parameters: {key: value}}.

Param Type Default Description
text string

Wikitext containing a template.

[start] number 0

Index noting where in the text the template begins.

parseTemplate~findParam([final])

Function to handle finding parameter values.

Kind: inner method of parseTemplate

Param Type Default Description
[final] boolean false

Whether this is the final parameter and we need to remove the trailing }}.

Morebits.userIsInGroup(group) ⇒ boolean

Simple helper function to see what groups a user might belong.

Kind: static method of Morebits

Param Type Description
group string

e.g. sysop, extendedconfirmed, etc.

Morebits.sanitizeIPv6(address) ⇒ string

Deprecated

Deprecated as of February 2021, use sanitizeIPv6.

Kind: static method of Morebits

Param Type Description
address string

The IPv6 address, with or without CIDR.

Morebits.isPageRedirect() ⇒ boolean

Determines whether the current page is a redirect or soft redirect. Fails to detect soft redirects on edit, history, etc. pages. Will attempt to detect Module:Redirect for discussion, with the same failure points.

Kind: static method of Morebits

Morebits.pageNameRegex(pageName) ⇒ string

Create a string for use in regex matching a page name. Accounts for leading character's capitalization, underscores as spaces, and special characters being escaped. See also namespaceRegex.

Kind: static method of Morebits
Returns: string - - For a page name Foo bar, returns the string [Ff]oo[_ ]bar.

Param Type Description
pageName string

Page name without namespace.

Morebits.namespaceRegex(namespaces) ⇒ string

Create a string for use in regex matching all namespace aliases, regardless of the capitalization and underscores/spaces. Doesn't include the optional leading :, but if there's more than one item, wraps the list in a non-capturing group. This means you can do Morebits.namespaceRegex([4]) + ':' + Morebits.pageNameRegex('Twinkle') to match a full page. Uses pageNameRegex.

Kind: static method of Morebits
Returns: string - - Regex-suitable string of all namespace aliases.

Param Type Description
namespaces Array.<number>

Array of namespace numbers. Unused/invalid namespace numbers are silently discarded.

Example

// returns '(?:[Ff][Ii][Ll][Ee]|[Ii][Mm][Aa][Gg][Ee])'
Morebits.namespaceRegex([6])

Morebits.htmlNode(type, content, [color]) ⇒ HTMLElement

Simple helper function to create a simple node.

Kind: static method of Morebits

Param Type Description
type string

Type of HTML element.

content string

Text content.

[color] string

Font color.

Morebits.checkboxShiftClickSupport(jQuerySelector, jQueryContext)

Add shift-click support for checkboxes. The wikibits version (window.addCheckboxClickHandlers) has some restrictions, and doesn't work with checkboxes inside a sortable table, so let's build our own.

Kind: static method of Morebits

Param
jQuerySelector
jQueryContext

documentation generated on Sun Feb 14 2021

Clone this wiki locally