From 0b86ea026341d4cbfc60123e7c4532beb1431746 Mon Sep 17 00:00:00 2001 From: HT_Zhang Date: Fri, 25 Oct 2024 15:17:57 +0800 Subject: [PATCH 01/53] update create_genre_form doc --- .../forms/create_genre_form/index.md | 241 +++++++++--------- 1 file changed, 120 insertions(+), 121 deletions(-) diff --git a/files/zh-cn/learn/server-side/express_nodejs/forms/create_genre_form/index.md b/files/zh-cn/learn/server-side/express_nodejs/forms/create_genre_form/index.md index 8d6fbfee733623..489c416d1ba347 100644 --- a/files/zh-cn/learn/server-side/express_nodejs/forms/create_genre_form/index.md +++ b/files/zh-cn/learn/server-side/express_nodejs/forms/create_genre_form/index.md @@ -3,53 +3,65 @@ title: 创建种类表单 slug: Learn/Server-side/Express_Nodejs/forms/Create_genre_form --- -本章节演示如何定义我们的页面,创建`Genre` 物件(这是一个很好的起点,因为类型只有一个字段,它的名称`name`,没有依赖项)。像任何其他页面一样,我们需要设置路由,控制器和视图。 +{{LearnSidebar}} -## 引入验证与无害化方法 +本章节演示如何定义页面来创建 `Genre` 对象(这是一个很好的起点,因为 `Genre` 只有一个字段,即它的名称 `name`,并且没有依赖项)。与任何其他页面一样,我们需要设置路由,控制器和视图。 -在我们的控制器中使用 _express-validator_ 验证器,我們必須导入我们想要从 **'express-validator/check**' 和 **'express-validator/filter**' 模块中使用的函数。 +## 导入验证与修整方法 -打开**/controllers/genreController.js**,并在文件顶部添加以下行: +要控制器中使用 _express-validator_,我們必須从 `'express-validator'` 模块中 _require_ 我们想使用的函数。 + +打开 **/controllers/genreController.js**,在文件顶部、路由处理函数之前添加下方代码: ```js -const { body, validationResult } = require("express-validator/check"); -const { sanitizeBody } = require("express-validator/filter"); +const { body, validationResult } = require("express-validator"); ``` -## 控制器—get 路由 +> [!NOTE] +> 此语法允许我们使用 `body` 和 `validationResult` 作为关联的中间件函数,正如你将在下面的 post 路由部分中看到的那样。它相当于: +> +> ```js +> const validator = require("express-validator"); +> const body = validator.body; +> const validationResult = validator.validationResult; +> ``` + +## 控制器——get 路由 -找到导出的`genre_create_get()` 控制器方法,并将其替换为以下代码。这只是渲染**genre_form.pug**视图,传递一个 title 变量。 +找到导出的 `genre_create_get()` 控制器方法,并将其替换为以下代码。这将渲染 **genre_form.pug** 视图,传递一个标题变量。 ```js -// Display Genre create form on GET. -exports.genre_create_get = function (req, res, next) { +// 呈现 GET 方法获取的种类表格 +exports.genre_create_get = (req, res, next) => { res.render("genre_form", { title: "Create Genre" }); }; ``` -## 控制器—post 路由 +请注意,这里我们将使用一个“普通”的函数替换我们在 [Express 教程 4:路由和控制器](/zh-CN/docs/Learn/Server-side/Express_Nodejs/routes) 中添加的占位 asynchronous handler 函数。我们不需要该路由的 `asyncHandler()` 函数的包装,因为它不包含任何可能引发异常的代码。 + +## 控制器——post 路由 -找到导出的`genre_create_post()`控制器方法,并将其替换为以下代码。 +找到导出的 `genre_create_post()` 控制器方法,并将其替换为以下代码。 ```js -// Handle Genre create on POST. +// 处理 POST 方法创建的 Genre 表单 exports.genre_create_post = [ - // Validate that the name field is not empty. - body("name", "Genre name required").isLength({ min: 1 }).trim(), - - // Sanitize (trim and escape) the name field. - sanitizeBody("name").trim().escape(), - - // Process request after validation and sanitization. - (req, res, next) => { - // Extract the validation errors from a request. + // 验证及修整名字字段 + body("name", "Genre name must contain at least 3 characters") + .trim() + .isLength({ min: 3 }) + .escape(), + + // 处理验证及修整过后的请求 + asyncHandler(async (req, res, next) => { + // 从请求中提取验证时产生的错误信息 const errors = validationResult(req); - // Create a genre object with escaped and trimmed data. - var genre = new Genre({ name: req.body.name }); + // 使用经过 trim() 和 escape() 处理过的数据创建一个种类对象 + const genre = new Genre({ name: req.body.name }); if (!errors.isEmpty()) { - // There are errors. Render the form again with sanitized values/error messages. + // 出现错误,并使用修整过的数据/错误信息重新渲染表单 res.render("genre_form", { title: "Create Genre", genre: genre, @@ -57,131 +69,118 @@ exports.genre_create_post = [ }); return; } else { - // Data from form is valid. - // Check if Genre with same name already exists. - Genre.findOne({ name: req.body.name }).exec(function (err, found_genre) { - if (err) { - return next(err); - } - - if (found_genre) { - // Genre exists, redirect to its detail page. - res.redirect(found_genre.url); - } else { - genre.save(function (err) { - if (err) { - return next(err); - } - // Genre saved. Redirect to genre detail page. - res.redirect(genre.url); - }); - } - }); + // 表格中的数据有效 + // 检查是否存在同名的 Genre + const genreExists = await Genre.findOne({ name: req.body.name }) + .collation({ locale: "en", strength: 2 }) + .exec(); + if (genreExists) { + // 存在同名的 Genre,则重定向到详情页面 + res.redirect(genreExists.url); + } else { + await genre.save(); + // 保存新创建的 Genre,然后重定向到详情页面 + res.redirect(genre.url); + } } - }, + }), ]; ``` -首先要注意的是,控制器不是单个中间件函数(带参数(`req, res, next`)),而是指定一组中间件函数。数组传递给路由器函数,并按顺序调用每个方法。 +首先需要注意的是,控制器不是单个中间件函数(带参数`(req, res, next)`),而是指定了中间件函数*数组*。该数组传递给路由器函数并依次执行各个方法。 > [!NOTE] -> 这种方法是必需的,因为消毒/验证器是中间件功能。 - -数组中的第一个方法定义了一个验证器(`body`),来检查 name 字段是否为空(在执行验证之前调用`trim()`,以删除任何尾随/前导空格)。 +> 这种方法是必要的,因为验证器是中间件函数。 -数组中的第二个方法(`sanitizeBody()`),创建一个清理程序来调用`trim()`修剪名称字段和调用`escape()`转义任何危险的 HTML 字符。 +数组中的第一个方法定义了一个 body 验证器(`body()`),用于验证和修整字段。这个方法使用 `trim()` 删除所有的首部/尾部空白,检查 _name_ 字段是否为空,然后使用 `escape()` 删除任何危险的 HTML 字符。 ```js -// Validate that the name field is not empty. -body('name', 'Genre name required').isLength({ min: 1 }).trim(), - -// Sanitize (trim and escape) the name field. -sanitizeBody('name').trim().escape(), +[ + // 检验 name 字段不为空 + body("name", "Genre name must contain at least 3 characters") + .trim() + .isLength({ min: 3 }) + .escape(), + // … +]; ``` -> [!NOTE] -> 验证期间运行的清洁器不会修改请求。这就是为什么我们必须在上面的两个步骤中调用`trim()`! - -在指定验证器和清理器之后,我们创建了一个中间件函数,来提取任何验证错误。我们使用`isEmpty()` 来检查验证结果中,是否有任何错误。如果有,那么我们再次渲染表单,传入我们的已清理种类对象和错误消息的数组(`errors.array()`)。 +指定验证器后,我们创建一个中间件函数来提取任何验证错误。我们使用 `isEmpty()` 来检查验证结果是否有错误。如果有,我们就再次渲染表单,传入经过修整的种类对象和错误消息数组(`errors.array()`)。 ```js -// Process request after validation and sanitization. -(req, res, next) => { - - // Extract the validation errors from a request. - const errors = validationResult(req); - - // Create a genre object with escaped and trimmed data. - var genre = new Genre( - { name: req.body.name } - ); - - if (!errors.isEmpty()) { - // There are errors. Render the form again with sanitized values/error messages. - res.render('genre_form', { title: 'Create Genre', genre: genre, errors: errors.array()}); +// 处理验证和修整之后的请求 +asyncHandler(async (req, res, next) => { + // 从请求中提取验证错误 + const errors = validationResult(req); + + // 使用经过 trim() 和 escape() 处理过的数据创建一个种类对象 + const genre = new Genre({ name: req.body.name }); + + if (!errors.isEmpty()) { + // 出现错误,并使用修整过的数据/错误信息重新渲染表单 + res.render("genre_form", { + title: "Create Genre", + genre: genre, + errors: errors.array(), + }); return; - } - else { - // Data from form is valid. - ... ... - } -} + } else { + // 表格中的数据有效 + // … + } +}); ``` -如果种类名称数据有效,那么我们检查,是否已存在具有相同名称的种类`Genre`(因为我们不想创建重复项)。 +如果种类名称数据有效,那么我们执行不区分大小写的搜索,以查看是否存在具有相同名称的种类 `Genre`(因为我们不想创建仅字母大小写不同的重复或过于近似的记录,例如“Fantasy”,“fantasy”,“FaNtAsY”等等)。为了在搜索时忽略掉大小写和重音,我们链式调用了 [`collation()`]() 方法,指定“en”的区域设置和 2 的强度(更多信息请参阅 MongoDB 的 [Collation](https://www.mongodb.com/docs/manual/reference/collation/)主题)。 -如果是,我们会重定向到现有种类的详细信息页面。如果没有,我们保存新种类,并重定向到其详细信息页面。 +如果匹配的种类 `Genre` 已经存在,我们将重定向到其详情页面。如果不存在,我们则保存新种类并重定向到其详情页面。请注意,这里我们 `await` 数据库的查询结果,遵循与其他路由处理程序相同的模式。 ```js -// Check if Genre with same name already exists. -Genre.findOne({ name: req.body.name }).exec(function (err, found_genre) { - if (err) { - return next(err); - } - if (found_genre) { - // Genre exists, redirect to its detail page. - res.redirect(found_genre.url); - } else { - genre.save(function (err) { - if (err) { - return next(err); - } - // Genre saved. Redirect to genre detail page. - res.redirect(genre.url); - }); - } -}); +// 检查是否存在同名的 Genre +const genreExists = await Genre.findOne({ name: req.body.name }) + .collation({ locale: "en", strength: 2 }) + .exec(); +if (genreExists) { + // 存在同名的 Genre,则重定向到详情页面 + res.redirect(genreExists.url); +} else { + await genre.save(); + // 保存新创建的 Genre,然后重定向到详情页面 + res.redirect(genre.url); +} ``` -在我们所有的 `POST`控制器中,都使用了相同的模式:我们运行验证器,然后运行消毒器,然后检查错误,并使用错误信息重新呈现表单,或保存数据。 +我们所有的 post 控制器中都使用了相同的模式:运行验证器(带有修整功能),然后检查错误并重新渲染带有错误信息的表单或保存数据。 ## 视图 -当我们创建一个新的种类`Genre`时,在`GET`和`POST`控制器/路由中,都会呈现相同的视图(稍后在我们更新种类`Genre`时也会使用它)。 - -在`GET`情况下,表单为空,我们只传递一个 title 变量。在`POST`情况下,用户先前输入了无效数据 - 在种类变量`genre`中,我们传回了输入数据的已清理版本,并且在`errors`变量中,我们传回了一组错误消息。 +当我们创建新的种类 `Genre` 时,相同的视图会在 `GET` 和 `POST` 控制器/路由中呈现(稍后当我们*更新*种类时也会使用它),在 `GET` 情况下,表单为空,我们只传递一个标题变量。在 `POST` 情况下,用户之前输入了无效数据——对于 `genre` 变量,我们回传经过修整后的输入数据,对于错误变量,则回传一组错误消息。下面的代码显示了在两种情况下渲染模板的控制器代码。 ```js +// 渲染 GET 方法获取的视图 res.render("genre_form", { title: "Create Genre" }); + +// 渲染 POST 方法使用的视图 res.render("genre_form", { title: "Create Genre", - genre: genre, + genre, errors: errors.array(), }); ``` -创建 **/views/genre_form.pug**,并复制下面的文本。 +创建 **/views/genre_form.pug**,并复制下方的代码。 -```plain +```pug extends layout block content + h1 #{title} - form(method='POST' action='') + form(method='POST') div.form-group label(for='name') Genre: - input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' value=(undefined===genre ? '' : genre.name)) + input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' required value=(undefined===genre ? '' : genre.name) ) button.btn.btn-primary(type='submit') Submit if errors @@ -190,32 +189,32 @@ block content li!= error.msg ``` -从我们之前的教程中,可以很好地理解这个模板的大部分内容。首先,我们扩展 **layout.pug**基本模板,并覆盖名为“**content**”的块`block`。然后我们有一个标题,我们从控制器传入的标题`title`(通过`render()` 方法)。 +从我们之前的教程中可以很好地理解这个模板的大部分内容。首先,我们扩展 **layout.pug** 基本模板并覆盖名为 **content** 的模块 `block`。然后我们就创建了网页头部,其包含了我们从控制器传入的标题 `title`(通过 `render()` 方法)。 -接下来,我们有 HTML 表单的 Pug 代码,它使用`POST`方法将数据发送到服务器,并且因为操作`action`是空字符串,所以将数据发送到与页面相同的 URL。 +接下来,pug 代码中的 HTML 表单部分则会使用 `method="POST"` 方法将数据发送到服务器,并且由于 `action` 是空字符串,因此会将数据发送到与页面相同的 URL。 -表单定义了一个名为“name”的“text”类型的必填字段。字段的默认值,取决于是否定义了种类变量`genre`。如果从`GET`路由调用,它将为空,因为这是一个新表单。如果从`POST`路由调用,它将包含用户最初输入的(无效)值。 +该表单定义了一个名为“name”的“text”类型的必填字段。该字段的默认值取决于是否定义了种类 `genre` 变量。如果从 `GET` 路由调用,它将为空,因为这是一个新表单。如果从 `POST` 路由调用,它将包含用户最初输入的(无效)值。 -页面的最后一部分是错误代码。如果已定义错误变量,则只会打印错误列表(换句话说,当模板在`GET`路由上呈现时,此部分不会出现)。 +该页面的最后一部分是错误代码。如果已定义错误变量,则只会打印错误列表(换句话说,当模板在 `GET` 路由上呈现时,此部分将不会出现)。 > [!NOTE] -> 这只是呈现错误的一种方法。你还可以从错误变量中,获取受影响字段的名称,并使用这些,来控制错误消息的呈现位置,以及是否应用自定义 CSS 等。 +> 这只是呈现错误的一种方法。你还可以从错误变量中获取受影响字段的名称,并使用它们来控制错误消息的呈现位置以及是否应用自定义 CSS 等。 ## 它看起來像是? -运行应用程序,打开浏览器到,然后选择 Create new genre 链接。如果一切设置正确,你的网站应该类似于以下屏幕截图。输入值后,应保存该值,你将进入种类详细信息页面。 +运行应用程序,打开浏览器到 `http://localhost:3000/`,然后选择 _Create new genre_ 链接。如果一切设置正确,你的网站应该类似于下方的屏幕截图。输入值后,应将其保存,并且你将进入种类详情页面。 -![Genre Create Page - Express Local Library site](locallibary_express_genre_create_empty.png) +![种类创建页面——Express 本地图书馆网站](locallibary_express_genre_create_empty.png) -我们针对服务器端,验证的唯一错误是种类字段不能为空。下面的屏幕截图,显示了如果你没有提供种类(以红色突出显示),错误列表会是什么样子。 +我们在服务器端验证的唯一错误是种类字段必须至少包含三个字符。下面的屏幕截图显示了如果你提供仅包含一个或两个字符的类型(以黄色突出显示),错误列表会是什么样子。 -![](locallibary_express_genre_create_error.png) +![本地图书馆应用的创建种类部分。左栏有一个垂直导航栏。右侧部分是创建一个新种类,标题为“创建种类”。有一个标有“种类”的输入字段。底部有一个提交按钮。“提交”按钮正下方有一条错误消息,上面写着“需要类型名称”。本文作者强调了该错误消息。表格中没有视觉指示表明类型是必需的,也没有错误消息仅在出现错误时出现。](locallibary_express_genre_create_error.png) > [!NOTE] -> 我们的验证使用`trim()`,来确保不接受空格作为种类名称。我们还可以在表单中 的字段定义中,添加值`required='true'`,来验证客户端字段不为空: +> 我们的验证使用 `trim()` 来确保不接受空格作为种类名称。我们还对表单中​​字段定义添加 `required` ![布尔属性](/zh-CN/docs/Glossary/Boolean/HTML)来验证客户端上的字段不为空: > -> ```js -> input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' value=(undefined===genre ? '' : genre.name), required='true' ) +> ```pug +> input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' required value=(undefined===genre ? '' : genre.name) ) > ``` ## 下一步 From 9f99424e6011649ff07aad416bb5d0e6d78a1b02 Mon Sep 17 00:00:00 2001 From: MDN Web Docs GitHub Bot <108879845+mdn-bot@users.noreply.github.com> Date: Thu, 24 Oct 2024 13:24:50 +0200 Subject: [PATCH 02/53] [ko] sync translated content (#24211) ko: sync translated content --- files/ko/_redirects.txt | 1 + .../web_audio_api_5736136f9abf17a4d0f3d96dc690824f}/index.md | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) rename files/ko/{web/api/web_audio_api/tools => conflicting/web/api/web_audio_api_5736136f9abf17a4d0f3d96dc690824f}/index.md (91%) diff --git a/files/ko/_redirects.txt b/files/ko/_redirects.txt index 776b9a5f29936f..902f641a9b2d36 100644 --- a/files/ko/_redirects.txt +++ b/files/ko/_redirects.txt @@ -500,6 +500,7 @@ /ko/docs/Web/API/WebGL_API/Using_textures_in_WebGL /ko/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL /ko/docs/Web/API/WebRTC_API/adapter.js /ko/docs/Web/API/WebRTC_API#상호_운용성 /ko/docs/Web/API/Web_Audio_API/Migrating_from_webkitAudioContext /ko/docs/conflicting/Web/API/Web_Audio_API +/ko/docs/Web/API/Web_Audio_API/Tools /ko/docs/conflicting/Web/API/Web_Audio_API_5736136f9abf17a4d0f3d96dc690824f /ko/docs/Web/API/Window/DOMContentLoaded_event /ko/docs/Web/API/Document/DOMContentLoaded_event /ko/docs/Web/API/WindowEventHandlers/onpopstate /ko/docs/Web/API/Window/popstate_event /ko/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /ko/docs/Web/API/Window/setTimeout diff --git a/files/ko/web/api/web_audio_api/tools/index.md b/files/ko/conflicting/web/api/web_audio_api_5736136f9abf17a4d0f3d96dc690824f/index.md similarity index 91% rename from files/ko/web/api/web_audio_api/tools/index.md rename to files/ko/conflicting/web/api/web_audio_api_5736136f9abf17a4d0f3d96dc690824f/index.md index b9dbc6a97fa8ca..37f82eb27f9974 100644 --- a/files/ko/web/api/web_audio_api/tools/index.md +++ b/files/ko/conflicting/web/api/web_audio_api_5736136f9abf17a4d0f3d96dc690824f/index.md @@ -1,6 +1,7 @@ --- title: Web Audio 사용을 분석하기 위한 도구들 -slug: Web/API/Web_Audio_API/Tools +slug: conflicting/Web/API/Web_Audio_API_5736136f9abf17a4d0f3d96dc690824f +original_slug: Web/API/Web_Audio_API/Tools --- {{APIRef("Web Audio API")}} From 6dec4bba9fe6c0406c0b692b9c192dd8f7d21ea7 Mon Sep 17 00:00:00 2001 From: hoel44 Date: Thu, 24 Oct 2024 16:55:44 +0200 Subject: [PATCH 03/53] Update index.md one missing word in french translation (#24210) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update index.md French translation, one missing word added in the sentence. Traduction française, un mot manquant ajouté dans la phrase. --- .../client-side_web_apis/manipulating_documents/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/fr/learn/javascript/client-side_web_apis/manipulating_documents/index.md b/files/fr/learn/javascript/client-side_web_apis/manipulating_documents/index.md index 886987e7fb0e9a..4a49fad8d7ee0a 100644 --- a/files/fr/learn/javascript/client-side_web_apis/manipulating_documents/index.md +++ b/files/fr/learn/javascript/client-side_web_apis/manipulating_documents/index.md @@ -184,7 +184,7 @@ Supprimer des éléments est également plutôt simple, dès lors qu'on a une r sect.removeChild(linkPara); ``` -Si vous souhaitez un élément uniquement à partir d'une référence à cet élément, comme c'est souvent le cas, vous pouvez utiliser [`Element.remove()`](/fr/docs/Web/API/Element/remove) : +Si vous souhaitez supprimer un élément uniquement à partir d'une référence à cet élément, comme c'est souvent le cas, vous pouvez utiliser [`Element.remove()`](/fr/docs/Web/API/Element/remove) : ```js linkPara.remove(); From 09866498a3dc0715c528625e985aa51887f0696a Mon Sep 17 00:00:00 2001 From: Facundo Botta <118886942+FacuBotta@users.noreply.github.com> Date: Thu, 24 Oct 2024 16:55:57 +0200 Subject: [PATCH 04/53] Typofix for Notions de base en HTML: "Comment ..." => "Comme ..." (#24215) Update index.md Correction in line 125. "Comment ..." => "Comme ..." --- .../fr/learn/getting_started_with_the_web/html_basics/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files/fr/learn/getting_started_with_the_web/html_basics/index.md b/files/fr/learn/getting_started_with_the_web/html_basics/index.md index 4cfbdd20d30379..f3f1fe28c600a0 100644 --- a/files/fr/learn/getting_started_with_the_web/html_basics/index.md +++ b/files/fr/learn/getting_started_with_the_web/html_basics/index.md @@ -122,7 +122,7 @@ Revenons sur l'élément [``](/fr/docs/Web/HTML/Element/img) : Mon image de test ``` -Comment mentionné auparavant, cet élément permet d'intégrer une image dans la page là où l'élément est placé. L'image à afficher est désignée par l'attribut `src` (source) qui contient le chemin vers le fichier image. +Comme mentionné auparavant, cet élément permet d'intégrer une image dans la page là où l'élément est placé. L'image à afficher est désignée par l'attribut `src` (source) qui contient le chemin vers le fichier image. Nous avons également inclus un attribut `alt` (pour texte alternatif). [L'attribut `alt`](/fr/docs/Web/HTML/Element/img#écrire_des_descriptions_alternatives_significatives), permet d'indiquer un texte descriptif pour les personnes qui ne peuvent pas voir l'image : From b1b6036a94e52aa7240f720241bfd5f2543771bb Mon Sep 17 00:00:00 2001 From: SphinxKnight Date: Thu, 24 Oct 2024 19:49:53 +0200 Subject: [PATCH 05/53] Fix #23755 (#23964) * Update per en-US to fix #23755 * Typofix / missing translation --- .../global_objects/object/groupby/index.md | 156 +++++------------- 1 file changed, 45 insertions(+), 111 deletions(-) diff --git a/files/fr/web/javascript/reference/global_objects/object/groupby/index.md b/files/fr/web/javascript/reference/global_objects/object/groupby/index.md index 95dde8721604a6..a864b57b68c8b6 100644 --- a/files/fr/web/javascript/reference/global_objects/object/groupby/index.md +++ b/files/fr/web/javascript/reference/global_objects/object/groupby/index.md @@ -1,123 +1,77 @@ --- -title: Array.prototype.group() +title: Object.groupBy() slug: Web/JavaScript/Reference/Global_Objects/Object/groupBy +l10n: + sourceCommit: eb061bd719102c148cf87d12fd7056ed0c5071c8 --- -{{JSRef}} {{SeeCompatTable}} +{{JSRef}} -La méthode **`group()`** permet de grouper les éléments du tableau appelant selon les chaînes de caractères renvoyées par la fonction de test passée en argument. L'objet renvoyé par cette méthode aura des propriétés pour chaque groupe ainsi obtenu, qui contiendront un tableau des éléments du groupe. +> [!NOTE] +> Dans certaines versions de navigateurs, cette méthode fut implémentée avec `Array.prototype.group()`. Suite à des problèmes de compatibilité web, elle est désormais implémentée comme une méthode statique. Voir [le tableau de compatibilité des navigateurs](#compatibilité_des_navigateurs) pour plus de détails. - +La méthode statique **`Object.groupBy()`** groupe les éléments d'un itérable donné selon la chaîne de caractères obtenue par la fonction de rappel fournie. L'objet renvoyé possède différentes propriétés pour chaque groupe, contenant des tableaux avec les éléments du groupe. -Cette méthode devrait être utilisée lorsque les noms des groupes peuvent être représentés par des chaînes de caractères. Si vous avez besoin de grouper les éléments avec une clé qui est une valeur arbitraire (et pas nécessairement une chaîne), vous pouvez utiliser [`Array.prototype.groupToMap()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/groupToMap) à la place. +Cette méthode devrait être utilisée lorsque les noms des groupes peuvent être représentés par des chaînes de caractères. S'il vous faut grouper des éléments selon une clé qui peut être une valeur arbitraire, privilégiez la méthode [`Map.groupBy()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Map/groupBy). + + ## Syntaxe ```js-nolint -// Fonction fléchée -group((element) => { /* … */ } ) -group((element, index) => { /* … */ } ) -group((element, index, array) => { /* … */ } ) - -// Fonction de rappel -group(fnRappel) -group(fnRappel, thisArg) - -// Fonction de rappel en incise -group(function(element) { /* … */ }) -group(function(element, index) { /* … */ }) -group(function(element, index, array) { /* … */ }) -group(function(element, index, array) { /* … */ }, thisArg) +Object.groupBy(items, fnRappel) ``` ### Paramètres +- `items` + - : Un [itérable](/fr/docs/Web/JavaScript/Reference/Iteration_protocols#le_protocole_«_itérable_») (comme un [tableau (`Array`)](/fr/docs/Web/JavaScript/Reference/Global_Objects/Array)) dont les éléments seront groupés. - `fnRappel` - - - : La fonction à exécuter pour chaque élément du tableau. - - Elle est appelée avec les arguments suivants : - + - : Une fonction à exécuter pour chaque élément de l'itérable. Cette fonction devrait renvoyer une valeur qui peut être convertie en une clé de propriété (c'est-à-dire une chaîne de caractères ou un [symbole](/fr/docs/Web/JavaScript/Reference/Global_Objects/Symbol)) indiquant le groupe de l'élément courant. Cette fonction est appelée avec les arguments suivants : - `element` - - : La valeur de l'élément du tableau en cours de traitement. + - : L'élément courant qui est traité. - `index` - - : L'indice de l'élément courant dans le tableau. - - `array` - - : Le tableau sur lequel `group()` a été appelée. - - L'objet renvoyé par la fonction de rappel indique le groupe de l'élément courant. La valeur renvoyée doit pouvoir être convertie en une chaîne de caractères (qui sera alors utilisée comme nom de propriété pour l'objet final). - -- `thisArg` {{optional_inline}} - - - : L'objet à utiliser comme valeur pour [`this`](/fr/docs/Web/JavaScript/Reference/Operators/this) pour `fnRappel`. - - Cet argument est ignoré pour les fonctions fléchées qui disposent de leur propre portée lexicale, utilisée à la place. Sinon, si `thisArg` n'est pas fourni, c'est la valeur `this` de la portée d'exécution qui est appelée, ou `undefined` si la fonction est appelée en [mode strict](/fr/docs/Web/JavaScript/Reference/Strict_mode). + - : L'indice de l'élément courant qui est traité. ### Valeur de retour -Un [objet](/fr/docs/Web/JavaScript/Reference/Global_Objects/Object) avec une propriété pour chaque groupe. Chaque propriété a comme valeur un tableau qui contient les éléments du groupe correspondant. Cette valeur de retour est un objet qui **n'hérite pas** de `Object.prototype`. - -### Exceptions - -- `TypeError` - - : La fonction de rappel fournie en argument n'est pas appelable. +Un [objet avec un prototype `null`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Object#objets_avec_prototype_null) avec une propriété pour chaque groupe, qui contient un tableau des éléments du groupe correspondant. ## Description -La méthode `group()` exécute la fonction `fnRappel` une fois pour chaque indice du tableau, qui renvoie une chaîne de caractères (ou une valeur qui peut être convertie en une chaîne) indiquant le groupe de l'élément. Une nouvelle propriété ayant comme valeur un tableau est créé dans l'objet résultat pour chaque nom de groupe unique renvoyé par la fonction de rappel. Chaque élément est ajouté au tableau de la propriété qui correspond à son groupe. - -`fnRappel` est appelée pour _chaque_ indice du tableau et pas uniquement pour ceux pour lesquels une valeur a été affectée. Les emplacements vides des [tableaux creux](/fr/docs/Web/JavaScript/Guide/Indexed_collections#tableaux_creux) se comportent comme avec `undefined`. - -`fnRappel` est appelée avec la valeur de l'élément courant, l'indice de cet élément, ainsi que le tableau complet. Bien que les groupes dépendent souvent de la valeur de l'élément courant, il est possible d'implémenter des stratégies de groupement basées sur les valeurs des autres éléments du tableau. - -Si un paramètre `thisArg` est fourni à la méthode `group()`, il sera utilisé comme valeur pour [`this`](/fr/docs/Web/JavaScript/Reference/Operators/this) à chaque appel de `fnRappel`. Si ce paramètre n'est pas fourni, c'est [`undefined`](/fr/docs/Web/JavaScript/Reference/Global_Objects/undefined) qui sera utilisé. - -La méthode `group()` est [une méthode de copie](/fr/docs/Web/JavaScript/Reference/Global_Objects/Array#méthodes_de_copie_et_de_modification). Elle ne modifie pas le tableau courant (`this`) mais renvoie un objet dont les propriétés sont des tableaux qui contiennent les mêmes éléments que ceux du tableau d'origine. On notera donc que l'objet renvoyé référence les _mêmes_ éléments que ceux du tableau original et pas des [copies profondes](/fr/docs/Glossary/Deep_copy). Modifier la structure interne de ces éléments se reflètera sur le tableau original et sur l'objet renvoyé. - -La méthode `group()` est [générique](/fr/docs/Web/JavaScript/Reference/Global_Objects/Array#méthodes_génériques). Elle s'attend uniquement à ce que la valeur `this` ait une propriété `length` et des propriétés dont les clés sont des entiers. +`Object.groupBy()` appelle une fonction de rappel `fnRappel()` sur chaque élément de l'itérable. Cette fonction renvoie alors une chaîne de caractères ou un symbole (sinon la valeur est [convertie en chaîne de caractères](/fr/docs/Web/JavaScript/Reference/Global_Objects/String#conversion_en_chaîne_de_caractères)) qui indique le groupe de l'élément. Les valeurs renvoyées par `fnRappel()` sont utilisées comme clés pour l'objet renvoyé par `Object.groupBy()`. La valeur de chaque propriété est un tableau dont les éléments sont ceux pour lesquels la fonction de rappel a renvoyé la même valeur. -### Modifier le tableau avec la fonction de rappel - -La méthode `group()` ne modifie pas le tableau sur lequel elle est appelée, mais la fonction fournie pour `fnRappel` peut le modifier. Les éléments traités par `group()` sont fixés _avant_ le premier appel à `fnRappel`. Ainsi : - -- `fnRappel` ne parcourra pas les éléments ajoutés après le début de l'appel à `group()`. -- Les éléments qui sont affectés à des indices ayant déjà été visités ne seront pas revus par `fnRappel`. -- Les éléments qui sont affectés à des indices en dehors de l'intervalle du tableau ne seront pas parcourus par `fnRappel`. -- Si un élément existant du tableau et qui n'a pas encore été traité mais est modifié par `fnRappel`, la valeur qui sera passée à `fnRappel` sera la valeur au moment où `group()` visite l'indice de l'élément. -- Les éléments qui sont [supprimés avec `delete`](/fr/docs/Web/JavaScript/Reference/Operators/delete) sont tout de même parcourus. - -> [!WARNING] -> Les modifications concurrentes comme celles qui sont décrites dans le paragraphe précédent mènent souvent à du code difficilement compréhensible et devraient généralement être évitées. +Les éléments de l'objet renvoyé et de l'itérable original sont les mêmes (il ne s'agit pas de [copies profondes](/fr/docs/Glossary/Deep_copy)). Modifier la structure interne des éléments sera reflété à la fois sur l'itérable original et sur l'objet renvoyé. ## Exemples -### Utiliser `group()` +### Utiliser `Object.groupBy()` -On définit un tableau contenant des objets qui représentent un inventaire alimentaire. Chaque type d'aliment a une propriété `type` et une propriété `quantite`. +Pour commencer, on définit un tableau contenant un inventaire d'aliments. Chaque aliment possède un nom, un type et une quantité. ```js const inventaire = [ - { nom: "asperge", type: "legume", quantite: 5 }, - { nom: "banane", type: "fruit", quantite: 0 }, + { nom: "asperges", type: "légumes", quantite: 5 }, + { nom: "bananes", type: "fruit", quantite: 0 }, { nom: "agneau", type: "viande", quantite: 23 }, - { nom: "cerise", type: "fruit", quantite: 5 }, + { nom: "cerises", type: "fruit", quantite: 5 }, { nom: "poisson", type: "viande", quantite: 22 }, ]; ``` -Le code qui suit groupe les éléments du tableau selon la valeur de leur propriété `type`. +L'instruction suivante groupera les éléments selon leur propriété `type`. ```js -const resultat = inventaire.group(({ type }) => type); +const resultat = Object.groupBy(inventaire, ({ type }) => type); -/* resultat vaut : +/* Le résultat sera : { - legume: [ - { nom: 'asperge', type: 'legume', quantite: 5 }, + légumes: [ + { nom: 'asperges', type: 'légumes', quantite: 5 }, ], fruit: [ - { nom: "banane", type: "fruit", quantite: 0 }, - { nom: "cerise", type: "fruit", quantite: 5 } + { nom: "bananes", type: "fruit", quantite: 0 }, + { nom: "cerises", type: "fruit", quantite: 5 } ], viande: [ { nom: "agneau", type: "viande", quantite: 23 }, @@ -127,55 +81,32 @@ const resultat = inventaire.group(({ type }) => type); */ ``` -La fonction fléchée renvoie la valeur de `type` pour chaque élément du tableau. Ici, l'argument `{ type }` passé à la fonction est un exemple de [décomposition objet pour les arguments d'une fonction](/fr/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#décomposer_les_propriétés_dobjets_passés_en_arguments). Cela récupère la propriété `type` de l'objet passé en paramètre et affecte cette valeur à une variable nommée `type` dans le corps de la fonction. Il s'agit d'une écriture concise pour accéder aux valeurs des propriétés pertinentes d'un objet dans une fonction. +La fonction fléchée renvoie la valeur de `type` pour chaque élément du tableau. On notera que l'argument `{ type }` est un exemple [de la syntaxe de décomposition d'objet pour les arguments de fonction](/fr/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#décomposer_les_propriétés_dobjets_passés_en_arguments). Cela extrait la propriété `type` d'un objet passé en paramètre et affecte la valeur à une variable nommée `type` dans le corps de la fonction. On peut ainsi écrire succinctement l'accès aux propriétés d'un élément dans une fonction. -On peut aussi créer des groupes selon un critère utilisant plusieurs propriétés des éléments. Dans ce qui suit, on a un exemple semblable qui place les éléments dans un groupe `ok` ou un groupe `restock` selon la valeur de la propriété `quantite`. +On pourrait également créer des groupes selon les valeurs d'une ou plusieurs propriétés de l'élément. Dans l'exemple qui suit, on place les aliments dans deux groupes `ok` ou `restock` selon la valeur de leur propriété `quantite`. ```js function maFonctionDeRappel({ quantite }) { return quantite > 5 ? "ok" : "restock"; } -const resultat2 = inventaire.group(maFonctionDeRappel); +const resultat2 = Object.groupBy(inventaire, maFonctionDeRappel); -/* resultat2 vaut : +/* Le résultat sera : { restock: [ - { name: "asperge", type: "legume", quantite: 5 }, - { name: "banane", type: "fruit", quantite: 0 }, - { name: "cerise", type: "fruit", quantite: 5 } + { nom: "asperges", type: "légumes", quantite: 5 }, + { nom: "bananes", type: "fruit", quantite: 0 }, + { nom: "cerises", type: "fruit", quantite: 5 } ], ok: [ - { name: "agneau", type: "viande", quantite: 23 }, - { name: "poisson", type: "viande", quantite: 22 } + { nom: "agneau", type: "viande", quantite: 23 }, + { nom: "poisson", type: "viande", quantite: 22 } ] } */ ``` -### Utiliser `group()` sur des tableaux creux - -Lorsqu'on utilise `group()` sur [un tableau creux](/fr/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), les emplacements vides du tableau sont considérés comme ayant la valeur `undefined`. - -```js -console.log([1, , 3].group((x) => x)); // { 1: [1], undefined: [undefined], 3: [3] } -``` - -### Appeler `group()` sur des objets qui ne sont pas des tableaux - -La méthode `group()` lit la propriété `length` de `this` puis parcourt les propriétés dont les clés sont des nombres entiers. - -```js -const semblableTableau = { - length: 3, - 0: 2, - 1: 3, - 2: 4, -}; -console.log(Array.prototype.group.call(semblableTableau, (x) => x % 2)); -// { 0: [2, 4], 1: [3] } -``` - ## Spécifications {{Specifications}} @@ -186,5 +117,8 @@ console.log(Array.prototype.group.call(semblableTableau, (x) => x % 2)); ## Voir aussi -- [`Array.prototype.groupToMap()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/groupToMap) qui permet de regrouper les éléments d'un tableau en une `Map`, avec n'importe quel type de valeur comme clé. -- [Une prothèse d'émulation de `Array.prototype.group()` dans la bibliothèque tierce `core-js`](https://github.com/zloirock/core-js#array-grouping) +- [Une prothèse d'émulation (polyfill) de `Object.groupBy()` dans la bibliothèque tierce `core-js`](https://github.com/zloirock/core-js#array-grouping) +- [Le guide sur les collections indexées](/fr/docs/Web/JavaScript/Guide/Indexed_collections) +- [`Array.prototype.reduce()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) +- [`Object.fromEntries()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) +- [`Map.groupBy()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Map/groupBy) From b349fb24de079a9ebbbaeea3665e9af95a90ec53 Mon Sep 17 00:00:00 2001 From: hiroya-uga Date: Thu, 24 Oct 2024 17:46:52 +0900 Subject: [PATCH 06/53] [ja] sync translated content --- files/ja/web/accessibility/aria/roles/search_role/index.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/files/ja/web/accessibility/aria/roles/search_role/index.md b/files/ja/web/accessibility/aria/roles/search_role/index.md index a88d01ae78f9bc..5c00c72a9af738 100644 --- a/files/ja/web/accessibility/aria/roles/search_role/index.md +++ b/files/ja/web/accessibility/aria/roles/search_role/index.md @@ -3,7 +3,7 @@ title: "ARIA: search ロール" slug: Web/Accessibility/ARIA/Roles/search_role --- -検索 (`search`) [ランドマークロール](/ja/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles)は、ページ、サイト、またはサイトのコレクションの検索に使用されるページのセクションを識別するために使用します。 +検索 (`search`) ロールは、ページ、サイト、またはサイトのコレクションの検索に使用されるページのセクションを識別するために使用します。 ```html
@@ -13,10 +13,12 @@ slug: Web/Accessibility/ARIA/Roles/search_role ## 説明 -検索 (`search`) ロールは、[ランドマーク](/ja/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles)です。 ランドマークは、支援技術によって使用され、文書の大きなセクションを素早く識別してナビゲートすることができます。 検索 (`search`) ロールは、全体として組み合わせて検索機能を作成する項目およびオブジェクトを含むコンテナー要素に追加します。 `` が検索フォームの場合、フォーム ([`form`](/ja/docs/Web/Accessibility/ARIA/Roles/Form_Role)) ロールの代わりに検索 (`search`) ロールを使用します。 文書に複数の検索が含まれている場合、それぞれに固有のラベルを持つべきです。 [`search` 型の `` 要素](/ja/docs/Web/HTML/Element/input/search)はありますが、検索ランドマークを定義する HTML 要素はありません。 +検索 (`search`) ロールは、文書やアプリケーションの検索機能を構成するために組み合わされたすべての要素を囲むコンテナー要素に追加できる[ランドマーク](/ja/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles)で、これには子孫要素として [``](/ja/docs/Web/HTML/Element/input/search) が含まれます。文書に複数の検索が含まれている場合、それぞれに固有のラベルを持つべきです。ただし、同じ検索が繰り返される場合は同じラベルを使用します。 [`search` 型の `` 要素](/ja/docs/Web/HTML/Element/input/search) がありますが、これ自体は検索ランドマークを定義するものではありません。検索ランドマークを定義するには、[``](/ja/docss/Web/HTML/Element/search) 要素を使用してください。 ## 例 +[``](/ja/docss/Web/HTML/Element/form) 要素が検索フォームの場合、[`form`](/ja/docs/Web/Accessibility/ARIA/Roles/form_role) ロールの代わりに `search` ロールを使用してください。 + ```html From 572d2919bd7551a0d8940da8e39de774d5f1877c Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 20 Oct 2024 11:06:36 +0900 Subject: [PATCH 07/53] =?UTF-8?q?2024/10/02=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- files/ja/web/http/mime_types/index.md | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/files/ja/web/http/mime_types/index.md b/files/ja/web/http/mime_types/index.md index 7a0fe3ef561e29..07c9c15b580572 100644 --- a/files/ja/web/http/mime_types/index.md +++ b/files/ja/web/http/mime_types/index.md @@ -1,9 +1,8 @@ --- title: MIME タイプ(IANA メディア種別) slug: Web/HTTP/MIME_types -original_slug: Web/HTTP/Basics_of_HTTP/MIME_types l10n: - sourceCommit: 592f6ec42e54981b6573b58ec0343c9aa8cbbda8 + sourceCommit: f75b2c86ae4168e59416aed4c7121f222afc201d --- {{HTTPSidebar}} @@ -79,7 +78,7 @@ MIME タイプは大文字と小文字を区別しませんが、伝統的に小 - : 三次元のオブジェクトやシーンなどのモデルデータです。例えば、 `model/3mf` や `model/vrml` などがあります。 [(IANA での model 型の登録を見る)](https://www.iana.org/assignments/media-types/media-types.xhtml#model) - `text` - - : テキストのみのデータで、人間が読むことができるあらゆるコンテンツ、ソースコード、コンマ区切り値 (CSV) 形式のデータのようなテキストデータを含みます。 + - : テキストのみのデータで、人間が読むことができるあらゆるコンテンツ、ソースコード、カンマ区切り値 (CSV) 形式のデータのようなテキストデータを含みます。 例えば、 `text/plain`, `text/csv`, `text/html` などがあります。 [(IANA での text 型の登録を見る)](https://www.iana.org/assignments/media-types/media-types.xhtml#text) - `video` @@ -190,18 +189,7 @@ MIME タイプが `image` であるファイルは、画像データを含んで 音声ファイルや動画ファイルの MIME タイプに関しては、通常、コンテナー形式(ファイルタイプ)を指定します。 オプションの[コーデック引数](/ja/docs/Web/Media/Formats/codecs_parameter)を MIME タイプに追加すると、使用するコーデックと、コーデックプロファイル、レベルなど、メディアのエンコードに使用したオプションをさらに指定することができます。 -ウェブコンテンツに使用されるMIMEタイプのうち、最も一般的なものを以下に一覧で示します。 -ただし、これは利用可能なすべてのタイプの完全なリストではありません。 -これについては[メディアコンテナー形式のガイド](/ja/docs/Web/Media/Formats/Containers)を参照してください。 - -| MIME タイプ | 音声または動画のタイプ | -| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `audio/wave` `audio/wav` `audio/x-wav` `audio/x-pn-wav` | WAVE コンテナー形式の音声ファイル。 PCM オーディオコーデック (WAVE コーデック "1") はたいていサポートされていますが、他のコーデックのサポートは (あるとしても) 限定的です。 | -| `audio/webm` | WebM コンテナー形式の音声ファイル。 Vorbis や Opus が WebM 仕様書で公式に対応しているコーデックです。 | -| `video/webm` | WebM コンテナー形式の、おそらく音声も含む動画ファイル。VP8 や VP9 がもっとも一般的に使用される動画コーデックです。 Vorbis や Opus がもっとも一般的な音声コーデックです。 | -| `audio/ogg` | Ogg コンテナー形式の音声ファイル。 Vorbis が、このコンテナーでもっとも一般的に使用される音声コーデックです。しかし、 Opus も同様に Ogg で対応しました。 | -| `video/ogg` | Ogg コンテナー形式の、おそらく音声も含む動画ファイル。通常の動画コーデックは Theora、音声コーデックは Vorbis ですが、 Opus がもっと有名になってきています。 | -| `application/ogg` | OGG コンテナー形式を使用する音声または動画のファイル。通常の動画コーデックは Theora、音声コーデックは Vorbis です。 | +よくあるメディア型についての詳しい情報は、[よくある MIME タイプ](/ja/docs/Web/HTTP/MIME_types/Common_types)ページを参照してください。 ### multipart/form-data @@ -305,6 +293,8 @@ Content-Range: bytes 300-400/1270 ## 正しい MIME タイプを設定することの重要性 +サーバーの設定項目によっては、ファイルの結合、圧縮、キャッシュなどの最適化を行うために、関連する MIME タイプを使用することがあります。特定の MIME タイプのファイルを圧縮する Apache の設定例については、[h5bp/server-configs-apache](https://github.com/h5bp/server-configs-apache/blob/main/h5bp/web_performance/compression.conf) を参照してください。 + 多くのウェブサーバーは未知の種類のリソースについて、既定の `application/octet-stream` MIME タイプを送ります。セキュリティ上の理由で、多くのブラウザーはこのようなリソースに既定のアクションを定義することを許可せず、リソースを使用するためにディスクへ保存することをユーザーに強制します。 以下のような誤ったサーバー設定がよく見られます。 @@ -314,9 +304,9 @@ Content-Range: bytes 300-400/1270 この場合、サーバーが `application/x-rar-compressed` を送信するように設定してください。 - 音声および動画。 正しい MIME タイプを持つリソースだけが、 {{HTMLElement("video")}} または {{HTMLElement("audio")}} 要素で再生されます。 - [音声および動画に対して正しい MIME タイプを使用する](/ja/docs/Web/Media/Formats)よう注意してください。 -- 独自のファイルタイプ。 - 特別な操作ができなくなるため、`application/octet-stream` の使用は避けてください。ほとんどのブラウザーは、この汎用的な MIME タイプに既定の動作 (「Word で開く」など) を定義することができません。 `application/vnd.mspowerpoint` のような特定の型ならば、ユーザーがそのようなファイルを自動的に選択したプレゼンテーションソフトウェアで開くことができます。 + [音声および動画の MIME タイプ](/ja/docs/Web/Media/Formats)を正しく使用するよう注意してください。 +- 独自のファイル型。 + `application/vnd.mspowerpoint` のような特定の型ならば、ユーザーがそのようなファイルを自動的に選択したプレゼンテーションソフトウェアで開くことができます。 ## MIME スニッフィング From 15aa53b04da1dc8e6915accaf7c1f0dfabeaa07d Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 20 Oct 2024 11:21:56 +0900 Subject: [PATCH 08/53] =?UTF-8?q?2024/10/09=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- files/ja/_redirects.txt | 2 +- files/ja/_wikihistory.json | 2 +- files/ja/web/css/url_function/index.md | 199 +++++++++++++++++++++++++ 3 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 files/ja/web/css/url_function/index.md diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 734bf8050932e2..e6c138d23bcb9a 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -3834,7 +3834,7 @@ /ja/docs/Web/CSS/transform-function/translateZ() /ja/docs/Web/CSS/transform-function/translateZ /ja/docs/Web/CSS/uri /ja/docs/Web/CSS/url_value /ja/docs/Web/CSS/url /ja/docs/Web/CSS/url_value -/ja/docs/Web/CSS/url() /ja/docs/Web/CSS/url_value +/ja/docs/Web/CSS/url() /ja/docs/Web/CSS/url_function /ja/docs/Web/CSS/user-ident /ja/docs/Web/CSS/custom-ident /ja/docs/Web/CSS/var() /ja/docs/Web/CSS/var /ja/docs/Web/CSS/visible /ja/docs/Web/CSS/visibility diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index 6b4d1590f430b3..2ef7c5304a4899 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -19992,7 +19992,7 @@ "modified": "2020-10-15T21:40:12.796Z", "contributors": ["mfuji09", "okayurisotto", "teoli", "YuichiNukiyama"] }, - "Web/CSS/url_value": { + "Web/CSS/url_function": { "modified": "2020-10-15T22:29:36.625Z", "contributors": ["mfuji09"] }, diff --git a/files/ja/web/css/url_function/index.md b/files/ja/web/css/url_function/index.md new file mode 100644 index 00000000000000..b9e8a82d01b850 --- /dev/null +++ b/files/ja/web/css/url_function/index.md @@ -0,0 +1,199 @@ +--- +title: url() +slug: Web/CSS/url_function +l10n: + sourceCommit: b2833ddfd45cae1bb5e050d24637865e9327408d +--- + +{{CSSRef}} + +**`url()`** は [CSS](/ja/docs/Web/CSS) の[関数](/ja/docs/Web/CSS/CSS_Functions)で、ファイルを含めるために使用します。引数は絶対 URL、相対 URL、Blob URL、データ URL の何れかです。 **`url()`** 関数は {{cssxref("attr")}} 関数のように、他の CSS 関数に引数として渡すことができます。値を使用するプロパティに応じて、求められるリソースは画像、フォント、スタイルシートのいずれかになります。`url()` 関数記法は `` データ型の値になります。 + +> **メモ:** {{Glossary("URI")}} と {{Glossary("URL")}} との間には違いがあります。 URI は単純にリソースを識別します。 URL は URI の一種で、リソースの*場所*を記述します。 URI はリソースの URL または名前 ({{Glossary("URN")}}) であることがあります。 +> +> CSS Level 1 では、 `url()` 関数記法は真に URL のみを記述していました。 CSS Level 2 では、 `url()` の定義はあらゆる URI、 URL または URN のどちらかを記述するように拡張されました。ややこしいことに、これは `url()` を CSS の `` データ型の生成のために使用することができることを意味していました。この変更は紛らわしいばかりでなく、議論になりやすく、 URN が実際の CSS で使用されることはほぼあり得ないため不必要でした。混乱を軽減するために、 CSS Level 3 ではより狭い初めの定義まで戻りました。現在では、 `url()` は真に `` のみを記述します。 + +```css +/* 単純な使い方 */ +url("https://example.com/images/myImg.jpg"); +url('https://example.com/images/myImg.jpg'); +url(https://example.com/images/myImg.jpg); +url("data:image/jpg;base64,iRxVB0…"); +url(myImg.jpg); +url(#IDofSVGpath); + +/* 関連するプロパティ */ +background-image: url("star.gif"); +list-style-image: url('../images/bullet.jpg'); +content: url("my-icon.jpg"); +cursor: url(my-cursor.cur); +border-image-source: url(/media/diamonds.png); +src: url('fantastic-font.woff'); +offset-path: url(#path); +mask-image: url("masks.svg#mask1"); + +/* 代替付きのプロパティ */ +cursor: url(pointer.cur), pointer; + +/* 関連する一括指定プロパティ */ +background: url('star.gif') bottom right repeat-x blue; +border-image: url("/media/diamonds.png") 30 fill / 30px / 30px space; + +/* 他の CSS 関数の引数として */ +background-image: cross-fade(20% url(first.png), url(second.png)); +mask-image: image(url(mask.png), skyblue, linear-gradient(rgb(0 0 0 / 100%), transparent)); + +/* 一括指定ではない複数の値の一部として */ +content: url(star.svg) url(star.svg) url(star.svg) url(star.svg) url(star.svg); + +/* アットルール */ +@document url("https://www.example.com/") { /* … */ } +@import url("https://www.example.com/style.css"); +@namespace url(http://www.w3.org/1999/xhtml); +``` + +相対 URL が使用された場合は、スタイルシートの URL からの相対となります (ウェブページの URL からではありません)。 + +**`url()`** 関数は {{cssxref('background')}}, {{cssxref('background-image')}}, {{cssxref('border')}}, {{cssxref('border-image')}}, {{cssxref('border-image-source')}}, {{cssxref('content')}}, {{cssxref('cursor')}}, {{cssxref('filter')}}, {{cssxref('list-style')}}, {{cssxref('list-style-image')}}, {{cssxref('mask')}}, {{cssxref('mask-image')}}, {{cssxref('offset-path')}}, {{cssxref('clip-path')}}, +[@font-face](/ja/docs/Web/CSS/@font-face) ブロック内での [src](/ja/docs/Web/CSS/@font-face/src), [@counter-style/`symbol`](/ja/docs/Web/CSS/@counter-style/symbols) の値として使用することができます。 + +## 構文 + +### 値 + +- `` + + - : URL まだは SVG 図形の ID を指定することができる文字列です。 + + - url + + - : 含まれるウェブリソースへの相対アドレス、絶対アドレス、ポインターのURL、またはデータ URI であり、任意で単一引用符または二重引用符を使用することができます。URL に括弧、空白、引用符が含まれている場合で、これらの文字がエスケープされていないか、アドレスに 0x7e 以上の制御文字が含まれている場合、引用符は必須です。二重引用符は二重引用符の中に入れることはできず、単一引用符はエスケープされない限り単一引用符の中に入れることはできません。以下のものはすべて有効であり、同等です。 + + ```css + : url("https://example.com/image.png") + : url('https://example.com/image.png') + : url(https://example.com/image.png) + ``` + + URL を引用符なしで書く場合は、バックスラッシュを (`\`) を URL に含まれる括弧、ホワイトスペース文字、単一引用符 (`'`)、二重引用符 (`"`) の前に使用してください。 + + - パス + - : [SVG 図形](/ja/docs/Web/SVG/Tutorial/Basic_Shapes)または [SVG フィルター](/ja/docs/Web/SVG/Element/filter)の ID への参照です。 + +- `` + - : 将来的には、`url()` 関数で修飾子、識別子、または関数記法を指定して、URL 文字列の意味を変更できるようになるかもしれません。これはサポートされておらず、仕様書でも完全に定義されていません。 + +## 形式文法 + +```plain +url( * ) +``` + +## 例 + +### background プロパティで使用される URL + +```css +body { + background: url("https://mdn.github.io/shared-assets/images/examples/leopard.jpg") + #00d no-repeat fixed; +} +``` + +{{EmbedLiveSample("As the background property value", "100%", "200")}} + +### リストの先頭記号として使用される画像を読み込む URL + +```html hidden +
    +
  • one
  • +
  • two
  • +
  • there
  • +
+``` + +```css hidden +ul { + font-size: 3rem; + margin: 0; +} +``` + +```css +ul { + list-style: outside + url("https://mdn.github.io/shared-assets/images/examples/firefox-logo.svg"); +} +``` + +{{EmbedLiveSample("For setting an image as a list bullet", "100%", "200")}} + +### content プロパティの使用 + +#### HTML + +```html +
    +
  • One
  • +
  • Two
  • +
  • Three
  • +
+``` + +#### CSS + +```css +li::after { + content: " - " + url("https://mdn.github.io/shared-assets/images/examples/star-white_16x16.png"); +} +``` + +#### 結果 + +{{EmbedLiveSample("Usage_in_the_content_property", "100%", "110")}} + +### データ URL の使用 + +#### CSS + +```css +body { + background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='90' height='45'%3E%3Cpath d='M10 10h60' stroke='%2300F' stroke-width='5'/%3E%3Cpath d='M10 20h60' stroke='%230F0' stroke-width='5'/%3E%3Cpath d='M10 30h60' stroke='red' stroke-width='5'/%3E%3C/svg%3E"); +} +``` + +{{EmbedLiveSample("Using_a_data_URL", "100%", 100)}} + +### フィルターでの使用 + +URL がフィルターへのパスとして使用される場合、 URL は以下のどちらかでなければなりません。 + +1. SVG ファイルへのパスに、追加されるフィルターの ID が付いたもの。 +2. SVG がページ内にある場合は、フィルターの ID。 + +```css +.blur { + filter: url(my-file.svg#svg-blur); /* フィルターとして使用する SVG ファイルの URL */ +} + +.inline-blur { + filter: url(#svg-blur); /* HTML ページに埋め込まれた SVG の ID */ +} +``` + +## 仕様書 + +{{Specifications}} + +## ブラウザーの互換性 + +{{Compat}} + +## 関連情報 + +- {{cssxref("<gradient>")}} +- {{cssxref("element", "element()")}} +- {{cssxref("image/image", "image()")}} +- {{cssxref("image/image-set", "image-set()")}} +- {{cssxref("cross-fade", "cross-fade()")}} From c51242578e9d6442a1295c6333b266bd79437beb Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 20 Oct 2024 11:32:22 +0900 Subject: [PATCH 09/53] =?UTF-8?q?2024/09/05=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=96=B0=E8=A6=8F=E7=BF=BB=E8=A8=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- files/ja/web/css/url_value/index.md | 182 ++-------------------------- 1 file changed, 12 insertions(+), 170 deletions(-) diff --git a/files/ja/web/css/url_value/index.md b/files/ja/web/css/url_value/index.md index e9a4705e0d42b5..22c7382db46584 100644 --- a/files/ja/web/css/url_value/index.md +++ b/files/ja/web/css/url_value/index.md @@ -1,191 +1,33 @@ --- -title: url() +title: slug: Web/CSS/url_value -original_slug: Web/CSS/url l10n: - sourceCommit: b82ff59aab7883b7bb2222cf9f9f9b6eed818e08 + sourceCommit: 5178e1e7c9edf0c9c652275ae62f090042ce2422 --- {{CSSRef}} -**`url()`** は [CSS](/ja/docs/Web/CSS) の[関数](/ja/docs/Web/CSS/CSS_Functions)で、ファイルを含めるために使用します。引数は絶対 URL、相対 URL、Blob URL、データ URL の何れかです。 **`url()`** 関数は {{cssxref("attr")}} 関数のように、他の CSS 関数に引数として渡すことができます。値を使用するプロパティに応じて、求められるリソースは画像、フォント、スタイルシートの何れかになります。`url()` 関数表記は `` データ型の値になります。 - -> **メモ:** {{Glossary("URI")}} と {{Glossary("URL")}} との間には違いがあります。 URI は単純にリソースを識別します。 URL は URI の一種で、リソースの*場所*を記述します。 URI はリソースの URL または名前 ({{Glossary("URN")}}) であることがあります。 -> -> CSS Level 1 では、 `url()` 関数記法は真に URL のみを記述していました。 CSS Level 2 では、 `url()` の定義はあらゆる URI、 URL または URN のどちらかを記述するように拡張されました。ややこしいことに、これは `url()` を CSS の `` データ型の生成のために使用することができることを意味していました。この変更は紛らわしいばかりでなく、議論になりやすく、 URN が実際の CSS で使用されることはほぼあり得ないため不必要でした。混乱を軽減するために、 CSS Level 3 ではより狭い初めの定義まで戻りました。現在では、 `url()` は真に `` のみを記述します。 - -```css -/* 単純な使い方 */ -url(https://example.com/images/myImg.jpg); -url(data:image/png;base64,iRxVB0…); -url(myFont.woff); -url(#IDofSVGpath); - -/* 関連するプロパティ */ -background-image: url("star.gif"); -list-style-image: url('../images/bullet.jpg'); -content: url("pdficon.jpg"); -cursor: url(mycursor.cur); -border-image-source: url(/media/diamonds.png); -src: url('fantasticfont.woff'); -offset-path: url(#path); -mask-image: url("masks.svg#mask1"); - -/* 代替付きのプロパティ */ -cursor: url(pointer.cur), pointer; - -/* 関連する一括指定プロパティ */ -background: url('star.gif') bottom right repeat-x blue; -border-image: url("/media/diamonds.png") 30 fill / 30px / 30px space; - -/* 他の CSS 関数の引数として */ -background-image: cross-fade(20% url(first.png), url(second.png)); -mask-image: image(url(mask.png), skyblue, linear-gradient(rgba(0, 0, 0, 1.0), transparent)); - -/* 一括指定ではない複数の値の一部として */ -content: url(star.svg) url(star.svg) url(star.svg) url(star.svg) url(star.svg); - -/* アットルール */ -@document url("https://www.example.com/") { /* … */ } {{Experimental_Inline}} -@import url("https://www.example.com/style.css"); -@namespace url(http://www.w3.org/1999/xhtml); -``` - -相対 URL が使用された場合は、スタイルシートの URL からの相対となります (ウェブページの URL からではありません)。 - -**`url()`** 関数は {{cssxref('background')}}, {{cssxref('background-image')}}, {{cssxref('border')}}, {{cssxref('border-image')}}, {{cssxref('border-image-source')}}, {{cssxref('content')}}, {{cssxref('cursor')}}, {{cssxref('filter')}}, {{cssxref('list-style')}}, {{cssxref('list-style-image')}}, {{cssxref('mask')}}, {{cssxref('mask-image')}}, {{cssxref('offset-path')}}, -[@font-face](/ja/docs/Web/CSS/@font-face) ブロック内での [src](/ja/docs/Web/CSS/@font-face/src), [@counter-style/symbol](/ja/docs/Web/CSS/@counter-style/symbols) の値として使用することができます。 +**``** は [CSS](/ja/docs/Web/CSS) の[データ型](/ja/docs/Web/CSS/CSS_Types)で、リソースを指します。リソースには画像、動画、CSS ファイル、フォントファイル、SVG 機能などがあります。 ## 構文 -### 値 - -- `` - - - : URL まだは SVG 図形の ID を指定することができる文字列です。 - - - \ - - - : 含まれるウェブリソースへの相対アドレス、絶対アドレス、ポインターのURL、またはデータ URI であり、任意で単一引用符または二重引用符を使用することができます。URL に括弧、空白、引用符が含まれている場合で、これらの文字がエスケープされていないか、アドレスに 0x7e 以上の制御文字が含まれている場合、引用符は必須です。二重引用符は二重引用符の中に入れることはできず、単一引用符はエスケープされない限り単一引用符の中に入れることはできません。以下のものはすべて有効であり、同等です。 - - ```css - : url("https://example.com/image.png") - : url('https://example.com/image.png') - : url(https://example.com/image.png) - ``` - - URL を引用符なしで書く場合は、バックスラッシュを (`\`) を URL に含まれる括弧、ホワイトスペース文字、単一引用符 (`'`)、二重引用符 (`"`) の前に使用してください。 - - - パス - - : [SVG 図形](/ja/docs/Web/SVG/Tutorial/Basic_Shapes)の ID への参照 — `circle`, `ellipse`, `line`, `path`, `polygon`, `polyline`, `rect` — パスとして図形の形状を使用します。 - -- `` {{Experimental_Inline}} - - : 将来的に `url()` 関数は、URL 文字列の意味を変更する修飾子、識別子、関数記法の指定に対応するかもしれません。これはまだ対応されておらず、仕様書では完全には定義されていません。 - -## 形式文法 - -```css -url( * ) +```plain + = | ``` -## 例 - -### background プロパティで使用される URL - -```css -.topbanner { - background: url("topbanner.png") #00d no-repeat fixed; -} -``` - -### リストの先頭記号として使用される画像を読み込む URL - -```css -ul { - list-style: square url(http://www.example.com/redball.png); -} -``` - -### content プロパティの使用 - -#### HTML - -```html -
    -
  • Item 1
  • -
  • Item 2
  • -
  • Item 3
  • -
-``` - -#### CSS - -```css -li::after { - content: " - " url(star.gif); -} -``` - -#### 結果 - -{{EmbedLiveSample("Usage_in_the_content_property", "100%", 110)}} - -### データ URL の使用 - -#### HTML - -```html -
-``` - -#### CSS - -```css hidden -.background { - height: 100vh; -} -``` - -```css -.background { - background: yellow; - background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='90' height='45'%3E%3Cpath d='M10 10h60' stroke='%2300F' stroke-width='5'/%3E%3Cpath d='M10 20h60' stroke='%230F0' stroke-width='5'/%3E%3Cpath d='M10 30h60' stroke='red' stroke-width='5'/%3E%3C/svg%3E"); -} -``` - -#### 結果 - -{{EmbedLiveSample("Using_a_data_URL", "100%", 50)}} - -### フィルターでの使用 - -URL がフィルターへのパスとして使用される場合、 URL は以下のどちらかでなければなりません。 - -1. SVG ファイルへのパスに、追加されるフィルターの ID が付いたもの。 -2. SVG がページ内にある場合は、フィルターの ID。 +### 値 -```css -.blur { - filter: url(my-file.svg#svg-blur); /* フィルターとして使用する SVG ファイルの URL */ -} +値は以下のどちらかです。 -.inline-blur { - filter: url(#svg-blur); /* HTML ページに埋め込まれた SVG の ID */ -} -``` +- [``](/ja/docs/Web/CSS/url_function) + - : `url()` 関数は、URL のリテラル文字列のみを受け付けます。 +- `` + - : この関数は、URL 文字列または [CSS 変数](/ja/docs/Web/CSS/var)を受け取ることができます。 ## 仕様書 {{Specifications}} -## ブラウザーの互換性 - -{{Compat}} - ## 関連情報 -- {{cssxref("<gradient>")}} -- {{cssxref("element", "element()")}} -- {{cssxref("image/image", "image()")}} -- {{cssxref("image/image-set", "image-set()")}} -- {{cssxref("cross-fade", "cross-fade()")}} +- {{cssxref("url_function", "url()")}} From 9e64393ab1b0e5ebc5334f2f65c00f514ae101eb Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 20 Oct 2024 14:16:19 +0900 Subject: [PATCH 10/53] =?UTF-8?q?2024/09/29=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../web/api/window/createimagebitmap/index.md | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/files/ja/web/api/window/createimagebitmap/index.md b/files/ja/web/api/window/createimagebitmap/index.md index 9c4d597ff1db18..b9321488da32af 100644 --- a/files/ja/web/api/window/createimagebitmap/index.md +++ b/files/ja/web/api/window/createimagebitmap/index.md @@ -1,14 +1,14 @@ --- -title: createImageBitmap() +title: "Window: createImageBitmap() メソッド" +short-title: createImageBitmap() slug: Web/API/Window/createImageBitmap -original_slug: Web/API/createImageBitmap l10n: - sourceCommit: 32539676aca5ea2913cfaefeab3ba986ecd2206f + sourceCommit: 58d79e9c2206e0a604cd4d7f6fba5181262af420 --- {{APIRef("Canvas API")}} -**`createImageBitmap()`** メソッドは、指定されたソースからビットマップを作成し、オプションでそのソースの一部のみを切り抜きます。このメソッドは、ウィンドウとワーカーの両方のグローバルスコープに存在します。このメソッドは、さまざまな画像ソースを受け付け、 {{domxref("ImageBitmap")}} に解決する {{jsxref("Promise")}} を返します。 +**`createImageBitmap()`** は {{domxref("Window")}} インターフェイスのメソッドで、指定されたソースからビットマップを作成し、オプションでそのソースの一部のみを切り抜きます。このメソッドは、ウィンドウとワーカーの両方のグローバルスコープに存在します。このメソッドは、さまざまな画像ソースを受け付け、 {{domxref("ImageBitmap")}} に解決する {{jsxref("Promise")}} を返します。 ## 構文 @@ -66,6 +66,19 @@ createImageBitmap(image, sx, sy, sw, sh, options) この例では、スプライトシートをロードし、個々のスプライトを抽出し、各スプライトをキャンバスにレンダリングします。スプライトシートとは、複数の小さな画像を含む画像で、それぞれを個別にレンダリングできるようにしたいものです。 +```html hidden +元の画像: + +
+ +``` + +```css hidden +canvas { + border: 2px solid green; +} +``` + ```js const canvas = document.getElementById("myCanvas"), ctx = canvas.getContext("2d"), @@ -74,20 +87,24 @@ const canvas = document.getElementById("myCanvas"), // スプライトシートがロードされるのを待ちます image.onload = () => { Promise.all([ - // スプライトシートから2つのスプライトを切り取ります + // スプライトシートから 2 つのスプライトを切り取ります createImageBitmap(image, 0, 0, 32, 32), createImageBitmap(image, 32, 0, 32, 32), + createImageBitmap(image, 0, 0, 50, 50, { imageOrientation: "flipY" }), ]).then((sprites) => { // 各スプライトをキャンバスに描きます ctx.drawImage(sprites[0], 0, 0); ctx.drawImage(sprites[1], 32, 32); + ctx.drawImage(sprites[2], 64, 64); }); }; // 画像ファイルからスプライトシートを読み込みます -image.src = "sprites.png"; +image.src = "50x50.jpg"; ``` +{{EmbedLiveSample("Creating sprites from a sprite sheet", "100%", "250")}} + ## 仕様書 {{Specifications}} @@ -98,5 +115,6 @@ image.src = "sprites.png"; ## 関連情報 +- {{domxref("WorkerGlobalScope.createImageBitmap()")}} - {{domxref("CanvasRenderingContext2D.drawImage()")}} - {{domxref("ImageData")}} From 6aba2c14232b29fa060263a510613d87bb903d15 Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 20 Oct 2024 14:18:25 +0900 Subject: [PATCH 11/53] =?UTF-8?q?2024/09/27=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- files/ja/web/api/window/reporterror/index.md | 26 ++++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/files/ja/web/api/window/reporterror/index.md b/files/ja/web/api/window/reporterror/index.md index 102bb4b397f2bd..cadb89aaced1c8 100644 --- a/files/ja/web/api/window/reporterror/index.md +++ b/files/ja/web/api/window/reporterror/index.md @@ -1,21 +1,19 @@ --- -title: reportError() グローバル関数 +title: "Window: reportError() メソッド" +short-title: reportError() slug: Web/API/Window/reportError -original_slug: Web/API/reportError l10n: - sourceCommit: 76717f752447b6eef25bf29c12272e407ee5cb6b + sourceCommit: 63297dea804061944e7430acd2c057d773770a4f --- -{{APIRef}} {{AvailableInWorkers}} +{{APIRef("DOM")}} -**`reportError()`** グローバルメソッドは、 JavaScript の捕捉されない例外をエミュレートして、コンソールやグローバルイベントハンドラーにエラーを報告するために使用することができます。 +**`reportError()`** は {{DOMxRef("Window")}} インターフェイスのメソッドで、 JavaScript の捕捉されない例外をエミュレートして、コンソールやグローバルイベントハンドラーにエラーを報告するために使用することができます。 この機能は、主にカスタムイベント配信ライブラリーや コールバック操作ライブラリーを対象としています。 ライブラリーはこの機能を使用して、コールバックコードのエラーを捕捉し、最上位のハンドラーに投げ直すことができます。 これにより、 1 つのコールバックで例外が発生しても、他のコールバックが処理されなくなることがなくなると同時に、スタックトレース情報が最上位レベルのデバッグに利用できるようになります。 - - ## 構文 ```js-nolint @@ -41,7 +39,7 @@ reportError(throwable) このメソッドが使用できるかどうかの機能検出です。 ```js -if (typeof self.reportError === "function") { +if (typeof window.reportError === "function") { // この関数が定義されている } ``` @@ -51,14 +49,14 @@ if (typeof self.reportError === "function") { ```js const newError = new Error("エラーメッセージ", "someFile.js", 11); -self.reportError(newError); +window.reportError(newError); window.onerror = (message, source, lineno, colno, error) => { console.error(`メッセージ: ${error.message}、行番号: ${lineno}`); return true; }; -self.addEventListener("error", (error) => { +window.addEventListener("error", (error) => { console.error(error.filename); }); @@ -77,6 +75,8 @@ self.addEventListener("error", (error) => { ## 関連情報 -- [`Window`](/ja/docs/Web/API/Window#methods_implemented_from_elsewhere) -- [`WorkerGlobalScope`](/ja/docs/Web/API/WorkerGlobalScope#methods_implemented_from_elsewhere) -- [error](/ja/docs/Web/API/HTMLElement/error_event) イベント +- {{DOMxRef("Window")}} +- {{DOMxRef("WorkerGlobalScope.reportError()")}} +- {{DOMxRef("Window/error_event", "error")}} イベント +- {{DOMxRef("WorkerGlobalScope/error_event", "error")}} イベント +- {{DOMxRef("HTMLElement/error_event", "error")}} イベント From 04b5f823dca88c712d42c35596325b36c5e4d5af Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 20 Oct 2024 14:20:14 +0900 Subject: [PATCH 12/53] =?UTF-8?q?2024/09/27=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ja/web/api/window/structuredclone/index.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/files/ja/web/api/window/structuredclone/index.md b/files/ja/web/api/window/structuredclone/index.md index f2dcc6cf0c76c4..935165a336b281 100644 --- a/files/ja/web/api/window/structuredclone/index.md +++ b/files/ja/web/api/window/structuredclone/index.md @@ -1,17 +1,17 @@ --- -title: structuredClone() グローバル関数 +title: "Window: structuredClone() メソッド" +short-title: structuredClone() slug: Web/API/Window/structuredClone -original_slug: Web/API/structuredClone l10n: - sourceCommit: cb279e20569055b200f93802d1704846c28aa04f + sourceCommit: 8b6cec0ceff01e7a9d6865cf5306788e15cce4b8 --- -{{APIRef("HTML DOM")}}{{AvailableInWorkers}} +{{APIRef("HTML DOM")}} -グローバルの **`structuredClone()`** メソッドは、指定された値の[ディープコピー](/ja/docs/Glossary/Deep_copy)を、[構造化複製アルゴリズム](/ja/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)を用いて生成します。 +**`structuredClone()`** は {{domxref("Window")}} のメソッドで、指定された値の[ディープコピー](/ja/docs/Glossary/Deep_copy)を、[構造化複製アルゴリズム](/ja/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)を用いて生成します。 このメソッドでは、元の値の[移譲可能オブジェクト](/ja/docs/Web/API/Web_Workers_API/Transferable_objects)を、新しいオブジェクトにクローンするのではなく、移譲することもできます。 -移譲されたオブジェクトは元のオブジェクトから切り離され、新しいオブジェクトに装着されます。元のオブジェクトからはもうアクセスできなくなります。 +移譲されたオブジェクトは元のオブジェクトから切り離され、新しいオブジェクトに関連付けられます。元のオブジェクトからはもうアクセスできなくなります。 ## 構文 @@ -59,8 +59,7 @@ console.assert(clone.itself === clone); // 循環参照も保持されている ### 移譲される値 -[移譲可能オブジェクト](/ja/docs/Web/API/Web_Workers_API/Transferable_objects)(のみ)が複製先のオブジェクトに複製する代わりに移譲することができます。この場合、 `options` 引数の `transfer` プロパティを使用します。 -移譲により、元のオブジェクトは使用不可能になります。 +[移譲可能オブジェクト](/ja/docs/Web/API/Web_Workers_API/Transferable_objects)(のみ)が複製先のオブジェクトに複製する代わりに移譲することができます。この場合、 `options` 引数の `transfer` プロパティを使用します。移譲により、元のオブジェクトは使用不可能になります。 > [!NOTE] > これが役立つ場面として、バッファー内のデータを保存する前に非同期で検証する場合です。 @@ -112,7 +111,7 @@ console.log(mushrooms1.amanita); // ["muscaria"] ### オブジェクトの移譲 -この例では、 {{jsxref("ArrayBuffer")}} を作成し、そのバッファーがメンバーであるオブジェクトを複製し、バッファーを移譲しています。複製したオブジェクトでバッファーを使用することができますが、元のバッファを使用しようとすると例外が発生します。 +この例では、 {{jsxref("ArrayBuffer")}} を作成し、そのバッファーがメンバーであるオブジェクトを複製し、バッファーを移譲しています。複製したオブジェクトでバッファーを使用することができますが、元のバッファーを使用しようとすると例外が発生します。 ```js // バイト単位のサイズを指定して ArrayBuffer を作成 From a47a153d7ec14ce2e83a09e6c574c6630616a02e Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Fri, 25 Oct 2024 21:25:20 +0900 Subject: [PATCH 13/53] =?UTF-8?q?2024/09/23=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=20(#24158)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 2024/09/23 時点の英語版に基づき更新 * Update index.md --- .../htmlinputelement/checkvalidity/index.md | 57 +++++++- .../htmlinputelement/reportvalidity/index.md | 133 +++++++++++++++++- 2 files changed, 184 insertions(+), 6 deletions(-) diff --git a/files/ja/web/api/htmlinputelement/checkvalidity/index.md b/files/ja/web/api/htmlinputelement/checkvalidity/index.md index 6a4ac91a29668a..5b2ab8d5b55903 100644 --- a/files/ja/web/api/htmlinputelement/checkvalidity/index.md +++ b/files/ja/web/api/htmlinputelement/checkvalidity/index.md @@ -3,12 +3,15 @@ title: "HTMLInputElement: checkValidity() メソッド" short-title: checkValidity() slug: Web/API/HTMLInputElement/checkValidity l10n: - sourceCommit: a3d9f61a8990ba7b53bda9748d1f26a9e9810b18 + sourceCommit: 0a9c10fc67901972221dc7b3d006334fbfa73dce --- {{APIRef("HTML DOM")}} -**`HTMLInputElement.checkValidity()`** メソッドは、その要素の値の妥当性を示す論理値を返します。値が無効である場合、このメソッドは要素に {{domxref("HTMLInputElement/invalid_event", "invalid")}} イベントを発行します。 +**`checkValidity()`** は {{domxref("HTMLInputElement")}} インターフェイスのメソッドで、その要素が適用された[制約検証](/ja/docs/Web/HTML/Constraint_validation)ルールを満たしているかどうかを示す論理値を返します。false の場合は、メソッドは要素上で {{domxref("HTMLInputElement/invalid_event", "invalid")}} イベントも発行します。`checkValidity()` には既定でブラウザーの動作が設定されていないため、この `invalid` イベントをキャンセルしても効果はありません。 + +> [!NOTE] +> HTML の {{htmlelement("select")}} 要素で、{{domxref("HTMLInputElement.validationMessage", "validationMessage")}} が null 以外の値を持つものは不正なものと見なされ、CSS の {{cssxref(":invalid")}} 擬似クラスに一致し、`checkValidity()` が false を返すようになります。 {{domxref("HTMLInputElement.setCustomValidity()")}} メソッドを使用して、{{domxref("HTMLInputElement.validationMessage")}} を空文字列に設定すると、{{domxref("HTMLInputElement.validity", "validity")}} 状態が妥当となります。 ## 構文 @@ -22,7 +25,50 @@ checkValidity() ### 返値 -要素の値を検証して問題ない場合は `true` を、そうでなければ `false` を返します。 +要素の値に妥当性の問題がなければ `true` を返し、そうでなければ `false` を返します。 + +## 例 + +### HTML + +必須の数値フィールドと、フォームのチェックボタンと送信ボタンの 2 つのボタンを設置したフォームを設置します。 + +```html + +

+ + +

+

+ + +

+

+ +``` + +### JavaScript + +```js +const output = document.querySelector("#log"); +const checkButton = document.querySelector("#check"); +const ageInput = document.querySelector("#age"); + +ageInput.addEventListener("invalid", () => { + console.log("invalid イベントが発行されました。"); +}); + +checkButton.addEventListener("click", () => { + const checkVal = ageInput.checkValidity(); + output.innerHTML = `checkValidity が ${checkVal} を返しました。`; +}); +``` + +### 結果 + +{{EmbedLiveSample("Examples", "100%", 220)}} + +`false` の場合、値が未入力、21 未満、65 超、または無効な場合、invalid イベントがコンソールに記録されます。ユーザーにエラーを報告するには、代わりに {{domxref("HTMLInputElement.reportValidity()")}} を使用してください。 ## 仕様書 @@ -34,6 +80,9 @@ checkValidity() ## 関連情報 -- [reportValidity](/ja/docs/Web/API/HTMLInputElement/reportValidity) +- {{domxref("HTMLInputElement.reportValidity()")}} +- {{HTMLElement("input")}} +- {{HTMLElement("form")}} - [学習: クライアント側フォーム検証](/ja/docs/Learn/Forms/Form_validation) - [ガイド: 制約検証](/ja/docs/Web/HTML/Constraint_validation) +- CSS の {{cssxref(":valid")}} および {{cssxref(":invalid")}} 擬似クラス diff --git a/files/ja/web/api/htmlinputelement/reportvalidity/index.md b/files/ja/web/api/htmlinputelement/reportvalidity/index.md index 6d0704664e8ef1..ba531f238be7aa 100644 --- a/files/ja/web/api/htmlinputelement/reportvalidity/index.md +++ b/files/ja/web/api/htmlinputelement/reportvalidity/index.md @@ -3,7 +3,7 @@ title: "HTMLInputElement: reportValidity() メソッド" short-title: reportValidity() slug: Web/API/HTMLInputElement/reportValidity l10n: - sourceCommit: a3d9f61a8990ba7b53bda9748d1f26a9e9810b18 + sourceCommit: 0a9c10fc67901972221dc7b3d006334fbfa73dce --- {{APIRef("HTML DOM")}} @@ -24,6 +24,132 @@ reportValidity() 要素を検証して問題がなければ `true` を返し、それ以外の場合は `false` を返します。 +## 例 + +### 基本的な使用 + +#### HTML + +必須の数値フィールドと、フォームのチェックボタンと送信ボタンの 2 つのボタンを設置したフォームを設置します。 + +```html +
+

+ + +

+

+ + +

+

+
+``` + +#### JavaScript + +"reportValidity()" ボタンが押された場合、`reportValidity()` メソッドを使用して、入力値が制約を満たしているかどうかを確認します。返値をログに記録します。`false` の場合、検証メッセージも表示し、`invalid` イベントを捕捉します。 + +```js +const output = document.querySelector("#log"); +const reportButton = document.querySelector("#report"); +const ageInput = document.querySelector("#age"); + +ageInput.addEventListener("invalid", () => { + console.log("invalid イベントが発行されました。"); +}); + +reportButton.addEventListener("click", () => { + const reportVal = ageInput.reportValidity(); + output.innerHTML = `"reportValidity()" の返値: ${reportVal}`; + if (!reportVal) { + output.innerHTML += `
検証メッセージ: "${ageInput.validationMessage}"`; + } +}); +``` + +#### 結果 + +{{EmbedLiveSample("基本的な使用", "100%", 120)}} + +`false` の場合、値が未入力、21 未満、65 超、または無効な場合、invalid イベントがコンソールに記録されます。 + +### 独自のエラーメッセージ + +この例は、独自のエラーメッセージが、値が有効であるにもかかわらず、`false` の返値を引き起こす可能性があることを示しています。 + +#### HTML + +前の例の HTML に[問題を修正]ボタンを追加します。 + +```html-nolint hidden +
+

+ + +

+

+ + +``` + +```html + +``` + +```html-nolint hidden +

+

+
+``` + +#### JavaScript + +上記の基本例の JavaScript を拡張し、{{domxref("HTMLInputElement.setCustomValidity()")}} メソッドを使用して独自のエラーメッセージを提供する関数を追加します。 `validateAge()` 関数は、入力が有効であり、`enableValidation` 変数が `true` の場合にのみエラーメッセージを空文字列に設定します。ただし、`enableValidation` は[問題を修正]ボタンが押されるまでは `false` になります。 + +```js +const output = document.querySelector("#log"); +const reportButton = document.querySelector("#report"); +const ageInput = document.querySelector("#age"); +const fixButton = document.querySelector("#fix"); +let enableValidation = false; + +fixButton.addEventListener("click", (e) => { + enableValidation = true; + fixButton.innerHTML = "エラーを修正しました"; + fixButton.disabled = true; +}); + +reportButton.addEventListener("click", () => { + validateAge(); + const reportVal = ageInput.reportValidity(); + output.innerHTML = `"reportValidity()" の返値: ${reportVal}`; + if (!reportVal) { + output.innerHTML += `
検証メッセージ: "${ageInput.validationMessage}"`; + } +}); + +const validateAge = () => { + const validityState_object = ageInput.validity; + if (validityState_object.valueMissing) { + ageInput.setCustomValidity("年齢を入力してください(必須)"); + } else if (ageInput.rangeUnderflow) { + ageInput.setCustomValidity("値が小さすぎます"); + } else if (ageInput.rangeOverflow) { + ageInput.setCustomValidity("値が大きすぎます"); + } else if (enableValidation) { + // 有効でかつ enableValidation が true に設定されている場合は true + ageInput.setCustomValidity(""); + } +}; +``` + +#### 結果 + +{{EmbedLiveSample("独自のエラーメッセージ", "100%", 120)}} + +年齢を入力する前に[reportValidity()]ボタンを起動すると、`required` の制約検証を満たさないため、`reportValidity()` メソッドは `false` を返します。このメソッドは入力に対して `invalid` イベントを発生させ、ユーザーに問題を報告し、独自のエラーメッセージ「年齢を入力してください(必須)」を表示します。独自のエラーメッセージが設定されている限り、[reportValidity()]ボタンを起動すると、有効な年齢を選択してもエラーが表示され続けます。検証を有効にするには、独自のエラーメッセージを空文字列に設定する必要があります。これは、[問題を修正]ボタンをクリックすることで行います。 + ## 仕様書 {{Specifications}} @@ -34,6 +160,9 @@ reportValidity() ## 関連情報 -- [checkValidity](/ja/docs/Web/API/HTMLInputElement/checkValidity) +- {{domxref("HTMLInputElement.checkValidity()")}} +- {{HTMLElement("input")}} +- {{HTMLElement("form")}} - [学習: クライアント側フォーム検証](/ja/docs/Learn/Forms/Form_validation) - [ガイド: 制約検証](/ja/docs/Web/HTML/Constraint_validation) +- CSS の {{cssxref(":valid")}} および {{cssxref(":invalid")}} 擬似クラス From 8809e9ea36e6804e1107a0ea753e95a8c30ea773 Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 20 Oct 2024 20:27:55 +0900 Subject: [PATCH 14/53] =?UTF-8?q?2024/10/11=20=E6=99=82=E7=82=B9=E3=81=AE?= =?UTF-8?q?=E8=8B=B1=E8=AA=9E=E7=89=88=E3=81=AB=E5=9F=BA=E3=81=A5=E3=81=8D?= =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- files/ja/web/html/element/label/index.md | 46 ++++++++++++------------ 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/files/ja/web/html/element/label/index.md b/files/ja/web/html/element/label/index.md index e8c6b24592a68c..1125fb2bf65868 100644 --- a/files/ja/web/html/element/label/index.md +++ b/files/ja/web/html/element/label/index.md @@ -2,7 +2,7 @@ title: "