Eventify TemplateDataGenerator and use oojs-ui

Change the ui/data behavior to work with oojs and event emitters,
and replace the gui from jquery ui to oojs-ui.

Changes made:
* Recreate the templatedata editor with oojs and ooui.
* Create a standalone templatedata model with internal validation.
* Allow the user to insert language-specific strings:
  * Allow adding arbitrary languages and values
  * Normalize output between language object and 'simple' string
  * Add new language code by searching for its name or code
* Import parameters from template code
  * If the template is in subpage and there is no code in the
    current page, the code will request the contents of the parent
    page.

Change-Id: I985ea03dfee58984ec22ec9a157a00968bfca878
This commit is contained in:
Moriel Schottlender 2014-10-11 01:22:21 -04:00
parent 6ddefe6131
commit df59f0179a
25 changed files with 3822 additions and 1769 deletions

View file

@ -2,7 +2,6 @@
// Enforcing
"bitwise": true,
"eqeqeq": true,
"es3": true,
"freeze": true,
"latedef": true,
"noarg": true,
@ -11,12 +10,25 @@
"unused": true,
"strict": false,
// Relaxing
"es5": false,
// Environment
"browser": true,
"jquery": true,
"globals": {
"jQuery": false,
"mw": false,
"OO": false,
"QUnit": false,
"mediaWiki": false
"unicodeJS": false,
"jQuery": false,
"mediaWiki": false,
"TemplateDataModel": true,
"TemplateDataDialog": true,
"TemplateDataOptionWidget": true,
"TemplateDataOptionImportWidget": true,
"TemplateDataLanguageSearchWidget": true,
"TemplateDataLanguageResultWidget": true
}
}

View file

@ -34,13 +34,36 @@ class TemplateDataHooks {
) {
$testModules['qunit']['ext.templateData.test'] = array(
'scripts' => array( 'tests/ext.templateData.tests.js' ),
'dependencies' => array( 'ext.templateDataGenerator.core' ),
'dependencies' => array( 'ext.templateDataGenerator.data' ),
'localBasePath' => __DIR__ ,
'remoteExtPath' => 'TemplateData',
);
return true;
}
/**
* Conditionally register the jquery.uls.data module, in case they've already
* been registered by the UniversalLanguageSelector extension.
*
* @param ResourceLoader $resourceLoader
* @return boolean true
*/
public static function onResourceLoaderRegisterModules( ResourceLoader &$resourceLoader ) {
$resourceModules = $resourceLoader->getConfig()->get( 'ResourceModules' );
if ( !isset( $resourceModules['jquery.uls.data'] ) ) {
$resourceLoader->register( array(
'jquery.uls.data' => array(
'localBasePath' => __DIR__,
'remoteExtPath' => 'TemplateData',
'scripts' => array(
'lib/jquery.uls/src/jquery.uls.data.js',
'lib/jquery.uls/src/jquery.uls.data.utils.js',
)
)
) );
}
}
/**
* @param Page &$page
* @param User &$user

View file

@ -39,6 +39,7 @@ $wgHooks['ParserFirstCallInit'][] = 'TemplateDataHooks::onParserFirstCallInit';
$wgHooks['PageContentSave'][] = 'TemplateDataHooks::onPageContentSave';
$wgHooks['UnitTestsList'][] = 'TemplateDataHooks::onUnitTestsList';
$wgHooks['ResourceLoaderTestModules'][] = 'TemplateDataHooks::onResourceLoaderTestModules';
$wgHooks['ResourceLoaderRegisterModules'][] = 'TemplateDataHooks::onResourceLoaderRegisterModules';
$wgHooks['EditPage::showEditForm:initial'][] = 'TemplateDataHooks::onEditPage';
// Register APIs
@ -62,7 +63,7 @@ $wgResourceModules['ext.templateDataGenerator.editPage'] = array(
'modules/ext.templateDataGenerator.editPage.js',
),
'dependencies' => array(
'ext.templateDataGenerator.core',
'ext.templateDataGenerator.ui',
),
'messages' => array(
'templatedata-editbutton',
@ -72,53 +73,83 @@ $wgResourceModules['ext.templateDataGenerator.editPage'] = array(
)
);
$wgResourceModules['ext.templateDataGenerator.core'] = array(
$wgResourceModules['ext.templateDataGenerator.data'] = array(
'localBasePath' => $dir,
'remoteExtPath' => 'TemplateData',
'styles' => 'modules/ext.templateDataGenerator.css',
'scripts' => array(
'modules/ext.templateDataGenerator.core.js',
'modules/ext.templateDataGenerator.data.js'
),
'dependencies' => array(
'jquery.ui.dialog',
'jquery.ui.button',
'jquery.ui.sortable',
'oojs'
)
);
$wgResourceModules['ext.templateDataGenerator.ui'] = array(
'localBasePath' => $dir,
'remoteExtPath' => 'TemplateData',
'styles' => 'modules/ext.templateDataGenerator.ui.css',
'scripts' => array(
'modules/ext.templateDataGenerator.ui.js',
'modules/widgets/ext.templateDataGenerator.optionWidget.js',
'modules/widgets/ext.templateDataGenerator.optionImportWidget.js',
'modules/widgets/ext.templateDataGenerator.languageResultWidget.js',
'modules/widgets/ext.templateDataGenerator.languageSearchWidget.js',
'modules/ext.templateDataGenerator.ui.tdDialog.js',
),
'dependencies' => array(
'oojs-ui',
'ext.templateDataGenerator.data',
'jquery.uls.data'
),
'messages' => array(
'comma-separator',
'templatedata-modal-button-add-language',
'templatedata-modal-button-addparam',
'templatedata-modal-button-apply',
'templatedata-modal-button-back',
'templatedata-modal-button-cancel',
'templatedata-modal-button-changelang',
'templatedata-modal-button-delparam',
'templatedata-modal-button-importParams',
'templatedata-modal-button-saveparam',
'templatedata-modal-current-language',
'templatedata-modal-errormsg',
'templatedata-modal-errormsg-import-noparams',
'templatedata-modal-errormsg-import-paramsalreadyexist',
'templatedata-modal-notice-import-numparams',
'templatedata-modal-placeholder-paramkey',
'templatedata-modal-search-input-placeholder',
'templatedata-modal-table-param-actions',
'templatedata-modal-table-param-aliases',
'templatedata-modal-table-param-autovalue',
'templatedata-modal-table-param-default',
'templatedata-modal-table-param-desc',
'templatedata-modal-table-param-description',
'templatedata-modal-table-param-importoption',
'templatedata-modal-table-param-importoption-subtitle',
'templatedata-modal-table-param-label',
'templatedata-modal-table-param-name',
'templatedata-modal-table-param-required',
'templatedata-modal-table-param-suggested',
'templatedata-modal-table-param-type',
'templatedata-modal-table-param-type-boolean',
'templatedata-modal-table-param-type-boolean',
'templatedata-modal-table-param-type-content',
'templatedata-modal-table-param-type-wiki-file-name',
'templatedata-modal-table-param-type-date',
'templatedata-modal-table-param-type-line',
'templatedata-modal-table-param-type-number',
'templatedata-modal-table-param-type-boolean',
'templatedata-modal-table-param-type-date',
'templatedata-modal-table-param-type-wiki-page-name',
'templatedata-modal-table-param-type-string',
'templatedata-modal-table-param-type-unbalanced-wikitext',
'templatedata-modal-table-param-type-undefined',
'templatedata-modal-table-param-type-wiki-file-name',
'templatedata-modal-table-param-type-wiki-page-name',
'templatedata-modal-table-param-type-wiki-user-name',
'templatedata-modal-table-param-uneditablefield',
'templatedata-modal-title',
'templatedata-modal-title-addparam',
'templatedata-modal-title-choose-language',
'templatedata-modal-title-language',
'templatedata-modal-title-templatedesc',
'templatedata-modal-title-templateparam-details',
'templatedata-modal-title-templateparams',
)
);

View file

@ -38,21 +38,30 @@
"templatedata-invalid-type": "Property \"$1\" is expected to be of type \"$2\".",
"templatedata-invalid-unknown": "Unexpected property \"$1\".",
"templatedata-invalid-value": "Invalid value for property \"$1\".",
"templatedata-modal-button-add-language": "Add language",
"templatedata-modal-button-addparam": "Add parameter",
"templatedata-modal-button-apply": "Apply",
"templatedata-modal-button-back": "Back",
"templatedata-modal-button-cancel": "Cancel",
"templatedata-modal-button-delparam": "Remove",
"templatedata-modal-button-changelang": "Change language",
"templatedata-modal-button-delparam": "Remove parameter information",
"templatedata-modal-button-importParams": "Import parameters",
"templatedata-modal-button-saveparam": "Save",
"templatedata-modal-current-language": "Current language: $1",
"templatedata-modal-errormsg": "Errors found. Please make sure there are no empty or duplicate parameter names, and that the parameter name does not include \"$1\", \"$2\" or \"$3\".",
"templatedata-modal-errormsg-import-noparams": "No new parameters found during import.",
"templatedata-modal-errormsg-import-paramsalreadyexist": "Some parameters were not imported, because they already exist in the editor: $1",
"templatedata-modal-notice-import-numparams": "$1 new {{PLURAL:$1|parameter was|parameters were}} imported.",
"templatedata-modal-notice-import-numparams": "$1 new {{PLURAL:$1|parameter was|parameters were}} imported: $2",
"templatedata-modal-placeholder-paramkey": "Parameter name",
"templatedata-modal-search-input-placeholder": "Search by language name or code",
"templatedata-modal-table-param-actions": "Actions",
"templatedata-modal-table-param-aliases": "Aliases (comma separated)",
"templatedata-modal-table-param-autovalue": "Auto value",
"templatedata-modal-table-param-default": "Default",
"templatedata-modal-table-param-desc": "Description",
"templatedata-modal-table-param-label": "Label",
"templatedata-modal-table-param-description": "Description ($1)",
"templatedata-modal-table-param-importoption": "Add $1 suggested {{PLURAL:$1|parameter|parameters}}",
"templatedata-modal-table-param-importoption-subtitle": "Including: $1",
"templatedata-modal-table-param-label": "Label ($1)",
"templatedata-modal-table-param-name": "Name",
"templatedata-modal-table-param-required": "Required",
"templatedata-modal-table-param-suggested": "Suggested",
@ -70,6 +79,10 @@
"templatedata-modal-table-param-type-wiki-user-name": "User",
"templatedata-modal-table-param-uneditablefield": "Uneditable",
"templatedata-modal-title": "Template documentation editor",
"templatedata-modal-title-templatedesc": "Template description",
"templatedata-modal-title-addparam": "Add new parameter",
"templatedata-modal-title-choose-language": "Choose language",
"templatedata-modal-title-language": "Language",
"templatedata-modal-title-templatedesc": "Template description ($1)",
"templatedata-modal-title-templateparam-details": "Parameter details: $1",
"templatedata-modal-title-templateparams": "Template parameters"
}

View file

@ -1,14 +1,15 @@
{
"@metadata": {
"authors": [
"Sethladan",
"Shirayuki",
"Timo Tijhof",
"Robby",
"Stryn",
"Liuxinyu970226",
"Nike",
"Raymond",
"Liuxinyu970226"
"Robby",
"Sethladan",
"Shirayuki",
"Stryn",
"Timo Tijhof",
"Moriel Schottlender"
]
},
"apihelp-templatedata-description": "{{doc-apihelp-description|templatedata}}",
@ -44,25 +45,34 @@
"templatedata-invalid-type": "Error message when a property is of the wrong type.\n* $1 - name of property. e.g. \"params.1.required\"\n* $2 - expected type of property. e.g. \"boolean\"",
"templatedata-invalid-unknown": "Error message when an unknown property is found.\n* $1 - name of property. e.g. \"params.1.foobar\"",
"templatedata-invalid-value": "Error message when a property that cannot contain free-form text has an invalid value.\n* $1 - name of property. e.g. \"params.1.type\"",
"templatedata-modal-button-add-language": "Label for the button to add a language in the edit dialog.",
"templatedata-modal-button-addparam": "Button to add a parameter.\n{{Identical|Add parameter}}",
"templatedata-modal-button-apply": "Label of the apply button.\n{{Identical|Apply}}",
"templatedata-modal-button-back": "Label for the button to go back in the templatedata edit dialog.",
"templatedata-modal-button-cancel": "Label of the cancel button.\n{{Identical|Cancel}}",
"templatedata-modal-button-changelang": "Label for the button to change language in the edit dialog.",
"templatedata-modal-button-delparam": "Button to remove a parameter.\n{{Identical|Remove}}",
"templatedata-modal-button-importParams": "Label of the import button",
"templatedata-modal-button-saveparam": "Label for the button to save parameter details in the templatedata edit dialog.",
"templatedata-modal-current-language": "Label displaying the current language in the edit dialog. $1 - currently showing language.",
"templatedata-modal-errormsg": "Error message that appears in the TemplateData generator GUI in case there are empty, duplicate or invalid parameter names.\n\nInvalid characters are supplied as parameters to avoid parsing errors in translation strings.\n\nParameters:\n* $1 - pipe (<code>|</code>)\n* $2 - equal sign (<code>=</code>)\n* $3 - double curly brackets (<code><nowiki>}}</nowiki></code>)",
"templatedata-modal-errormsg-import-noparams": "Error message that appears in the TemplateData generator GUI in case no template parameters were found during the import attempt.",
"templatedata-modal-errormsg-import-paramsalreadyexist": "Error message that appears when some parameters were not imported from the template code because they already exist in the editor.\n\nParameters:\n* $1 - list of parameters that were not imported",
"templatedata-modal-notice-import-numparams": "Message that appears in the TemplateData generator GUI showing how many new parameters were imported into the GUI from an existing template.\n\nParameters:\n* $1 - number of parameters",
"templatedata-modal-table-param-actions": "Label for a table heading: Parameter actions in the table\n{{Identical|Action}}",
"templatedata-modal-table-param-aliases": "Label for a table heading: Aliases of the parameter, instruct the user to separate aliases with commas.",
"templatedata-modal-table-param-autovalue": "Label for a table heading: Parameter auto value in the table",
"templatedata-modal-table-param-default": "Label for a table heading: Default value of the parameter.\n{{Identical|Default}}",
"templatedata-modal-table-param-desc": "Label for a table heading: Description of the parameter.\n{{Identical|Description}}",
"templatedata-modal-table-param-label": "Label for a table heading: Label of the parameter.\n\nSee https://en.wikipedia.org/w/index.php?title=Template:Infobox_treaty/TemplateData&action=edit for example.\n{{Identical|Label}}",
"templatedata-modal-table-param-name": "Label for a table heading: Name of the parameter.\n{{Identical|Name}}",
"templatedata-modal-table-param-required": "Label for a table heading: Required status of the parameter.\n{{Identical|Required}}",
"templatedata-modal-table-param-suggested": "Label for a table heading: Suggested status of the parameter.\n{{Identical|Suggested}}",
"templatedata-modal-table-param-type": "Label for a table heading: Type of the parameter.\n{{Identical|Type}}",
"templatedata-modal-notice-import-numparams": "Message that appears in the TemplateData generator GUI showing how many new parameters were imported into the GUI from an existing template.\n\nParameters:\n* $1 - number of parameters. $2 - list of parameters that were imported",
"templatedata-modal-placeholder-paramkey": "Placeholder for the input that contains new parameter name in the add parameter panel in the edit dialog.",
"templatedata-modal-search-input-placeholder": "Placeholder text for language search panel.",
"templatedata-modal-table-param-actions": "Label for a parameter property input: Parameter actions in the table",
"templatedata-modal-table-param-aliases": "Label for a parameter property input: Aliases of the parameter, instruct the user to separate aliases with commas.",
"templatedata-modal-table-param-autovalue": "Label for a parameter property input: Parameter auto value in the table",
"templatedata-modal-table-param-default": "Label for a parameter property input: Default value of the parameter.\n{{Identical|Default}}",
"templatedata-modal-table-param-description": "Label for a parameter property input: Description of the parameter. $1 - currently showing language.\n{{Identical|Description}}",
"templatedata-modal-table-param-importoption": "Label for the import option in the parameter list in the edit dialog. $1 - number of suggested parameters that can be imported.",
"templatedata-modal-table-param-importoption-subtitle": "A list of suggested parameter names in the import option in the parameter list in the edit dialog. $1 - list (or partial list) of suggested parameter names to import.",
"templatedata-modal-table-param-label": "Label for a parameter property input: Label of the parameter.\n\nSee https://en.wikipedia.org/w/index.php?title=Template:Infobox_treaty/TemplateData&action=edit for example. $1 - currently showing language.\n{{Identical|Label}}",
"templatedata-modal-table-param-name": "Label for a parameter property input: Name of the parameter.\n{{Identical|Name}}",
"templatedata-modal-table-param-required": "Label for a parameter property input: Required status of the parameter.\n{{Identical|Required}}",
"templatedata-modal-table-param-suggested": "Label for a parameter property input: Suggested status of the parameter.\n{{Identical|Suggested}}",
"templatedata-modal-table-param-type": "Label for a parameter property input: Type of the parameter.\n{{Identical|Type}}",
"templatedata-modal-table-param-type-boolean": "A possible parameter type: Boolean\n{{Related|Templatedata-modal-table-param-type}}",
"templatedata-modal-table-param-type-content": "A possible parameter type: Content\n{{Related|Templatedata-modal-table-param-type}}\n{{Identical|Content}}",
"templatedata-modal-table-param-type-date": "A possible parameter type: Date\n{{Related|Templatedata-modal-table-param-type}}\n{{Identical|Date}}",
@ -74,8 +84,12 @@
"templatedata-modal-table-param-type-wiki-file-name": "A possible parameter type: File\n{{Related|Templatedata-modal-table-param-type}}\n{{Identical|File}}",
"templatedata-modal-table-param-type-wiki-page-name": "A possible parameter type: Page\n{{Related|Templatedata-modal-table-param-type}}\n{{Identical|Page}}",
"templatedata-modal-table-param-type-wiki-user-name": "A possible parameter type: User\n{{Related|Templatedata-modal-table-param-type}}\n{{Identical|User}}",
"templatedata-modal-table-param-uneditablefield": "Placeholder text notifying the user the field is uneditable\n{{Identical|Uneditable}}",
"templatedata-modal-title": "Title of the modal popup.",
"templatedata-modal-title-templatedesc": "The title for the template description textbox",
"templatedata-modal-table-param-uneditablefield": "Placeholder text notifying the user the field is uneditable",
"templatedata-modal-title": "Title of the edit dialog.",
"templatedata-modal-title-addparam": "Title for add new parameter panel in the edit dialog.\n{{Identical|Add parameter}}",
"templatedata-modal-title-choose-language": "Title for the choose language panel in the edit dialog.",
"templatedata-modal-title-language": "Label for the language dropdown in the edit menu.",
"templatedata-modal-title-templatedesc": "The title for the template description textbox. $1 - currently used language.",
"templatedata-modal-title-templateparam-details": "The title for the parameter information section. $1: The parameter name.",
"templatedata-modal-title-templateparams": "The title for the template parameters table"
}

13
lib/jquery.uls/CREDITS Normal file
View file

@ -0,0 +1,13 @@
Universal Language Selector, part of Project Milkshake, is a collaborative
project released under the GNU General Public License v2. We would like to
recognize the following names for their contribution to the product.
== Developers ==
* Alolita Sharma
* Amir Aharoni
* Arun Ganesh
* Brandon Harris
* Niklas Laxström
* Pau Giner
* Santhosh Thottingal
* Siebrand Mazeland

342
lib/jquery.uls/GPL-LICENSE Normal file
View file

@ -0,0 +1,342 @@
== GNU GENERAL PUBLIC LICENSE ==
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
=== Preamble ===
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
== TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION ==
'''0.''' This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
'''1.''' You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
'''2.''' You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
'''a)''' You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
'''b)''' You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
'''c)''' If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
'''3.''' You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
'''a)''' Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
'''b)''' Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
'''c)''' Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
'''4.''' You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
'''5.''' You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
'''6.''' Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
'''7.''' If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
'''8.''' If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
'''9.''' The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
'''10.''' If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
=== NO WARRANTY ===
'''11.''' BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
'''12.''' IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
'''END OF TERMS AND CONDITIONS'''
== How to Apply These Terms to Your New Programs ==
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,465 @@
/**
* Utility functions for querying language data.
*
* Copyright (C) 2012 Alolita Sharma, Amir Aharoni, Arun Ganesh, Brandon Harris,
* Niklas Laxström, Pau Giner, Santhosh Thottingal, Siebrand Mazeland and other
* contributors. See CREDITS for a list.
*
* UniversalLanguageSelector is dual licensed GPLv2 or later and MIT. You don't
* have to do anything special to choose one license or the other and you don't
* have to notify anyone which license you are using. You are free to use
* UniversalLanguageSelector in commercial projects as long as the copyright
* header is left intact. See files GPL-LICENSE and MIT-LICENSE for details.
*
* @file
* @ingroup Extensions
* @licence GNU General Public Licence 2.0 or later
* @licence MIT License
*/
( function ( $ ) {
'use strict';
/**
* Is this language a redirect to another language?
* @param language string Language code
* @return Target language code if it's a redirect or false if it's not
*/
$.uls.data.isRedirect = function ( language ) {
return ( $.uls.data.languages[language] !== undefined &&
$.uls.data.languages[language].length === 1 ) ? $.uls.data.languages[language][0] : false;
};
/**
* Returns the script of the language.
* @param language string Language code
* @return string
*/
$.uls.data.getScript = function ( language ) {
var target = $.uls.data.isRedirect( language );
if ( target ) {
return $.uls.data.getScript( target );
}
if ( !$.uls.data.languages[language] ) {
// Undetermined
return 'Zyyy';
}
return $.uls.data.languages[language][0];
};
/**
* Returns the regions in which a language is spoken.
* @param language string Language code
* @return array|string 'UNKNOWN'
*/
$.uls.data.getRegions = function ( language ) {
var target = $.uls.data.isRedirect( language );
if ( target ) {
return $.uls.data.getRegions( target );
}
return ( $.uls.data.languages[language] && $.uls.data.languages[language][1] ) || 'UNKNOWN';
};
/**
* Returns the autonym of the language.
* @param language string Language code
* @return string
*/
$.uls.data.getAutonym = function ( language ) {
var target = $.uls.data.isRedirect( language );
if ( target ) {
return $.uls.data.getAutonym( target );
}
return ( $.uls.data.languages[language] && $.uls.data.languages[language][2] ) || language;
};
/**
* Returns all language codes and corresponding autonyms
* @return array
*/
$.uls.data.getAutonyms = function () {
var language,
autonymsByCode = {};
for ( language in $.uls.data.languages ) {
if ( $.uls.data.isRedirect( language ) ) {
continue;
}
autonymsByCode[language] = $.uls.data.getAutonym( language );
}
return autonymsByCode;
};
/**
* Returns an array of all region codes.
* @return array
*/
$.uls.data.getAllRegions = function () {
var region,
allRegions = [];
for ( region in $.uls.data.regiongroups ) {
allRegions.push( region );
}
return allRegions;
};
/**
* Returns all languages written in script.
* @param script string
* @return array of strings (languages codes)
*/
$.uls.data.getLanguagesInScript = function ( script ) {
return $.uls.data.getLanguagesInScripts( [ script ] );
};
/**
* Returns all languages written in the given scripts.
* @param scripts array of strings
* @return array of strings (languages codes)
*/
$.uls.data.getLanguagesInScripts = function ( scripts ) {
var language, i,
languagesInScripts = [];
for ( language in $.uls.data.languages ) {
if ( $.uls.data.isRedirect( language ) ) {
continue;
}
for ( i = 0; i < scripts.length; i++ ) {
if ( scripts[i] === $.uls.data.getScript( language ) ) {
languagesInScripts.push( language );
break;
}
}
}
return languagesInScripts;
};
/**
* Returns all languages in a given region.
* @param region string
* @return array of strings (languages codes)
*/
$.uls.data.getLanguagesInRegion = function ( region ) {
return $.uls.data.getLanguagesInRegions( [ region ] );
};
/**
* Returns all languages in given regions.
* @param regions array of strings.
* @return array of strings (languages codes)
*/
$.uls.data.getLanguagesInRegions = function ( regions ) {
var language, i,
languagesInRegions = [];
for ( language in $.uls.data.languages ) {
if ( $.uls.data.isRedirect( language ) ) {
continue;
}
for ( i = 0; i < regions.length; i++ ) {
if ( $.inArray( regions[i], $.uls.data.getRegions( language ) ) !== -1 ) {
languagesInRegions.push( language );
break;
}
}
}
return languagesInRegions;
};
/**
* Returns all languages in a region group.
* @param groupNum number.
* @return array of strings (languages codes)
*/
$.uls.data.getLanguagesInRegionGroup = function ( groupNum ) {
return $.uls.data.getLanguagesInRegions( $.uls.data.getRegionsInGroup( groupNum ) );
};
/**
* Returns an associative array of languages in a region,
* grouped by script.
* @param region string Region code
* @return associative array
*/
$.uls.data.getLanguagesByScriptInRegion = function ( region ) {
var language, script,
languagesByScriptInRegion = {};
for ( language in $.uls.data.languages ) {
if ( $.uls.data.isRedirect( language ) ) {
continue;
}
if ( $.inArray( region, $.uls.data.getRegions( language ) ) !== -1 ) {
script = $.uls.data.getScript( language );
if ( languagesByScriptInRegion[script] === undefined ) {
languagesByScriptInRegion[script] = [];
}
languagesByScriptInRegion[script].push( language );
}
}
return languagesByScriptInRegion;
};
/**
* Returns an associative array of languages in a region,
* grouped by script group.
* @param region string Region code
* @return associative array
*/
$.uls.data.getLanguagesByScriptGroupInRegion = function ( region ) {
return $.uls.data.getLanguagesByScriptGroupInRegions( [ region ] );
};
/**
* Returns an associative array of all languages,
* grouped by script group.
* @return associative array
*/
$.uls.data.getAllLanguagesByScriptGroup = function () {
return $.uls.data.getLanguagesByScriptGroupInRegions( $.uls.data.getAllRegions() );
};
/**
* Get the given list of languages grouped by script.
* @param languages Array of language codes
* @return {Object} Array of languages indexed by script codes
*/
$.uls.data.getLanguagesByScriptGroup = function ( languages ) {
var languagesByScriptGroup = {},
language, codeToAdd, langScriptGroup;
for ( language in languages ) {
codeToAdd = $.uls.data.isRedirect( language ) || language;
langScriptGroup = $.uls.data.getScriptGroupOfLanguage( codeToAdd );
if ( !languagesByScriptGroup[langScriptGroup] ) {
languagesByScriptGroup[langScriptGroup] = [];
}
// Prevent duplicate adding of redirects
if ( $.inArray( codeToAdd, languagesByScriptGroup[langScriptGroup] ) === -1 ) {
languagesByScriptGroup[langScriptGroup].push( codeToAdd );
}
}
return languagesByScriptGroup;
};
/**
* Returns an associative array of languages in several regions,
* grouped by script group.
* @param regions array of strings - region codes
* @return associative array
*/
$.uls.data.getLanguagesByScriptGroupInRegions = function ( regions ) {
var language, i, scriptGroup,
languagesByScriptGroupInRegions = {};
for ( language in $.uls.data.languages ) {
if ( $.uls.data.isRedirect( language ) ) {
continue;
}
for ( i = 0; i < regions.length; i++ ) {
if ( $.inArray( regions[i], $.uls.data.getRegions( language ) ) !== -1 ) {
scriptGroup = $.uls.data.getScriptGroupOfLanguage( language );
if ( languagesByScriptGroupInRegions[scriptGroup] === undefined ) {
languagesByScriptGroupInRegions[scriptGroup] = [];
}
languagesByScriptGroupInRegions[scriptGroup].push( language );
break;
}
}
}
return languagesByScriptGroupInRegions;
};
/**
* Returns an array of languages grouped by region group,
* region, script group and script.
* @return associative array
*/
$.uls.data.getAllLanguagesByRegionAndScript = function () {
var region, regionGroup, language,
script, scriptGroup, regions, regionNum,
allLanguagesByRegionAndScript = {};
for ( region in $.uls.data.regiongroups ) {
regionGroup = $.uls.data.regiongroups[region];
if ( allLanguagesByRegionAndScript[regionGroup] === undefined ) {
allLanguagesByRegionAndScript[regionGroup] = {};
}
allLanguagesByRegionAndScript[regionGroup][region] = {};
}
for ( language in $.uls.data.languages ) {
if ( $.uls.data.isRedirect( language ) ) {
continue;
}
script = $.uls.data.getScript( language );
scriptGroup = $.uls.data.getGroupOfScript( script );
regions = $.uls.data.getRegions( language );
for ( regionNum = 0; regionNum < regions.length; regionNum++ ) {
region = regions[regionNum];
regionGroup = $.uls.data.regiongroups[region];
if ( allLanguagesByRegionAndScript[regionGroup][region][scriptGroup] === undefined ) {
allLanguagesByRegionAndScript[regionGroup][region][scriptGroup] = {};
}
if ( allLanguagesByRegionAndScript[regionGroup][region][scriptGroup][script] === undefined ) {
allLanguagesByRegionAndScript[regionGroup][region][scriptGroup][script] = [];
}
allLanguagesByRegionAndScript[regionGroup][region][scriptGroup][script].push( language );
}
}
return allLanguagesByRegionAndScript;
};
/**
* Returns all regions in a region group.
* @param groupNum int
* @return array of strings
*/
$.uls.data.getRegionsInGroup = function ( groupNum ) {
var region,
regionsInGroup = [];
for ( region in $.uls.data.regiongroups ) {
if ( $.uls.data.regiongroups[region] === groupNum ) {
regionsInGroup.push( region );
}
}
return regionsInGroup;
};
/**
* Returns the script group of a script or 'Other' if it doesn't
* belong to any group.
* @param script string Script code
* @return string script group name
*/
$.uls.data.getGroupOfScript = function ( script ) {
var scriptGroup;
for ( scriptGroup in $.uls.data.scriptgroups ) {
if ( $.inArray( script, $.uls.data.scriptgroups[scriptGroup] ) !== -1 ) {
return scriptGroup;
}
}
return 'Other';
};
/**
* Returns the script group of a language.
* @param language string Language code
* @return string script group name
*/
$.uls.data.getScriptGroupOfLanguage = function ( language ) {
return $.uls.data.getGroupOfScript( $.uls.data.getScript( language ) );
};
/**
* A callback for sorting languages by autonym.
* Can be used as an argument to a sort function.
* @param a string Language code
* @param b string Language code
*/
$.uls.data.sortByAutonym = function ( a, b ) {
var autonymA = $.uls.data.getAutonym( a ) || a,
autonymB = $.uls.data.getAutonym( b ) || b;
return ( autonymA.toLowerCase() < autonymB.toLowerCase() ) ? -1 : 1;
};
/**
* Check if a language is right-to-left.
* @param language string Language code
* @return boolean
*/
$.uls.data.isRtl = function ( language ) {
return $.inArray( $.uls.data.getScript( language ), $.uls.data.rtlscripts ) !== -1;
};
/**
* Return the direction of the language
* @param language string Language code
* @return string
*/
$.uls.data.getDir = function ( language ) {
return $.uls.data.isRtl( language ) ? 'rtl' : 'ltr';
};
/**
* Returns the languages spoken in a territory.
* @param territory string Territory code
* @return list of language codes
*/
$.uls.data.getLanguagesInTerritory = function ( territory ) {
return $.uls.data.territories[territory];
};
/**
* Adds a language in run time and sets its options as provided.
* If the target option is provided, the language is defined as a redirect.
* Other possible options are script, regions and autonym.
*
* @param code string New language code.
* @param options Object Language properties.
* @return list of language codes
*/
$.uls.data.addLanguage = function( code, options ) {
if ( options.target ) {
$.uls.data.languages[code] = [options.target];
} else {
$.uls.data.languages[code] = [options.script, options.regions, options.autonym];
}
};
/**
* Removes a language from the langdb in run time.
*
* @param code string Language code to delete.
* @return true if the language was removed, false otherwise.
*/
$.uls.data.deleteLanguage = function( code ) {
if ( $.uls.data.languages[code] ) {
delete $.uls.data.languages[code];
return true;
}
return false;
};
} ( jQuery ) );

File diff suppressed because it is too large Load diff

View file

@ -1,89 +0,0 @@
.tdg-editscreen-main-button {
padding: 5px;
font-size: 120%;
}
.tdg-editscreen-main-helplink {
margin-left: 15px;
}
.tdg-parameters-table {
width: 100%;
}
.tdg-editTable th,
.tdg-parameters-table td {
padding: 0;
}
.tdg-parameters-table th {
text-align: left;
}
.tdg-parameters-table > tbody > tr:hover > td {
background-color: #BECDD4;
}
.tdg-parameters-table input,
.tdg-parameters-table select,
.tdg-parameters-table textarea,
.tdg-template-description {
background: transparent;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.tdg-parameters-table input:not([type="checkbox"]),
.tdg-parameters-table select,
.tdg-parameters-table textarea {
width: 100%;
border: 1px solid #999999;
padding: 5px;
height: 40px;
}
.tdg-editTable .tdg-title-delbutton,
.tdg-title-required {
width: 80px;
}
.tdg-editTable .tdg-attr-required {
text-align: center;
}
.tdg-editTable .tdg-attr-required label {
display: block;
}
.tdg-attr-type select {
padding-top: 15px;
}
.tdg-attr-type {
width: 130px;
text-align: center;
}
.tdg-editTable .tdgerror {
background-color: #F2CBCB;
}
.tdg-not-in-template {
background: #E6E6FF;
}
/* Start small, grow on focus: */
.tdg-table-head-delbutton {
width: 100px;
}
.tdg-table-head-suggested,
.tdg-table-head-required {
width: 100px;
}
textarea.param-type-input:focus,
input[type="text"].param-type-input:focus {
min-width: 200px;
}
textarea.param-type-input:focus {
height: 70px;
}

File diff suppressed because it is too large Load diff

View file

@ -8,11 +8,21 @@
'use strict';
$( function () {
var $textbox = $( '#wpTextbox1' );
var config = {
isPageSubLevel: false
},
$textbox = $( '#wpTextbox1' ),
pageName = mw.config.get( 'wgPageName' );
// Check if there's an editor textarea and if we're in the proper namespace
if ( $textbox.length && mw.config.get( 'wgCanonicalNamespace' ) === 'Template' ) {
mw.libs.templateDataGenerator.init( $( '#mw-content-text' ), $textbox );
if ( pageName.indexOf( '/' ) > -1 ) {
config.parentPage = pageName.substr( 0, pageName.indexOf( '/' ) );
config.isPageSubLevel = pageName.indexOf( '/' ) > -1;
}
// Prepare the editor
mw.libs.tdgUi.init( $( '#mw-content-text' ), $textbox, config );
}
} );

View file

@ -0,0 +1,72 @@
.tdg-editscreen-main {
margin-bottom: 1em;
}
.tdg-editscreen-main-helplink {
margin-left: 1em;
}
.tdg-editscreen-error-msg {
display: block;
padding: 0.5em;
margin-top: 0.5em;
}
.tdg-TemplateDataDialog-panels .oo-ui-panelLayout {
padding: 1em;
}
.successbox, .errorbox {
padding: .5em 1em
}
.tdg-editscreen-input-error input {
background-color: #FFA3A3;
}
.tdg-TemplateDataOptionWidget-param-name,
.tdg-TemplateDataOptionWidget-param-aliases,
.tdg-TemplateDataOptionWidget-param-description {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
/* HACK: Based on the expected width of this widget, using % produces unreliable results*/
max-width: 33em;
}
.tdg-TemplateDataOptionWidget-param-name {
font-weight: bold;
}
.tdg-TemplateDataOptionWidget-param-aliases {
float: right;
font-size: 0.9em;
}
.tdg-TemplateDataOptionWidget-param-alias {
border-radius: 0.3em;
padding: 0.125em 0.25em;
margin-left: 0.5em;
color: #999;
background-color: #eee;
border: solid 1px #ddd;
}
.tdg-TemplateDataOptionWidget-param-alias:first-child {
background-color: #fff;
}
.tdg-TemplateDataOptionWidget-paramList-param-description {
clear: both;
color: #555;
}
.oo-ui-icon-parameter {
/* @embed */
background-image: url(images/parameter-ltr.svg);
}
.oo-ui-icon-parameter-set {
/* @embed */
background-image: url(images/parameter-set-ltr.svg);
}

View file

@ -0,0 +1,170 @@
( function ( $, mw ) {
/**
* TemplateData Generator data model.
* This singleton is independent of any UI; it expects
* a templatedata string, converts it into the object
* model and manages it, fully event-driven.
*
* @author Moriel Schottlender
*/
'use strict';
mw.libs.tdgUi = ( function () {
var isPageSubLevel,
parentPage,
$textbox,
/**
* ooui Window Manager
*/
tdgDialog,
windowManager,
/**
* Edit window elements
*/
editOpenDialogButton,
editNoticeLabel,
editArea = {
/**
* Display error message in the edit window
* @param {string} msg Message to display
* @param {string} type Message type 'notice' or 'error'
*/
setNoticeMessage: function ( msg, type ) {
type = type || 'error';
editNoticeLabel.$element.toggleClass( 'errorbox', type === 'error' );
editNoticeLabel.setLabel( msg );
editNoticeLabel.$element.show();
},
/**
* Reset the error message in the edit window
*/
resetNoticeMessage: function () {
editNoticeLabel.setLabel( '' );
editNoticeLabel.$element.hide();
}
},
/**
* Respond to edit dialog button click.
*/
onEditOpenDialogButton = function () {
// Reset notice message
editArea.resetNoticeMessage();
// Open the dialog
windowManager.openWindow( tdgDialog, {
wikitext: $textbox.val(),
config: {
parentPage: parentPage,
isPageSubLevel: !!isPageSubLevel
}
} );
},
/**
* Respond to edit dialog apply event
* @param {string} templateDataString New templatedata string
*/
onDialogApply = function ( templateDataString ) {
$textbox.val( replaceTemplateData( templateDataString ) );
},
/**
* Replace the old templatedata string with the new one, or
* insert the new one into the page if an old one doesn't exist
* @param {string} newTemplateData New templatedata string
* @return {string} Full wikitext content with the new templatedata
* string.
*/
replaceTemplateData = function ( newTemplateData ) {
var finalOutput,
fullWikitext = $textbox.val(),
parts = fullWikitext.match(
/<templatedata>([\s\S]*?)<\/templatedata>/i
);
if ( parts && parts[1] ) {
// <templatedata> exists. Replace it
finalOutput = fullWikitext.replace(
/(<templatedata>)([\s\S]*?)(<\/templatedata>)/i,
'<templatedata>\n' + newTemplateData + '\n</templatedata>'
);
} else {
if ( isPageSubLevel ) {
// Add the <templatedata>
finalOutput = fullWikitext + '\n<templatedata>\n' +
newTemplateData +
'\n</templatedata>\n';
} else {
// If we are not in a subpage, add <noinclude> tags
finalOutput = fullWikitext + '\n<noinclude>\n<templatedata>\n' +
newTemplateData +
'\n</templatedata>\n</noinclude>\n';
}
}
return finalOutput;
};
return {
/**
* Initialize UI
* @param {jQuery} $container The container to attach UI buttons to
* @param {jQuery} $editorTextbox The editor textbox to take the
* current wikitext from.
*/
init: function ( $container, $editorTextbox, userConfig ) {
var editHelpButtonWidget,
config = userConfig;
$textbox = $editorTextbox;
parentPage = config.parentPage;
isPageSubLevel = !!config.isPageSubLevel;
editOpenDialogButton = new OO.ui.ButtonWidget( {
label: mw.msg( 'templatedata-editbutton' )
} );
editNoticeLabel = new OO.ui.LabelWidget( {
classes: [ 'tdg-editscreen-error-msg' ]
} )
.toggle( false );
editHelpButtonWidget = new OO.ui.ButtonWidget( {
label: mw.msg( 'templatedata-helplink' ),
classes: [ 'tdg-editscreen-main-helplink' ],
href: 'https://www.mediawiki.org/wiki/Extension:TemplateData',
target: '_blank',
framed: false
} );
// Dialog
windowManager = new OO.ui.WindowManager();
tdgDialog = new TemplateDataDialog( config );
windowManager.addWindows( [ tdgDialog ] );
// Prepend to container
$container
.prepend(
$( '<div>' )
.addClass( 'tdg-editscreen-main' )
.append(
editOpenDialogButton.$element,
editHelpButtonWidget.$element,
editNoticeLabel.$element
)
);
$( 'body' )
.append( windowManager.$element );
// UI events
editOpenDialogButton.connect( this, { click: onEditOpenDialogButton } );
tdgDialog.connect( this, {
apply: onDialogApply
} );
}
};
}() );
}( jQuery, mediaWiki ) );

View file

@ -0,0 +1,823 @@
( function ( mw ) {
/**
* TemplateData Dialog
* @param {Object} config Dialog configuration object
*/
TemplateDataDialog = function TemplateDataDialog( config ) {
// Parent constructor
TemplateDataDialog.super.call( this, config );
this.model = null;
this.language = null;
this.availableLanguages = [];
this.selectedParamKey = '';
this.propInputs = {};
this.propFieldLayout = {};
// Initialize
this.$element.addClass( 'tdg-TemplateDataDialog' );
};
OO.inheritClass( TemplateDataDialog, OO.ui.ProcessDialog );
/* Static properties */
TemplateDataDialog.static.name = 'TemplateDataDialog';
TemplateDataDialog.static.title = mw.msg( 'templatedata-modal-title' );
TemplateDataDialog.static.size = 'large';
TemplateDataDialog.static.actions = [
{
action: 'apply',
label: mw.msg( 'templatedata-modal-button-apply' ),
flags: [ 'primary', 'constructive' ],
modes: 'list'
},
{
action: 'add',
label: mw.msg( 'templatedata-modal-button-addparam' ),
flags: [ 'constructive' ],
modes: 'list'
},
{
action: 'delete',
label: mw.msg( 'templatedata-modal-button-delparam' ),
modes: 'edit',
flags: 'destructive'
},
{
label: mw.msg( 'templatedata-modal-button-cancel' ),
flags: 'safe',
modes: [ 'list', 'error' ]
},
{
action: 'back',
label: mw.msg( 'templatedata-modal-button-back' ),
flags: 'safe',
modes: [ 'edit', 'language', 'add' ]
}
];
/**
* @inheritDoc
*/
TemplateDataDialog.prototype.initialize = function () {
var templateParamsFieldset, languageFieldset,
addParamFieldlayout, languageFieldLayout;
// Parent method
TemplateDataDialog.super.prototype.initialize.call( this );
this.$spinner = this.$( '<div>' ).addClass( 'tdg-spinner' ).text( 'working...' );
this.$body.append( this.$spinner );
this.noticeLabel = new OO.ui.LabelWidget( { $: this.$ } );
this.noticeLabel.$element.hide();
this.panels = new OO.ui.StackLayout( { $: this.$, continuous: false } );
this.listParamsPanel = new OO.ui.PanelLayout( {
$: this.$,
scrollable: true
} );
this.editParamPanel = new OO.ui.PanelLayout( {
$: this.$
} );
this.languagePanel = new OO.ui.PanelLayout( {
$: this.$
} );
this.addParamPanel = new OO.ui.PanelLayout( {
$: this.$
} );
// Language panel
this.newLanguageSearchWidget = new TemplateDataLanguageSearchWidget( {
$: this.$
} );
// Add parameter panel
this.newParamInput = new OO.ui.TextInputWidget( {
$: this.$,
placeholder: mw.msg( 'templatedata-modal-placeholder-paramkey' )
} );
this.addParamButton = new OO.ui.ButtonWidget( {
$: this.$,
label: mw.msg( 'templatedata-modal-button-addparam' )
} );
addParamFieldlayout = new OO.ui.FieldsetLayout( {
$: this.$,
label: mw.msg( 'templatedata-modal-title-addparam' ),
items: [ this.newParamInput, this.addParamButton ]
} );
// Param list panel (main)
this.languageDropdownWidget = new OO.ui.DropdownWidget( { $: this.$ } );
this.languagePanelButton = new OO.ui.ButtonWidget( {
$: this.$,
label: mw.msg( 'templatedata-modal-button-add-language' )
} );
languageFieldLayout = new OO.ui.FieldLayout( this.languageDropdownWidget, {
$: this.$,
align: 'left',
label: mw.msg( 'templatedata-modal-title-language' )
} );
languageFieldset = new OO.ui.FieldsetLayout( {
$: this.$,
items: [ languageFieldLayout, this.languagePanelButton ]
} );
this.descriptionInput = new OO.ui.TextInputWidget( {
$: this.$,
multiline: true,
autosize: true
} );
this.templateDescriptionFieldset = new OO.ui.FieldsetLayout( {
$: this.$,
items: [ this.descriptionInput ]
} );
this.paramListNoticeLabel = new OO.ui.LabelWidget( { $: this.$ } );
this.paramListNoticeLabel.$element.hide();
this.paramSelectWidget = new OO.ui.SelectWidget();
templateParamsFieldset = new OO.ui.FieldsetLayout( {
$: this.$,
label: mw.msg( 'templatedata-modal-title-templateparams' )
} );
templateParamsFieldset.$element.append( this.paramSelectWidget.$element );
// Param details panel
this.$paramDetailsContainer = this.$( '<div>' )
.addClass( 'tdg-TemplateDataDialog-paramDetails' );
this.listParamsPanel.$element
.addClass( 'tdg-templateDataDialog-listParamsPanel' )
.append(
this.paramListNoticeLabel.$element,
languageFieldset.$element,
this.templateDescriptionFieldset.$element,
templateParamsFieldset.$element
);
this.paramEditNoticeLabel = new OO.ui.LabelWidget( { $: this.$ } );
this.paramEditNoticeLabel.$element.hide();
// Edit panel
this.editParamPanel.$element
.addClass( 'tdg-templateDataDialog-editParamPanel' )
.append(
this.paramEditNoticeLabel.$element,
this.$paramDetailsContainer
);
// Language panel
this.languagePanel.$element
.addClass( 'tdg-templateDataDialog-languagePanel' )
.append(
this.newLanguageSearchWidget.$element
);
this.addParamPanel.$element
.addClass( 'tdg-templateDataDialog-addParamPanel' )
.append( addParamFieldlayout.$element );
this.panels.addItems( [
this.listParamsPanel,
this.editParamPanel,
this.languagePanel,
this.addParamPanel
] );
this.panels.setItem( this.listParamsPanel );
this.panels.$element.addClass( 'tdg-TemplateDataDialog-panels' );
// Build param details panel
this.$paramDetailsContainer.append( this.createParamDetails() );
// Initialization
this.$body.append(
this.noticeLabel.$element,
this.panels.$element
);
// Events
this.newLanguageSearchWidget.connect( this, { select: 'newLanguageSearchWidgetSelect' } );
this.addParamButton.connect( this, { click: 'onAddParamButtonClick' } );
this.descriptionInput.connect( this, { change: 'onDescriptionInputChange' } );
this.languagePanelButton.connect( this, { click: 'onLanguagePanelButton' } );
this.languageDropdownWidget.getMenu().connect( this, { choose: 'onLanguageDropdownWidgetChoose' } );
this.paramSelectWidget.connect( this, { choose: 'onParamSelectWidgetChoose' } );
};
/**
* Respond to model change of description event
* @param {jQuery.event} event Event details
* @param {string} description New description
*/
TemplateDataDialog.prototype.onModelChangeDescription = function ( description ) {
this.descriptionInput.setValue( description );
};
/**
* Respond to description input change event
*/
TemplateDataDialog.prototype.onDescriptionInputChange = function ( value ) {
if ( this.model.getTemplateDescription() !== value ) {
this.model.setTemplateDescription( value, this.language );
}
};
/**
* Respond to add language button click
*/
TemplateDataDialog.prototype.onLanguagePanelButton = function () {
this.switchPanels( 'language' );
};
/**
* Respond to language select widget choose event
* @param {OO.ui.OptionWidget} item Chosen item
*/
TemplateDataDialog.prototype.onLanguageDropdownWidgetChoose = function ( item ) {
var language = item ? item.getData() : this.language;
// Change current language
if ( language !== this.language ) {
this.language = language;
// Update description label
this.templateDescriptionFieldset.setLabel( mw.msg( 'templatedata-modal-title-templatedesc', this.language ) );
// Update description value
this.descriptionInput.setValue( this.model.getTemplateDescription( language ) );
// Update all param descriptions in the param select widget
this.repopulateParamSelectWidget();
// Update the parameter detail page
this.updateParamDetailsLanguage( this.language );
this.emit( 'change-language', this.language );
}
};
/**
* Respond to add language button
* @param {Object} data Data from the selected option widget
*/
TemplateDataDialog.prototype.newLanguageSearchWidgetSelect = function ( data ) {
var languageButton,
newLanguage = data.code;
if (
newLanguage &&
$.inArray( newLanguage, this.availableLanguages ) === -1
) {
// Add new language
this.availableLanguages.push( newLanguage );
languageButton = new OO.ui.OptionWidget( {
data: newLanguage,
$: this.$,
label: $.uls.data.getAutonym( newLanguage )
} );
this.languageDropdownWidget.getMenu().addItems( [ languageButton ] );
}
// Go to the main panel
this.switchPanels( 'listParams' );
};
/**
* Respond to add parameter button
*/
TemplateDataDialog.prototype.onAddParamButtonClick = function () {
var newParamKey = this.newParamInput.getValue(),
allProps = TemplateDataModel.static.getAllProperties( true );
// Validate parameter
if (
!newParamKey.match( allProps.name.restrict ) &&
$.inArray( newParamKey, this.model.getAllParamNames() ) === -1
) {
// Add to model
if ( this.model.addParam( newParamKey ) ) {
// Add parameter to list
this.addParamToSelectWidget( newParamKey );
// Empty the parameter
this.newParamInput.setValue( '' );
// Go back to list
this.switchPanels( 'listParams' );
}
}
};
/**
* Respond to choose event from the param select widget
* @param {OO.ui.OptionWidget} item Parameter item
*/
TemplateDataDialog.prototype.onParamSelectWidgetChoose = function ( item ) {
var paramKey = item.getData();
if ( paramKey === 'tdg-importParameters' ) {
// Import
this.importParametersFromTemplateCode();
} else {
this.selectedParamKey = paramKey;
// Fill in parameter detail
this.getParameterDetails( paramKey );
this.switchPanels( 'editParam' );
}
};
TemplateDataDialog.prototype.onParamPropertyInputChange = function ( property, value ) {
var err = false,
anyInputError = false,
allProps = TemplateDataModel.static.getAllProperties( true );
if ( property === 'type' ) {
value = this.propInputs[property].getSelectedItem() ? this.propInputs[property].getSelectedItem().getData() : 'undefined';
}
// TODO: Validate the name
if ( allProps[property].restrict ) {
if ( value.match( allProps[property].restrict ) ) {
// Error! Don't fix the model
err = true;
this.toggleNoticeMessage( 'edit', true, 'error', mw.msg( 'templatedata-modal-errormsg', '|', '=', '}}' ) );
} else {
this.toggleNoticeMessage( 'edit', false );
}
}
this.propInputs[property].$element.toggleClass( 'tdg-editscreen-input-error', err );
// Validate
$( '.tdg-TemplateDataDialog-paramInput' ).each( function () {
if ( $( this ).hasClass( 'tdg-editscreen-input-error' ) ) {
anyInputError = true;
}
} );
// Disable the 'back' button if there are any errors in the inputs
this.actions.setAbilities( { back: !anyInputError } );
if ( !err ) {
this.model.setParamProperty( this.selectedParamKey, property, value, this.language );
}
};
/**
* Set the parameter details in the detail panel.
* @param {Object} paramKey Parameter details
*/
TemplateDataDialog.prototype.getParameterDetails = function ( paramKey ) {
var prop,
paramData = this.model.getParamData( paramKey );
for ( prop in this.propInputs ) {
this.changeParamPropertyInput( paramKey, prop, paramData[prop], this.language );
}
};
/**
* Reset contents on reload
*/
TemplateDataDialog.prototype.reset = function () {
this.language = null;
this.availableLanguages = [];
if ( this.paramSelectWidget ) {
this.paramSelectWidget.clearItems();
this.selectedParamKey = '';
}
if ( this.languageDropdownWidget ) {
this.languageDropdownWidget.getMenu().clearItems();
}
};
/**
* Empty and repopulate the parameter select widget.
*/
TemplateDataDialog.prototype.repopulateParamSelectWidget = function () {
var paramKey,
missingParams = this.model.getMissingParams(),
paramList = this.model.getParams();
this.paramSelectWidget.clearItems();
// Update all param descriptions in the param select widget
this.paramSelectWidget.clearItems();
for ( paramKey in paramList ) {
if ( !paramList[paramKey].deleted ) {
this.addParamToSelectWidget( paramKey );
}
}
// Check if there are potential parameters to add
// from the template source code
if ( missingParams.length > 0 ) {
// Add a final option
this.paramSelectWidget.addItems( [
new TemplateDataOptionImportWidget( {
data: 'tdg-importParameters',
$: this.$,
params: missingParams
} )
] );
}
};
/**
* Change parameter property
* @param {string} paramKey Parameter key
* @param {string} propName Property name
* @param {string} propVal Property value
* @param {string} [lang] Language
*/
TemplateDataDialog.prototype.changeParamPropertyInput = function ( paramKey, propName, value, lang ) {
var languageProps = TemplateDataModel.static.getPropertiesWithLanguage(),
allProps = TemplateDataModel.static.getAllProperties( true ),
prop = allProps[propName],
propInput = typeof this.propInputs[propName].getMenu === 'function' ?
this.propInputs[propName].getMenu() : this.propInputs[propName];
lang = lang || this.language;
if ( value !== undefined ) {
// Change the actual input
if ( prop.type === 'select' ) {
propInput.selectItem( propInput.getItemFromData( value ) );
} else if ( prop.type === 'boolean' ) {
propInput.setValue( !!value );
} else {
if ( $.inArray( propName, languageProps ) !== -1 ) {
propInput.setValue( value[lang] );
} else {
if ( prop.type === 'array' && $.type( value ) === 'array' ) {
value = value.join( prop.delimiter );
}
propInput.setValue( value );
}
}
} else {
// Empty the input
if ( prop.type === 'select' ) {
propInput.selectItem( propInput.getItemFromData( prop['default'] ) );
} else {
propInput.setValue( '' );
}
}
};
/**
* Add parameter to the list
* @param {string} paramKey Parameter key in the model
* @param {Object} paramData Parameter data
*/
TemplateDataDialog.prototype.addParamToSelectWidget = function ( paramKey ) {
var paramItem,
data = this.model.getParamData( paramKey );
paramItem = new TemplateDataOptionWidget( {
data: {
key: paramKey,
name: data.name,
aliases: data.aliases,
description: this.model.getParamDescription( paramKey, this.language )
},
$: this.$
} );
this.paramSelectWidget.addItems( [ paramItem ] );
};
/**
* Create the information page about individual parameters
* @returns {jQuery} Editable details page for the parameter
*/
TemplateDataDialog.prototype.createParamDetails = function () {
var props, type, propInput, config, paramProperties,
paramFieldset,
typeItemArray = [];
paramProperties = TemplateDataModel.static.getAllProperties( true );
// Fieldset
paramFieldset = new OO.ui.FieldsetLayout( {
$: this.$
} );
for ( props in paramProperties ) {
config = {
$: this.$,
multiline: paramProperties[props].multiline
};
if ( paramProperties[props].multiline ) {
config.autosize = true;
}
// Create the property inputs
switch ( props ) {
case 'type':
propInput = new OO.ui.DropdownWidget( config );
for ( type in paramProperties[props].children ) {
typeItemArray.push( new OO.ui.OptionWidget( {
data: paramProperties[props].children[type],
$: this.$,
label: mw.msg( 'templatedata-modal-table-param-type-' + paramProperties[props].children[type] )
} ) );
}
propInput.getMenu().addItems( typeItemArray );
break;
case 'required':
case 'suggested':
propInput = new OO.ui.ToggleSwitchWidget( config );
break;
default:
propInput = new OO.ui.TextInputWidget( config );
break;
}
this.propInputs[props] = propInput;
propInput.$element
.addClass( 'tdg-TemplateDataDialog-paramInput tdg-TemplateDataDialog-paramList-' + props );
this.propFieldLayout[props] = new OO.ui.FieldLayout( propInput, {
align: 'left',
label: mw.msg( 'templatedata-modal-table-param-' + props )
} );
// Event
if ( props === 'type' ) {
propInput.connect( this, { choose: [ 'onParamPropertyInputChange', props ] } );
} else {
propInput.connect( this, { change: [ 'onParamPropertyInputChange', props ] } );
}
// Append to parameter section
paramFieldset.$element.append( this.propFieldLayout[props].$element );
}
// Update parameter property fields with languages
this.updateParamDetailsLanguage( this.language );
return paramFieldset.$element;
};
TemplateDataDialog.prototype.onDeleteParamButtonClick = function () {
};
/**
* Update the labels for parameter property inputs that include language, so
* they show the currently used language.
* @param {string} [lang] Language. If not used, will use currently defined
* language.
*/
TemplateDataDialog.prototype.updateParamDetailsLanguage = function ( lang ) {
var i, prop, label,
languageProps = TemplateDataModel.static.getPropertiesWithLanguage();
lang = lang || this.language;
for ( i = 0; i < languageProps.length; i++ ) {
prop = languageProps[i];
label = mw.msg( 'templatedata-modal-table-param-' + prop, lang );
this.propFieldLayout[prop].setLabel( label );
}
};
/**
* Override getBodyHeight to create a tall dialog relative to the screen.
* @return {number} Body height
*/
TemplateDataDialog.prototype.getBodyHeight = function () {
return window.innerHeight - 200;
};
/**
* Show or hide the notice message in the dialog with a set message.
* @param {string} type Which notice label to show: 'list' or 'global'
* @param {Boolean} isShowing Show or hide the message
* @param {string} status Message status 'error' or 'success'
* @param {string|string[]} noticeMessage The message to display
*/
TemplateDataDialog.prototype.toggleNoticeMessage = function ( type, isShowing, status, noticeMessage ) {
var noticeReference,
$message;
type = type || 'list';
// Hide all
this.noticeLabel.$element.hide();
this.paramEditNoticeLabel.$element.hide();
this.paramListNoticeLabel.$element.hide();
if ( noticeMessage ) {
// See which error to display
if ( type === 'global' ) {
noticeReference = this.noticeLabel;
} else if ( type === 'edit' ) {
noticeReference = this.paramEditNoticeLabel;
} else {
noticeReference = this.paramListNoticeLabel;
}
isShowing = isShowing || !noticeReference.$element.is( ':visible' );
if ( $.type( noticeMessage ) === 'array' ) {
$message = $( '<div>' );
$.each( noticeMessage, function ( i, msg ) {
$message.append( $( '<p>' ).text( msg ) );
} );
noticeReference.setLabel( $message );
} else {
noticeReference.setLabel( noticeMessage );
}
noticeReference.$element
.toggle( isShowing )
.toggleClass( 'errorbox', status === 'error' )
.toggleClass( 'successbox', status === 'success' );
}
};
/**
* Import parameters from the source code.
*/
TemplateDataDialog.prototype.importParametersFromTemplateCode = function () {
var combinedMessage = [],
state = 'success',
response = this.model.importSourceCodeParameters();
// Repopulate the list
this.repopulateParamSelectWidget();
if ( response.existing.length > 0 ) {
combinedMessage.push( mw.msg( 'templatedata-modal-errormsg-import-paramsalreadyexist', response.existing.join( mw.msg( 'comma-separator' ) ) ) );
}
if ( response.imported.length === 0 ) {
combinedMessage.push( mw.msg( 'templatedata-modal-errormsg-import-noparams' ) );
state = 'error';
} else {
combinedMessage.push( mw.msg( 'templatedata-modal-notice-import-numparams', response.imported.length, response.imported.join( mw.msg( 'comma-separator' ) ) ) );
}
this.toggleNoticeMessage( 'list', true, state, combinedMessage );
};
/**
* @inheritDoc
*/
TemplateDataDialog.prototype.getSetupProcess = function ( data ) {
return TemplateDataDialog.super.prototype.getSetupProcess.call( this, data )
.next( function () {
// Hide the panels and display a spinner
this.$spinner.show();
this.panels.$element.hide();
this.toggleNoticeMessage( 'global', false );
this.toggleNoticeMessage( 'list', false );
this.reset();
// Start with parameter list
this.switchPanels( 'listParams' );
this.model = new TemplateDataModel( data.config );
// Events
this.model.connect( this, {
'change-description': 'onModelChangeDescription'
} );
// Load the model according to the string
this.model.loadModel( data.wikitext )
.done( $.proxy( function () {
var i,
language = this.model.getDefaultLanguage(),
languageItems = [],
languages = this.model.getExistingLanguageCodes();
this.setupDetailsFromModel();
// Fill up the language selection
if (
languages.length === 0 ||
$.inArray( language, languages ) === -1
) {
// Add the default language
languageItems.push( new OO.ui.OptionWidget( {
data: language,
$: this.$,
label: $.uls.data.getAutonym( language )
} ) );
this.availableLanguages.push( language );
}
// Add all available languages
for ( i = 0; i < languages.length; i++ ) {
languageItems.push( new OO.ui.OptionWidget( {
data: languages[i],
$: this.$,
label: $.uls.data.getAutonym( languages[i] )
} ) );
// Store available languages
this.availableLanguages.push( languages[i] );
}
this.languageDropdownWidget.getMenu().addItems( languageItems );
// Trigger the initial language choice
this.languageDropdownWidget.getMenu().chooseItem( this.languageDropdownWidget.getMenu().getItemFromData( language ) );
// Show the panel
this.$spinner.hide();
this.panels.$element.show();
}, this ) )
.fail( $.proxy( function () {
// Show error
this.actions.setMode( 'error' );
this.$spinner.hide();
this.toggleNoticeMessage( 'global', true, 'error', mw.msg( 'templatedata-errormsg-jsonbadformat' ) );
}, this ) );
}, this );
};
/**
* Set up the list of parameters from the model. This should happen
* after initialization of the model.
*/
TemplateDataDialog.prototype.setupDetailsFromModel = function () {
// Reset parameter list
this.reset();
// Set up description
this.descriptionInput.setValue( this.model.getTemplateDescription( this.language ) );
// TODO: Set up paramOrder
this.repopulateParamSelectWidget();
};
/**
* Switch between stack layout panels
* @param {string} panel Panel key to switch to
*/
TemplateDataDialog.prototype.switchPanels = function ( panel ) {
switch ( panel ) {
case 'listParams':
this.actions.setMode( 'list' );
this.panels.setItem( this.listParamsPanel );
// Reset message
this.toggleNoticeMessage( 'list', false );
// Deselect parameter
this.paramSelectWidget.selectItem( null );
// Repopulate the list to account for any changes
if ( this.model ) {
this.repopulateParamSelectWidget();
}
// Hide/show panels
this.listParamsPanel.$element.show();
this.editParamPanel.$element.hide();
this.addParamPanel.$element.hide();
this.languagePanel.$element.hide();
break;
case 'editParam':
this.actions.setMode( 'edit' );
this.panels.setItem( this.editParamPanel );
// Deselect parameter
this.paramSelectWidget.selectItem( null );
// Hide/show panels
this.listParamsPanel.$element.hide();
this.languagePanel.$element.hide();
this.addParamPanel.$element.hide();
this.editParamPanel.$element.show();
break;
case 'addParam':
this.actions.setMode( 'add' );
this.panels.setItem( this.addParamPanel );
// Hide/show panels
this.listParamsPanel.$element.hide();
this.editParamPanel.$element.hide();
this.languagePanel.$element.hide();
this.addParamPanel.$element.show();
break;
case 'language':
this.actions.setMode( 'language' );
this.panels.setItem( this.languagePanel );
// Hide/show panels
this.listParamsPanel.$element.hide();
this.editParamPanel.$element.hide();
this.addParamPanel.$element.hide();
this.languagePanel.$element.show();
break;
}
};
/**
* @inheritDoc
*/
TemplateDataDialog.prototype.getActionProcess = function ( action ) {
if ( action === 'back' ) {
return new OO.ui.Process( function () {
this.switchPanels( 'listParams' );
}, this );
}
if ( action === 'add' ) {
return new OO.ui.Process( function () {
this.switchPanels( 'addParam' );
}, this );
}
if ( action === 'delete' ) {
return new OO.ui.Process( function () {
this.model.deleteParam( this.selectedParamKey );
this.switchPanels( 'listParams' );
}, this );
}
if ( action === 'apply' ) {
return new OO.ui.Process( function () {
this.emit( 'apply', this.model.outputTemplateDataString() );
this.close( { action: action } );
}, this );
}
// Fallback to parent handler
return TemplateDataDialog.super.prototype.getActionProcess.call( this, action );
};
}( mediaWiki ) );

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<g id="parameter">
<path id="offset-box" d="M16 6h-8c-2 0-3 1-3 3v6c0 2 1 3 3 3h8c2 0 3-1 3-3v-6c0-2-1-3-3-3zm1 9c0 .469-.521 1-1 1h-6v-8h6c.479 0 1 .531 1 1v6z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 315 B

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<g id="parameter">
<path id="offset-box" d="M8 6h8c2 0 3 1 3 3v6c0 2-1 3-3 3h-8c-2 0-3-1-3-3v-6c0-2 1-3 3-3zm-1 9c0 .469.521 1 1 1h6v-8h-6c-.479 0-1 .531-1 1v6z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 315 B

View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<g id="parameter-set">
<path id="offset-front" d="M16.504 11.019h-3.987c-.998 0-1.496.498-1.496 1.494v2.991c0 .998.498 1.496 1.496 1.496h3.987c.998 0 1.496-.498 1.496-1.496v-2.991c0-.996-.498-1.494-1.496-1.494zm.498 4.485c0 .234-.259.498-.498.498h-2.991v-4.002h2.991c.239 0 .498.279.498.513v2.991z"/>
<path id="box-middle" d="M9.516 11.513c0-.996.504-1.513 1.502-1.513h3.912c-.153-.655-.616-1-1.426-1h-3.987c-.998 0-1.496.498-1.496 1.494v2.991c0 .998.498 1.496 1.496 1.496l-.001-3.468z"/>
<path id="box-back" d="M6.516 9.513c0-.996.504-1.513 1.502-1.513h3.912c-.153-.655-.616-1-1.426-1h-3.987c-.998 0-1.496.498-1.496 1.494v2.991c0 .998.498 1.496 1.496 1.496l-.001-3.468z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 841 B

View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<g id="parameter-set">
<path id="offset-front" d="M6.517 11.019h3.987c.998 0 1.496.498 1.496 1.494v2.991c0 .998-.498 1.496-1.496 1.496h-3.987c-.998 0-1.496-.498-1.496-1.496v-2.991c0-.996.498-1.494 1.496-1.494zm-.498 4.485c0 .234.259.498.498.498h2.991v-4.002h-2.991c-.239 0-.498.279-.498.513v2.991z"/>
<path id="box-middle" d="M13.505 11.513c0-.996-.504-1.513-1.502-1.513h-3.912c.153-.655.616-1 1.426-1h3.987c.998 0 1.496.498 1.496 1.494v2.991c0 .998-.498 1.496-1.496 1.496l.001-3.468z"/>
<path id="box-back" d="M16.505 9.513c0-.996-.504-1.513-1.502-1.513h-3.912c.153-.655.616-1 1.426-1h3.987c.998 0 1.496.498 1.496 1.494v2.991c0 .998-.498 1.496-1.496 1.496l.001-3.468z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 839 B

View file

@ -0,0 +1,77 @@
/**
* Creates a TemplateDataLanguageResultWidget object.
* This is a copy of ve.ui.LanguageResultWidget
*
* @class
* @extends OO.ui.OptionWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
TemplateDataLanguageResultWidget = function TemplateDataLanguageResultWidget( config ) {
// Parent constructor
OO.ui.OptionWidget.call( this, config );
// Initialization
this.$element.addClass( 'tdg-languageResultWidget' );
this.$name = this.$( '<div>' ).addClass( 'tdg-languageResultWidget-name' );
this.$otherMatch = this.$( '<div>' ).addClass( 'tdg-languageResultWidget-otherMatch' );
this.setLabel( this.$otherMatch.add( this.$name ) );
};
/* Inheritance */
OO.inheritClass( TemplateDataLanguageResultWidget, OO.ui.OptionWidget );
/* Methods */
/**
* Update labels based on query
*
* @param {string} [query] Query text which matched this result
* @param {string} [matchedProperty] Data property which matched the query text
* @chainable
*/
TemplateDataLanguageResultWidget.prototype.updateLabel = function ( query, matchedProperty ) {
var $highlighted, data = this.getData();
// Reset text
this.$name.text( data.name );
this.$otherMatch.text( data.code );
// Highlight where applicable
if ( matchedProperty ) {
$highlighted = this.highlightQuery( data[matchedProperty], query );
if ( matchedProperty === 'name' ) {
this.$name.empty().append( $highlighted );
} else {
this.$otherMatch.empty().append( $highlighted );
}
}
return this;
};
/**
* Highlight text where a substring query matches
*
* @param {string} text Text
* @param {string} query Query to find
* @returns {jQuery} Text with query substring wrapped in highlighted span
*/
TemplateDataLanguageResultWidget.prototype.highlightQuery = function ( text, query ) {
var $result = this.$( '<span>' ),
offset = text.toLowerCase().indexOf( query.toLowerCase() );
if ( !query.length || offset === -1 ) {
return $result.text( text );
}
$result.append(
document.createTextNode( text.slice( 0, offset ) ),
this.$( '<span>' )
.addClass( 'tdg-languageResultWidget-highlight' )
.text( text.substr( offset, query.length ) ),
document.createTextNode( text.slice( offset + query.length ) )
);
return $result.contents();
};

View file

@ -0,0 +1,112 @@
/**
* Creates a TemplateDataLanguageSearchWidget object.
* This is a copy of ve.ui.LanguageSearchWidget.
*
* @class
* @extends OO.ui.SearchWidget
*
* @constructor
* @param {Object} [config] Configuration options
*/
TemplateDataLanguageSearchWidget = function TemplateDataLanguageSearchWidget( config ) {
// Configuration intialization
config = $.extend( {
placeholder: mw.msg( 'templatedata-modal-search-input-placeholder' )
}, config );
// Parent constructor
OO.ui.SearchWidget.call( this, config );
// Properties
this.languageResultWidgets = [];
var i, l, languageCode,
languageCodes = Object.keys( $.uls.data.getAutonyms() ).sort();
for ( i = 0, l = languageCodes.length; i < l; i++ ) {
languageCode = languageCodes[i];
this.languageResultWidgets.push(
new TemplateDataLanguageResultWidget( {
data: {
code: languageCode,
name: $.uls.data.getAutonym( languageCode ),
autonym: $.uls.data.getAutonym( languageCode )
},
$: this.$
} )
);
}
// Initialization
this.$element.addClass( 'tdg-languageSearchWidget' );
};
/* Inheritance */
OO.inheritClass( TemplateDataLanguageSearchWidget, OO.ui.SearchWidget );
/* Methods */
/**
* @inheritdoc
*/
TemplateDataLanguageSearchWidget.prototype.onQueryChange = function () {
// Parent method
OO.ui.SearchWidget.prototype.onQueryChange.call( this );
// Populate
this.addResults();
};
/**
* Update search results from current query
*/
TemplateDataLanguageSearchWidget.prototype.addResults = function () {
var i, iLen, j, jLen, languageResult, data, matchedProperty,
matchProperties = ['name', 'autonym', 'code'],
query = this.query.getValue().trim(),
matcher = new RegExp( '^' + this.constructor.static.escapeRegex( query ), 'i' ),
hasQuery = !!query.length,
items = [];
this.results.clearItems();
for ( i = 0, iLen = this.languageResultWidgets.length; i < iLen; i++ ) {
languageResult = this.languageResultWidgets[i];
data = languageResult.getData();
matchedProperty = null;
for ( j = 0, jLen = matchProperties.length; j < jLen; j++ ) {
if ( matcher.test( data[matchProperties[j]] ) ) {
matchedProperty = matchProperties[j];
break;
}
}
if ( query === '' || matchedProperty ) {
items.push(
languageResult
.updateLabel( query, matchedProperty )
.setSelected( false )
.setHighlighted( false )
);
}
}
this.results.addItems( items );
if ( hasQuery ) {
this.results.highlightItem( this.results.getFirstSelectableItem() );
}
};
/**
* Escape regex.
*
* Ported from Languagefilter#escapeRegex in jquery.uls.
*
* @param {string} value Text
* @returns {string} Text escaped for use in regex
*/
TemplateDataLanguageSearchWidget.static.escapeRegex = function ( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$\|#\s]/g, '\\$&' );
};

View file

@ -0,0 +1,37 @@
/**
* TemplateData Option Import Widget
* @extends {OO.ui.DecoratedOptionWidget}
* @param {Object} config Dialog configuration object
*/
TemplateDataOptionImportWidget = function TemplateDataOptionImportWidget( config ) {
config = config || {};
// Parent constructor
TemplateDataOptionImportWidget.super.call( this, $.extend( {}, config, { icon: 'parameter-set' } ) );
this.params = config.params;
// Initialize
this.$element.addClass( 'tdg-templateDataOptionImportWidget' );
this.buildParamLabel();
};
OO.inheritClass( TemplateDataOptionImportWidget, OO.ui.DecoratedOptionWidget );
/**
* Build the parameter label in the parameter select widget
* @param {Object} paramData Parameter data
* @return {jQuery} Label element
*/
TemplateDataOptionImportWidget.prototype.buildParamLabel = function () {
var paramNames = this.params.slice( 0, 9 ).join( mw.msg( 'comma-separator' ) ),
$paramName = this.$( '<div>' )
.addClass( 'tdg-TemplateDataOptionWidget-param-name' ),
$description = this.$( '<div>' )
.addClass( 'tdg-TemplateDataOptionWidget-param-description' );
$paramName.text( mw.msg( 'templatedata-modal-table-param-importoption', this.params.length ) );
$description.text( mw.msg( 'templatedata-modal-table-param-importoption-subtitle', paramNames ) );
this.setLabel( $paramName.add( $description ) );
};

View file

@ -0,0 +1,54 @@
/**
* TemplateData Option Widget
* @extends {OO.ui.DecoratedOptionWidget}
* @param {Object} config Dialog configuration object
*/
TemplateDataOptionWidget = function TemplateDataOptionWidget( config ) {
var data;
config = config || {};
data = config.data || {};
// Parent constructor
TemplateDataOptionWidget.super.call( this, $.extend( {}, config, { data: data.key, icon: 'parameter' } ) );
this.key = data.key;
this.name = data.name;
this.aliases = data.aliases;
this.description = data.description;
// Initialize
this.$element.addClass( 'tdg-TemplateDataOptionWidget' );
this.buildParamLabel();
};
OO.inheritClass( TemplateDataOptionWidget, OO.ui.DecoratedOptionWidget );
/**
* Build the parameter label in the parameter select widget
* @param {Object} paramData Parameter data
* @return {jQuery} Label element
*/
TemplateDataOptionWidget.prototype.buildParamLabel = function () {
var i, len,
$paramName = this.$( '<div>' )
.addClass( 'tdg-TemplateDataOptionWidget-param-name' ),
$aliases = this.$( '<div>' )
.addClass( 'tdg-TemplateDataOptionWidget-param-aliases' ),
$description = this.$( '<div>' )
.addClass( 'tdg-TemplateDataOptionWidget-param-description' );
$paramName.text( this.name );
$description.text( this.description );
if ( this.aliases !== undefined ) {
for ( i = 0, len = this.aliases.length; i < len; i++ ) {
$aliases.append(
this.$( '<span>' )
.addClass( 'tdg-TemplateDataOptionWidget-param-alias' )
.text( this.aliases[i] )
);
}
}
this.setLabel( $paramName.add( $aliases ).add( $description ) );
};

View file

@ -2,63 +2,81 @@
* TemplateData Generator GUI Unit Tests
*/
( function ( $, mw ) {
( function ( $ ) {
'use strict';
QUnit.module( 'ext.templateData', QUnit.newMwEnvironment() );
var originalWikitext = 'Some text here that is not templatedata information.' +
'<templatedata>' +
'{' +
' "description": "Label unsigned comments in a conversation.",' +
' "params": {' +
' "user": {' +
' "label": "Username",' +
' "type": "wiki-user-name",' +
' "required": true,' +
' "description": "User name of person who forgot to sign their comment.",' +
' "aliases": ["1"]' +
' },' +
' "date": {' +
' "label": "Date",' +
' "description": {' +
' "en": "Timestamp of when the comment was posted, in YYYY-MM-DD format."' +
' },' +
' "aliases": ["2"],' +
' "autovalue": "{{subst:CURRENTMONTHNAME}}",' +
' "suggested": true' +
' },' +
' "year": {' +
' "label": "Year",' +
' "type": "number"' +
' },' +
' "month": {' +
' "label": "Month",' +
' "inherits": "year"' +
' },' +
' "day": {' +
' "label": "Day",' +
' "inherits": "year"' +
' },' +
' "comment": {' +
' "required": false' +
' }' +
' },' +
' "sets": [' +
' {' +
' "label": "Date",' +
' "params": ["year", "month", "day"]' +
' }' +
' ]' +
'}' +
'</templatedata>' +
'Trailing text at the end.',
var i, testVars, finalJsonStringOnly,
resultDescCurrLang = {},
resultDescMockLang = {},
resultDescBothLang = {},
currLanguage = mw.config.get( 'wgContentLanguage' ) || 'en',
model = new TemplateDataModel(),
originalWikitext = 'Some text here that is not templatedata information.' +
'<templatedata>' +
'{' +
' "description": {\n' +
' "' + currLanguage + '": "Label unsigned comments in a conversation.",\n' +
' "blah": "Template description in some blah language."\n' +
' },' +
' "params": {' +
' "user": {' +
' "label": "Username",' +
' "type": "wiki-user-name",' +
' "required": true,' +
' "description": "User name of person who forgot to sign their comment.",' +
' "aliases": ["1"]' +
' },' +
' "date": {' +
' "label": "Date",' +
' "description": {' +
' "en": "Timestamp of when the comment was posted, in YYYY-MM-DD format."' +
' },' +
' "aliases": ["2"],' +
' "autovalue": "{{subst:CURRENTMONTHNAME}}",' +
' "suggested": true' +
' },' +
' "year": {' +
' "label": "Year",' +
' "type": "number"' +
' },' +
' "month": {' +
' "label": "Month",' +
' "inherits": "year"' +
' },' +
' "day": {' +
' "label": "Day",' +
' "inherits": "year"' +
' },' +
' "comment": {' +
' "required": false' +
' }' +
' },' +
' "sets": [' +
' {' +
' "label": "Date",' +
' "params": ["year", "month", "day"]' +
' }' +
' ]' +
'}' +
'</templatedata>' +
'Trailing text at the end.';
// Prepare description language objects
resultDescCurrLang[currLanguage] = 'Some string here in ' + currLanguage + ' language.';
resultDescMockLang.blah = 'Some string here in blah language.';
resultDescBothLang = $.extend( {}, resultDescCurrLang, resultDescMockLang );
finalJsonStringOnly = '{\n' +
' "description": "Label unsigned comments in a conversation.",\n' +
' "description": {\n' +
' "' + currLanguage + '": "Label unsigned comments in a conversation.",\n' +
' "blah": "Template description in some blah language."\n' +
' },\n' +
' "params": {\n' +
' "user": {\n' +
' "label": "New user label",\n' +
' "label": "Username",\n' +
' "type": "wiki-user-name",\n' +
' "required": true,\n' +
' "description": "User name of person who forgot to sign their comment.",\n' +
' "aliases": [\n' +
' "1"\n' +
@ -84,10 +102,25 @@
' "inherits": "year"\n' +
' },\n' +
' "comment": {\n' +
' "required": false\n' +
' "required": false,\n' +
' "type": "wiki-page-name"\n' +
' },\n' +
' "someNewParameter": {\n' +
' "newParam1": {\n' +
' "description": {\n' +
' "' + currLanguage + '": "Some string here in ' + currLanguage + ' language.",\n' +
' "blah": "Some string here in blah language."\n' +
' },\n' +
' "required": true\n' +
' },\n' +
' "newParam2": {},\n' +
' "newParam3": {\n' +
' "description": "Some string here in ' + currLanguage + ' language."\n' +
' },\n' +
' "newParam4": {\n' +
' "description": {\n' +
' "' + currLanguage + '": "' + resultDescBothLang[currLanguage] + '",\n' +
' "blah": "' + resultDescBothLang.blah + '"\n' +
' }\n' +
' }\n' +
' },\n' +
' "sets": [\n' +
@ -100,116 +133,405 @@
' ]\n' +
' }\n' +
' ]\n' +
'}',
tdManualParamsObject = {
'user': {
// The parameter data model adds 'name' attribute
'name': 'user',
'label': 'Username',
'type': 'wiki-user-name',
'required': true,
'description': 'User name of person who forgot to sign their comment.',
'aliases': ['1']
},
'date': {
'name': 'date',
'label': 'Date',
'description': {
'en': 'Timestamp of when the comment was posted, in YYYY-MM-DD format.'
},
'autovalue': '{{subst:CURRENTMONTHNAME}}',
'aliases': ['2'],
'suggested': true
},
'year': {
'name': 'year',
'label': 'Year',
'type': 'number'
},
'month': {
'name': 'month',
'label': 'Month',
'inherits': 'year'
},
'day': {
'name': 'day',
'label': 'Day',
'inherits': 'year'
},
'comment': {
'name': 'comment',
'required': false
'}';
// Test validation tools
QUnit.test( 'Validation tools', function ( assert ) {
var tests = {
'compare': [
{
obj1: {},
obj2: [],
result: false,
msg: 'Compare: object vs array'
},
{
obj1: null,
obj2: undefined,
result: false,
msg: 'Compare: null vs undefined'
},
{
obj1: 'string',
obj2: undefined,
result: false,
msg: 'Compare: string vs undefined'
},
{
obj1: undefined,
obj2: undefined,
result: true,
msg: 'Compare: undefined vs undefined'
},
{
obj1: null,
obj2: null,
result: true,
msg: 'Compare: null vs null'
},
{
obj1: 'A proper string.',
obj2: 'A proper string.',
result: true,
msg: 'Compare: strings'
},
{
obj1: true,
obj2: true,
result: true,
msg: 'Compare: booleans'
},
{
obj1: { 1: 'string', 2: 'another', 4: 'and another' },
obj2: { 1: 'string', 2: 'another', 4: 'and another' },
result: true,
allowSubset: true,
msg: 'Compare: plain object full equality'
},
{
obj1: { 1: 'string', 2: 'another', 4: 'and another' },
obj2: { 1: 'another', 2: 'and another', 4: 'string' },
result: false,
allowSubset: true,
msg: 'Compare: plain object full inequality'
},
{
obj1: { 1: 'string', 2: 'another', 4: 'and another' },
obj2: { 4: 'and another' },
result: true,
allowSubset: true,
msg: 'Compare: plain object subset equality'
},
{
obj1: [ 'val1', 'val2', 'val3' ],
obj2: [ 'val1', 'val2', 'val3' ],
result: true,
msg: 'Compare: arrays'
},
{
obj1: [ 'val1', 'val2', 'val3' ],
obj2: [ 'val1' ],
result: true,
allowSubset: true,
msg: 'Compare: array subset: true'
},
{
obj1: [ 'val1', 'val2', 'val3' ],
obj2: [ 'val1' ],
result: false,
allowSubset: false,
msg: 'Compare: array subset: false'
},
{
obj1: {
param1: {
type: 'undefined',
aliases: [ 'alias2', 'alias1', 'alias3' ],
description: 'Some description',
required: true,
suggested: false
},
param2: {
required: true
}
},
obj2: {
param1: {
type: 'undefined',
aliases: [ 'alias2', 'alias1', 'alias3' ],
description: 'Some description',
required: true,
suggested: false
},
param2: {
required: true
}
},
result: true,
allowSubset: true,
msg: 'Compare: complex objects'
},
{
obj1: {
param1: {
type: 'undefined',
aliases: [ 'alias1', 'alias2', 'alias3' ],
description: 'Some description',
required: true,
suggested: false
},
param2: {
required: true
}
},
obj2: {
param1: {
aliases: [ 'alias1', 'alias2', 'alias3' ],
suggested: false
}
},
result: true,
allowSubset: true,
msg: 'Compare: complex objects subset'
}
],
'splitAndTrimArray': [
{
string: 'str1 , str2 ',
delim: ',',
result: [ 'str1', 'str2' ],
msg: 'splitAndTrimArray: split and trim'
},
{
string: 'str1, str2, , , , str3',
delim: ',',
result: [ 'str1', 'str2', 'str3' ],
msg: 'splitAndTrimArray: remove empty values'
},
{
string: 'str1|str2|str3',
delim: '|',
result: [ 'str1', 'str2', 'str3' ],
msg: 'splitAndTrimArray: different delimeter'
}
],
'arrayUnionWithoutEmpty': [
{
arrays: [ [ 'en', 'he', '' ], [ 'he', 'de', '' ], [ 'en', 'de' ] ],
result: [ 'en', 'he', 'de' ],
msg: 'arrayUnionWithoutEmpty: Remove duplications'
},
{
arrays: [ [ 'en', '', '' ], [ 'he', '', '' ], [ 'de', '' ] ],
result: [ 'en', 'he', 'de' ],
msg: 'arrayUnionWithoutEmpty: Remove empty values'
}
],
'props': {
'all': [
'name',
'aliases',
'label',
'description',
'type',
'default',
'autovalue',
'required',
'suggested'
],
'language': [
'label',
'description'
]
}
};
QUnit.expect(
tests.compare.length +
tests.splitAndTrimArray.length +
tests.arrayUnionWithoutEmpty.length +
Object.keys( tests.props ).length
);
// Compare
for ( i = 0; i < tests.compare.length; i++ ) {
testVars = tests.compare[i];
assert.equal(
TemplateDataModel.static.compare( testVars.obj1, testVars.obj2, testVars.allowSubset ),
testVars.result,
testVars.msg
);
}
};
/** Parameter data model tests **/
QUnit.asyncTest( 'TemplateData Parameter Model', 6, function ( assert ) {
var tdgTests;
mw.libs.templateDataGenerator.init( null, null, { 'useGUI': false, 'fetchCodeFromSource': false } );
tdgTests = mw.libs.templateDataGenerator.tests;
// Load data into model
tdgTests.loadTemplateDataJson( originalWikitext ).done( function ( pmodel ) {
// Tests
// Split and trim
for ( i = 0; i < tests.splitAndTrimArray.length; i++ ) {
testVars = tests.splitAndTrimArray[i];
assert.deepEqual(
tdManualParamsObject,
pmodel,
'Loading parameters data model'
TemplateDataModel.static.splitAndTrimArray( testVars.string, testVars.delim ),
testVars.result,
testVars.msg
);
}
// Make sure description sticks
assert.equal(
tdgTests.getTDMeta().description,
'Label unsigned comments in a conversation.',
'Template description.'
);
// Change attributes
tdManualParamsObject.user.label = 'New user label';
delete tdManualParamsObject.user.required;
tdgTests.modelUpdateParamAttribute( 'user', 'label', 'New user label' );
tdgTests.modelUpdateParamAttribute( 'user', 'required', false );
// arrayUnionWithoutEmpty
for ( i = 0; i < tests.arrayUnionWithoutEmpty.length; i++ ) {
testVars = tests.arrayUnionWithoutEmpty[i];
assert.deepEqual(
tdManualParamsObject,
pmodel,
'Changing parameter attributes'
TemplateDataModel.static.arrayUnionWithoutEmpty.apply( testVars, testVars.arrays ),
testVars.result,
testVars.msg
);
}
// Add parameter
tdManualParamsObject.newparam = { 'name': 'someNewParameter', 'required': true };
tdgTests.modelAddParam( 'newparam', { 'name': 'someNewParameter', 'required': true } );
assert.deepEqual(
tdManualParamsObject,
pmodel,
'Adding a new parameter'
);
// Delete a parameter
delete tdManualParamsObject.day;
tdgTests.modelDeleteParam( 'day' );
assert.deepEqual(
tdManualParamsObject,
pmodel,
'Deleting a parameter'
);
// Outputting final templatedata string
assert.equal(
finalJsonStringOnly,
tdgTests.modelOutputJsonString(),
'Outputting templatedata json string from model'
);
} )
.always( function () {
QUnit.start();
} );
// Props
assert.deepEqual(
TemplateDataModel.static.getAllProperties( false ),
tests.props.all,
'All properties'
);
assert.deepEqual(
TemplateDataModel.static.getPropertiesWithLanguage(),
tests.props.language,
'Language properties'
);
} );
}( jQuery, mediaWiki ) );
// Test model load
QUnit.asyncTest( 'TemplateData model', function ( assert ) {
var i,
paramAddTest = [
{
key: 'newParam1',
data: { required: true },
result: { name: 'newParam1', required: true },
description: '',
msg: 'Adding a simple parameter.'
},
{
key: 'newParam2',
data: null,
result: { name: 'newParam2' },
description: '',
msg: 'Adding new parameter without data.'
},
{
key: 'newParam3',
data: { description: 'Some string here in ' + currLanguage + ' language.' },
result: { name: 'newParam3', description: resultDescCurrLang },
description: 'Some string here in ' + currLanguage + ' language.',
msg: 'Adding parameter with language prop: original without language.'
},
{
key: 'newParam4',
data: {
description: resultDescBothLang
},
result: { name: 'newParam4', description: resultDescBothLang },
description: 'Some string here in ' + currLanguage + ' language.',
msg: 'Adding parameter with language prop: original with multiple languages.'
}
],
paramChangeTest = [
{
key: 'newParam1',
property: 'description',
language: 'en',
value: resultDescCurrLang[currLanguage],
result: $.extend( {}, paramAddTest[0].result, {
description: resultDescCurrLang
} ),
msg: 'Adding description in current language.'
},
{
key: 'newParam1',
property: 'description',
language: 'blah',
value: resultDescMockLang.blah,
result: $.extend( {}, paramAddTest[0].result, {
description: $.extend( {}, resultDescCurrLang, resultDescMockLang )
} ),
msg: 'Adding description in mock language.'
},
{
key: 'comment',
property: 'type',
value: 'wiki-page-name',
result: {
name: 'comment',
type: 'wiki-page-name',
required: false
},
msg: 'Adding type to comment.'
},
{
key: 'newParam2',
property: 'description',
language: 'blah',
value: '',
result: $.extend( {}, paramAddTest[1].result, {
description: { 'blah': '' }
} ),
msg: 'Adding empty description in mock language.'
}
];
QUnit.expect(
// Description and parameter list
3 +
// Add parameter tests
2 * paramAddTest.length +
// Change properties tests
paramChangeTest.length +
// Json output
1
);
model.loadModel( originalWikitext )
.done( function () {
// Check description
assert.equal(
model.getTemplateDescription(),
'Label unsigned comments in a conversation.',
'Description in default language.'
);
assert.equal(
model.getTemplateDescription( 'blah' ),
'Template description in some blah language.',
'Description in mock language.'
);
// Check parameters
assert.deepEqual(
Object.keys( model.getParams() ),
[ 'user', 'date', 'year', 'month', 'day', 'comment' ],
'Parameters retention.'
);
for ( i = 0; i < paramAddTest.length; i++ ) {
// Add parameter
model.addParam( paramAddTest[i].key, paramAddTest[i].data );
// Test new param data
assert.deepEqual(
model.getParamData( paramAddTest[i].key ),
paramAddTest[i].result,
paramAddTest[i].msg + ' (parameter data)'
);
// Check description in current language
assert.equal(
model.getParamDescription( paramAddTest[i].key, currLanguage ),
paramAddTest[i].description,
paramAddTest[i].msg + ' (description in current language)'
);
}
// Change parameter properties
for ( i = 0; i < paramChangeTest.length; i++ ) {
testVars = paramChangeTest[i];
model.setParamProperty( testVars.key, testVars.property, testVars.value, testVars.language );
assert.deepEqual(
model.getParamData( testVars.key ),
paramChangeTest[i].result,
paramChangeTest[i].msg
);
}
// Delete parameter
model.deleteParam( 'day' );
// Ouput a final templatedata string
assert.equal(
model.outputTemplateDataString(),
finalJsonStringOnly,
'Final templatedata output'
);
} )
.always( function () {
QUnit.start();
} );
} );
}( jQuery ) );